Tizen 2.0 Release tizen_2.0 accepted/tizen_2.0/20130215.203808 submit/tizen_2.0/20130215.191733
authorHyungKyu Song <hk76.song@samsung.com>
Fri, 15 Feb 2013 15:13:58 +0000 (00:13 +0900)
committerHyungKyu Song <hk76.song@samsung.com>
Fri, 15 Feb 2013 15:13:58 +0000 (00:13 +0900)
150 files changed:
CMakeLists.txt
LICENSE.APLv2 [new file with mode: 0644]
LICENSE.BSD [new file with mode: 0644]
NOTICE [new file with mode: 0644]
email-api/CMakeLists.txt [new file with mode: 0755]
email-api/email-api-account.c [new file with mode: 0755]
email-api/email-api-etc.c [new file with mode: 0755]
email-api/email-api-init.c [new file with mode: 0755]
email-api/email-api-mail.c [new file with mode: 0755]
email-api/email-api-mailbox.c [new file with mode: 0755]
email-api/email-api-network.c [new file with mode: 0755]
email-api/email-api-rule.c [new file with mode: 0755]
email-api/email-api-smime.c [new file with mode: 0755]
email-api/include/email-api-account.h [new file with mode: 0755]
email-api/include/email-api-etc.h [new file with mode: 0755]
email-api/include/email-api-init.h [new file with mode: 0755]
email-api/include/email-api-mail.h [new file with mode: 0755]
email-api/include/email-api-mailbox.h [new file with mode: 0755]
email-api/include/email-api-network.h [new file with mode: 0755]
email-api/include/email-api-rule.h [new file with mode: 0755]
email-api/include/email-api-smime.h [new file with mode: 0755]
email-api/include/email-api.h [new file with mode: 0755]
email-common-use/CMakeLists.txt [new file with mode: 0755]
email-common-use/email-convert.c [new file with mode: 0755]
email-common-use/email-utilities.c [new file with mode: 0755]
email-common-use/include/email-convert.h [new file with mode: 0755]
email-common-use/include/email-debug-log.h [new file with mode: 0755]
email-common-use/include/email-errors.h [new file with mode: 0755]
email-common-use/include/email-internal-types.h [new file with mode: 0755]
email-common-use/include/email-types.h [new file with mode: 0755]
email-common-use/include/email-utilities.h [new file with mode: 0755]
email-common-use/include/tpl.h [new file with mode: 0755]
email-common-use/tpl.c [new file with mode: 0644]
email-core/CMakeLists.txt
email-core/email-core-account.c [new file with mode: 0755]
email-core/email-core-api.c [new file with mode: 0755]
email-core/email-core-cert.c [new file with mode: 0755]
email-core/email-core-event.c [new file with mode: 0755]
email-core/email-core-global.c [new file with mode: 0755]
email-core/email-core-imap-idle.c [new file with mode: 0755]
email-core/email-core-imap-mailbox.c [new file with mode: 0755]
email-core/email-core-mail.c [new file with mode: 0755]
email-core/email-core-mailbox-sync.c [new file with mode: 0755]
email-core/email-core-mailbox.c [new file with mode: 0755]
email-core/email-core-mime.c [new file with mode: 0755]
email-core/email-core-mm-callbacks.c [new file with mode: 0755]
email-core/email-core-signal.c [new file with mode: 0755]
email-core/email-core-smime.c [new file with mode: 0755]
email-core/email-core-smtp.c [new file with mode: 0755]
email-core/email-core-sound.c [new file with mode: 0755]
email-core/email-core-task-manager.c [new file with mode: 0755]
email-core/email-core-tasks.c [new file with mode: 0755]
email-core/email-core-timer.c [new file with mode: 0755]
email-core/email-core-utils.c [new file with mode: 0755]
email-core/email-device/email-device.c [new file with mode: 0755]
email-core/email-device/include/email-device.h [new file with mode: 0755]
email-core/email-network/email-network.c [new file with mode: 0755]
email-core/email-network/include/email-network.h [new file with mode: 0755]
email-core/email-storage/email-storage.c [new file with mode: 0755]
email-core/email-storage/include/email-storage.h [new file with mode: 0755]
email-core/include/email-core-account.h [new file with mode: 0755]
email-core/include/email-core-api.h [new file with mode: 0755]
email-core/include/email-core-cert.h [new file with mode: 0644]
email-core/include/email-core-event.h [new file with mode: 0755]
email-core/include/email-core-global.h [new file with mode: 0755]
email-core/include/email-core-imap-idle.h [new file with mode: 0755]
email-core/include/email-core-imap-mailbox.h [new file with mode: 0755]
email-core/include/email-core-mail.h [new file with mode: 0755]
email-core/include/email-core-mailbox-sync.h [new file with mode: 0755]
email-core/include/email-core-mailbox.h [new file with mode: 0755]
email-core/include/email-core-mime.h [new file with mode: 0755]
email-core/include/email-core-signal.h [new file with mode: 0755]
email-core/include/email-core-smime.h [new file with mode: 0755]
email-core/include/email-core-smtp.h [new file with mode: 0755]
email-core/include/email-core-sound.h [new file with mode: 0755]
email-core/include/email-core-task-manager.h [new file with mode: 0755]
email-core/include/email-core-tasks.h [new file with mode: 0755]
email-core/include/email-core-timer.h [new file with mode: 0755]
email-core/include/email-core-utils.h [new file with mode: 0755]
email-daemon/CMakeLists.txt [new file with mode: 0755]
email-daemon/email-daemon-account.c [new file with mode: 0755]
email-daemon/email-daemon-auto-poll.c [new file with mode: 0755]
email-daemon/email-daemon-emn.c [new file with mode: 0755]
email-daemon/email-daemon-etc.c [new file with mode: 0755]
email-daemon/email-daemon-init.c [new file with mode: 0755]
email-daemon/email-daemon-mail.c [new file with mode: 0755]
email-daemon/email-daemon-mailbox.c [new file with mode: 0755]
email-daemon/include/.gitignore [new file with mode: 0644]
email-daemon/include/email-daemon-account.h [new file with mode: 0755]
email-daemon/include/email-daemon-auto-poll.h [new file with mode: 0755]
email-daemon/include/email-daemon-emn.h [new file with mode: 0755]
email-daemon/include/email-daemon-init.h [new file with mode: 0755]
email-daemon/include/email-daemon-mutex.h [new file with mode: 0755]
email-daemon/include/email-daemon.h [new file with mode: 0755]
email-daemon/main.c [new file with mode: 0755]
email-ipc/CMakeLists.txt [new file with mode: 0755]
email-ipc/email-activation/email-dbus-activation.c [new file with mode: 0755]
email-ipc/email-activation/email-service.service [new file with mode: 0755]
email-ipc/email-activation/email-service.xml [new file with mode: 0755]
email-ipc/email-activation/include/email-dbus-activation.h [new file with mode: 0755]
email-ipc/email-ipc-api.c [new file with mode: 0755]
email-ipc/email-ipc-api/email-ipc-api-info.c [new file with mode: 0755]
email-ipc/email-ipc-api/email-ipc-param-list.c [new file with mode: 0755]
email-ipc/email-ipc-api/email-ipc-param.c [new file with mode: 0755]
email-ipc/email-ipc-api/include/email-ipc-api-info.h [new file with mode: 0755]
email-ipc/email-ipc-api/include/email-ipc-param-list.h [new file with mode: 0755]
email-ipc/email-ipc-api/include/email-ipc-param.h [new file with mode: 0755]
email-ipc/email-ipc-build.c [new file with mode: 0755]
email-ipc/email-ipc-proxy.c [new file with mode: 0755]
email-ipc/email-ipc-stub.c [new file with mode: 0755]
email-ipc/email-proxy/email-proxy-callback-info.c [new file with mode: 0755]
email-ipc/email-proxy/email-proxy-main.c [new file with mode: 0755]
email-ipc/email-proxy/email-proxy-socket.c [new file with mode: 0644]
email-ipc/email-proxy/include/email-proxy-callback-info.h [new file with mode: 0755]
email-ipc/email-proxy/include/email-proxy-main.h [new file with mode: 0755]
email-ipc/email-proxy/include/email-proxy-socket.h [new file with mode: 0755]
email-ipc/email-socket/email-ipc-socket.c [new file with mode: 0755]
email-ipc/email-socket/include/email-ipc-socket.h [new file with mode: 0755]
email-ipc/email-stub/email-stub-main.c [new file with mode: 0755]
email-ipc/email-stub/email-stub-socket.c [new file with mode: 0755]
email-ipc/email-stub/email-stub-task-manager.c [new file with mode: 0755]
email-ipc/email-stub/email-stub-task.c [new file with mode: 0755]
email-ipc/email-stub/include/email-stub-main.h [new file with mode: 0755]
email-ipc/email-stub/include/email-stub-socket.h [new file with mode: 0755]
email-ipc/email-stub/include/email-stub-task-manager.h [new file with mode: 0755]
email-ipc/email-stub/include/email-stub-task.h [new file with mode: 0755]
email-ipc/include/email-ipc-build.h [new file with mode: 0755]
email-ipc/include/email-ipc.h [new file with mode: 0755]
email-service.manifest [new file with mode: 0644]
email-service.pc.in
email-service_PG.h [new file with mode: 0755]
packaging/email-service.spec [changed mode: 0644->0755]
packaging/email.service [new file with mode: 0644]
res/Q02_Notification_email.png [new file with mode: 0755]
utilities/CMakeLists.txt
utilities/test-application/include/testapp-account.h [new file with mode: 0755]
utilities/test-application/include/testapp-mail.h [new file with mode: 0755]
utilities/test-application/include/testapp-mailbox.h [new file with mode: 0755]
utilities/test-application/include/testapp-others.h [new file with mode: 0755]
utilities/test-application/include/testapp-rule.h [new file with mode: 0755]
utilities/test-application/include/testapp-thread.h [new file with mode: 0755]
utilities/test-application/include/testapp-utility.h [new file with mode: 0755]
utilities/test-application/main.c [new file with mode: 0755]
utilities/test-application/testapp-account.c [new file with mode: 0755]
utilities/test-application/testapp-mail.c [new file with mode: 0755]
utilities/test-application/testapp-mailbox.c [new file with mode: 0755]
utilities/test-application/testapp-others.c [new file with mode: 0755]
utilities/test-application/testapp-rule.c [new file with mode: 0755]
utilities/test-application/testapp-thread.c [new file with mode: 0755]
utilities/test-application/testapp-utility.c [new file with mode: 0755]

index 123b582..020dace 100755 (executable)
@@ -17,12 +17,12 @@ MESSAGE(">>> Build type: ${CMAKE_BUILD_TYPE}")
 ##########################################################
 # Define BASE LIB
 ##########################################################
-ADD_SUBDIRECTORY(Common)
+ADD_SUBDIRECTORY(email-common-use)
 
 #########################################################
 # Define IPC
 ##########################################################
-ADD_SUBDIRECTORY(ipc)
+ADD_SUBDIRECTORY(email-ipc)
 
 ##########################################################
 # Define STORAGE, NETWORK, CORE lib
@@ -34,13 +34,13 @@ ADD_SUBDIRECTORY(email-core)
 # Define Email API   
 ##########################################################
 
-ADD_SUBDIRECTORY(MAPI)
+ADD_SUBDIRECTORY(email-api)
 
 ##########################################################
 # Define Execute File
 ##########################################################
 
-ADD_SUBDIRECTORY(email-engine)
+ADD_SUBDIRECTORY(email-daemon)
 
 ##########################################################
 # Define Test App
@@ -49,20 +49,13 @@ ADD_SUBDIRECTORY(email-engine)
 ADD_SUBDIRECTORY(utilities)
 
 ##########################################################
-# Define locale
-##########################################################
-
-ADD_SUBDIRECTORY(po)
-
-##########################################################
 # Define Install Files
 ##########################################################
 
 CONFIGURE_FILE(email-service.pc.in email-service.pc @ONLY)
 INSTALL(FILES ${CMAKE_BINARY_DIR}/email-service.pc DESTINATION lib/pkgconfig) 
-INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config/.email-service.db DESTINATION /opt/dbspace)
-INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config/.email-service.db-journal DESTINATION /opt/dbspace)
 
-#SET(RC_LOCAL_SCRIPT email-service)
-#INSTALL(PROGRAMS ${RC_LOCAL_SCRIPT} DESTINATION /etc/rc.d/init.d)
+# LICENSE file
+INSTALL(FILES ${CMAKE_SOURCE_DIR}/LICENSE.BSD DESTINATION /usr/share/license/email-service/LICENSE)
 
+INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/res/ DESTINATION /opt/usr/data/email/res/image FILES_MATCHING PATTERN "*.png")
diff --git a/LICENSE.APLv2 b/LICENSE.APLv2
new file mode 100644 (file)
index 0000000..74f474e
--- /dev/null
@@ -0,0 +1,203 @@
+Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/LICENSE.BSD b/LICENSE.BSD
new file mode 100644 (file)
index 0000000..b68368e
--- /dev/null
@@ -0,0 +1,20 @@
+Copyright (c) 2005-2010, Troy D. Hanson     http://tpl.sourceforge.net
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/NOTICE b/NOTICE
new file mode 100644 (file)
index 0000000..17c17d4
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,7 @@
+Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+Except as noted, this software is licensed under Apache License, Version 2.
+Please, see the LICENSE.APLv2 file for Apache License, Version 2 terms and conditions.
+tpl.c and tpl.h are licensed under BSD license.
+Please, see copyright and license comments section in the header of each file,
+and the LICENSE.BSD file for BSD License terms and conditions.
diff --git a/email-api/CMakeLists.txt b/email-api/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..6af6cf7
--- /dev/null
@@ -0,0 +1,80 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(email-api)
+
+SET(CMAKE_SKIP_BUILD_RPATH TRUE)
+
+IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+       SET(CMAKE_BUILD_TYPE "Debug")
+ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+
+MESSAGE("")
+MESSAGE(">>> current directory: ${CMAKE_CURRENT_SOURCE_DIR}")
+MESSAGE(">>> Build type: ${CMAKE_BUILD_TYPE}")
+
+
+SET(VISIBILITY "-DEXPORT_API=\"__attribute__((visibility(\\\"default\\\")))\"")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden")
+
+##########################################################
+# Define Email API   
+##########################################################
+
+SET(API-LIB "email-api")
+SET(API-SRCS 
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-account.c
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-mail.c
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-network.c
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-rule.c
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-mailbox.c
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-init.c
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-smime.c
+       ${CMAKE_SOURCE_DIR}/email-api/email-api-etc.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/email-daemon/include
+       ${CMAKE_SOURCE_DIR}/email-api/include
+       ${CMAKE_SOURCE_DIR}/email-api/socket/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/include
+       ${CMAKE_SOURCE_DIR}/email-core/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(api_pkgs REQUIRED glib-2.0 dlog dbus-1 vconf db-util contacts-service2 uw-imap-toolkit) 
+
+FOREACH(flag ${api_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${API-LIB} SHARED ${API-SRCS})
+
+TARGET_LINK_LIBRARIES(${API-LIB} ${api_pkgs_LDFLAGS} email-ipc email-storage email-core email-common-use email-network)
+#${NETWORK-LIB} ${CORE-LIB} ${STORAGE-LIB} ${IPC-LIB} ${COMMON-LIB})
+
+SET_TARGET_PROPERTIES(${API-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${API-LIB} PROPERTIES VERSION ${VERSION})
+
+INSTALL(TARGETS ${API-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
+SET(EMAIL-API-HEADERS
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api.h
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-account.h
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-init.h
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-mail.h
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-mailbox.h
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-network.h
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-rule.h
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-etc.h
+       ${CMAKE_SOURCE_DIR}/email-api/include/email-api-smime.h
+       ${CMAKE_SOURCE_DIR}/email-common-use/include/email-types.h
+       ${CMAKE_SOURCE_DIR}/email-common-use/include/email-errors.h
+)
+
+INSTALL(FILES ${EMAIL-API-HEADERS} DESTINATION include/email-service)
+
diff --git a/email-api/email-api-account.c b/email-api/email-api-account.c
new file mode 100755 (executable)
index 0000000..3acfd66
--- /dev/null
@@ -0,0 +1,692 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-account.c
+ * @brief              This file contains the data structures and interfaces of Account related Functionality provided by
+ *                     email-service .
+ */
+
+#include "email-api.h"
+#include "string.h"
+#include "email-convert.h"
+#include "email-api-account.h"
+#include "email-storage.h"
+#include "email-core-mail.h"
+#include "email-core-account.h"
+#include "email-core-utils.h"
+#include "email-utilities.h"
+#include "email-ipc.h"
+
+/* API - Adds the Email Account */
+EXPORT_API int email_add_account(email_account_t* account)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p]", account);
+       char* local_account_stream = NULL;
+       int size = 0;
+       int err = EMAIL_ERROR_NONE;
+       int ret_from_ipc = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = NULL;
+
+       if ( !account )  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       /* composing account information to be added */
+       hAPI = emipc_create_email_api(_EMAIL_API_ADD_ACCOUNT);
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       local_account_stream = em_convert_account_to_byte_stream(account, &size);
+       EM_PROXY_IF_NULL_RETURN_VALUE(local_account_stream, hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       if(!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, local_account_stream, size)) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+       EM_DEBUG_LOG("APPID[%d], APIID [%d]", emipc_get_app_id(hAPI), emipc_get_api_id(hAPI));
+
+       /* passing account information to service */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       /* get result from service */
+       if( (ret_from_ipc = emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_get_parameter failed [%d]", ret_from_ipc);
+               err = ret_from_ipc;
+               goto FINISH_OFF;
+       }
+
+       if(err == EMAIL_ERROR_NONE) {
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &account->account_id);
+       }
+       else {  /*  get error code */
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err);
+       }
+
+FINISH_OFF:
+
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_free_account(email_account_t** account_list, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("account_list[%p], count[%d]", account_list, count);
+
+       /*  default variable */
+       int err = EMAIL_ERROR_NONE;
+
+       if (count > 0)  {
+               if (!account_list || !*account_list)  {
+                       err = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+               email_account_t* p = *account_list;
+               int i;
+
+               for (i = 0; i < count; i++)  {
+                       EM_SAFE_FREE(p[i].account_name);
+                       EM_SAFE_FREE(p[i].incoming_server_address);
+                       EM_SAFE_FREE(p[i].user_email_address);
+                       EM_SAFE_FREE(p[i].incoming_server_user_name);
+                       EM_SAFE_FREE(p[i].incoming_server_password);
+                       EM_SAFE_FREE(p[i].outgoing_server_address);
+                       EM_SAFE_FREE(p[i].outgoing_server_user_name);
+                       EM_SAFE_FREE(p[i].outgoing_server_password);
+                       EM_SAFE_FREE(p[i].user_display_name);
+                       EM_SAFE_FREE(p[i].reply_to_address);
+                       EM_SAFE_FREE(p[i].return_address);
+                       EM_SAFE_FREE(p[i].logo_icon_path);
+                       EM_SAFE_FREE(p[i].user_data);
+                       p[i].user_data_length = 0;
+                       EM_SAFE_FREE(p[i].options.display_name_from);
+                       EM_SAFE_FREE(p[i].options.signature);
+               }
+               free(p); *account_list = NULL;
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       return err;
+}
+
+
+/* API - Delete  the Email Account */
+EXPORT_API int email_delete_account(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d]", account_id);
+
+       int ret = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       if (account_id < 0 || account_id == 0)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d]", account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_DELETE_ACCOUNT);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter account_id  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &ret);
+       if(ret != EMAIL_ERROR_NONE) {   /*  get error code */
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err);
+       }
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("RETURN VALUE [%d], ERROR CODE [%d]", ret, err);
+       return err;
+}
+
+/* API - Update  the Email Account */
+EXPORT_API int email_update_account(int account_id, email_account_t* new_account)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], new_account[%p]", account_id, new_account);
+
+       int ret = 0;
+       int size = 0;
+       int err = EMAIL_ERROR_NONE;
+       int with_validation = false;
+       char* new_account_stream = NULL;
+
+       if ( account_id <= 0 || !new_account )  { /*prevent 23138*/
+               EM_DEBUG_EXCEPTION("account_id[%d], new_account[%p], with_validation[%d]", account_id, new_account, with_validation);
+               return  EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_UPDATE_ACCOUNT);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter account_id failed ");
+               goto FINISH_OFF;
+       }
+
+       /* new_account */
+       new_account_stream = em_convert_account_to_byte_stream(new_account, &size);
+       EM_PROXY_IF_NULL_RETURN_VALUE(new_account_stream, hAPI, EMAIL_ERROR_NULL_VALUE);
+       if(!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, new_account_stream, size)) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter new_account failed ");
+               goto FINISH_OFF;
+       }
+
+       /* with_validation */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&with_validation, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter with_validation failed ");
+               goto FINISH_OFF;
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &ret);
+       if(ret != EMAIL_ERROR_NONE) {
+               /*  get error code */
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err);
+       }
+
+FINISH_OFF:
+
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("RETURN VALUE [%d], ERROR CODE [%d]", ret, err);
+       return err;
+}
+
+/* API - Update  the Email Account */
+EXPORT_API int email_update_account_with_validation(int account_id, email_account_t* new_account)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], new_account[%p]", account_id, new_account);
+
+       int ret = 0;
+       int size = 0;
+       int err = EMAIL_ERROR_NONE;
+       int with_validation = true;
+       char* new_account_stream = NULL;
+
+       if ((account_id <= 0) || !new_account || (with_validation != false && with_validation != true))  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], new_account[%p], with_validation[%d]", account_id, new_account, with_validation);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_UPDATE_ACCOUNT);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("email_update_account--emipc_add_parameter account_id  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* new_account */
+       new_account_stream = em_convert_account_to_byte_stream(new_account, &size);
+       EM_PROXY_IF_NULL_RETURN_VALUE(new_account_stream, hAPI, EMAIL_ERROR_NULL_VALUE);
+       if(!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, new_account_stream, size)) {
+               EM_DEBUG_EXCEPTION("email_update_account--emipc_add_parameter new_account  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* with_validation */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&with_validation, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("email_update_account--emipc_add_parameter with_validation  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("email_update_account--emipc_execute_proxy_api failed ");
+               /* Prevent defect 18624 */
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &ret);
+       if(ret != EMAIL_ERROR_NONE) {   /*  get error code */
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err);
+       }
+
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("RETURN VALUE [%d], ERROR CODE [%d]", ret, err);
+       return err;
+}
+
+
+/* API - Get the account Information based on the account ID */
+EXPORT_API int email_get_account(int account_id, int pulloption, email_account_t** account)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = 0;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *account_tbl = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(account, EMAIL_ERROR_INVALID_PARAM);
+
+       if (pulloption == GET_FULL_DATA)
+               pulloption = EMAIL_ACC_GET_OPT_FULL_DATA;
+
+       if (pulloption & EMAIL_ACC_GET_OPT_PASSWORD) {
+               pulloption = pulloption & (~(EMAIL_ACC_GET_OPT_PASSWORD));      /*  disable password -Can't obtain password by MAPI */
+               EM_DEBUG_LOG("change pulloption : disable password");
+       }
+
+       if (!emstorage_get_account_by_id(account_id, pulloption, &account_tbl, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed - %d", err);
+               goto FINISH_OFF;
+       }
+
+       *account = em_malloc(sizeof(email_account_t));
+       if (!*account) {
+               EM_DEBUG_EXCEPTION("allocation failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       memset((void*)*account, 0, sizeof(email_account_t));
+       em_convert_account_tbl_to_account(account_tbl, *account);
+
+
+       ret = true;
+
+FINISH_OFF:
+       if (account_tbl)
+               emstorage_free_account(&account_tbl, 1, NULL);
+
+       EM_DEBUG_FUNC_END();
+       return err;
+}
+
+EXPORT_API int email_get_account_list(email_account_t** account_list, int* count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE, i = 0;
+       emstorage_account_tbl_t *temp_account_tbl = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(account_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_get_account_list(count, &temp_account_tbl , true, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if(temp_account_tbl && (*count) > 0) {
+               *account_list = em_malloc(sizeof(email_account_t) * (*count));
+               if(!*account_list) {
+                       EM_DEBUG_EXCEPTION("allocation failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               memset((void*)*account_list, 0, sizeof(email_account_t) * (*count));
+               for(i = 0; i < (*count); i++)
+                       em_convert_account_tbl_to_account(temp_account_tbl + i, (*account_list) + i);
+       }
+
+FINISH_OFF:
+
+
+       if(temp_account_tbl)
+               emstorage_free_account(&temp_account_tbl, (*count), NULL);
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+
+}
+
+EXPORT_API int email_validate_account(int account_id, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], handle[%p]", account_id, handle);
+
+       int ret = 0;
+       int err = EMAIL_ERROR_NONE;
+       if (account_id <= 0)  {
+               EM_DEBUG_EXCEPTION("account_id[%d]", account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_VALIDATE_ACCOUNT);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter account_id  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION(" emipc_execute_proxy_api failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &ret); /*  return  */
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err); /*  error code */
+
+       if(handle)
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 2, sizeof(int), handle);
+
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+
+}
+
+
+EXPORT_API int email_add_account_with_validation(email_account_t* account, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p]", account);
+       char* local_account_stream = NULL;
+       int ret = -1;
+       int size = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(account, false);
+
+       if(emstorage_check_duplicated_account(account, true, &err) == false) {
+               EM_DEBUG_EXCEPTION("emstorage_check_duplicated_account failed (%d) ", err);
+               return err;
+       }
+
+       /* create account information */
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_ADD_ACCOUNT_WITH_VALIDATION);
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       local_account_stream = em_convert_account_to_byte_stream(account, &size);
+       EM_PROXY_IF_NULL_RETURN_VALUE(local_account_stream, hAPI, EMAIL_ERROR_NULL_VALUE);
+       if(!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, local_account_stream, size)) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION(" emipc_execute_proxy_api failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &ret);
+       if(ret == EMAIL_ERROR_NONE) {
+               if(handle)
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+       } else {
+               /*  get error code */
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err);
+       }
+
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_backup_accounts_into_secure_storage(const char *file_name)
+{
+       EM_DEBUG_FUNC_BEGIN("file_name[%s]", file_name);
+       int ret = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!file_name)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_BACKUP_ACCOUNTS);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* file_name */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)file_name, EM_SAFE_STRLEN(file_name)+1)) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter account_id  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION(" emipc_execute_proxy_api failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &ret);
+
+       if(0 == ret) {  /*  get error code */
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err);
+       }
+
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+EXPORT_API int email_restore_accounts_from_secure_storage(const char * file_name)
+{
+       EM_DEBUG_FUNC_BEGIN("file_name[%s]", file_name);
+       int ret = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!file_name)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_RESTORE_ACCOUNTS);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* file_name */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)file_name, EM_SAFE_STRLEN(file_name)+1)) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter account_id  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION(" emipc_execute_proxy_api failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &ret);
+
+       if(0==ret) {    /*  get error code */
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err);
+       }
+
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_password_length_of_account(const int account_id, int *password_length)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], password_length[%p]", account_id, password_length);
+       int ret = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       if (account_id <= 0 || password_length == NULL)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_GET_PASSWORD_LENGTH_OF_ACCOUNT);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter account_id  failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION(" emipc_execute_proxy_api failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &ret);
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &err);
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 2, sizeof(int), password_length);
+
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("*password_length[%d]", *password_length);
+       return err;
+}
+
+EXPORT_API int email_query_server_info(const char* domain_name, email_server_info_t **result_server_info)
+{
+       EM_DEBUG_FUNC_BEGIN("domain_name [%s], result_server_info [%p]", domain_name, result_server_info);
+       int err = EMAIL_ERROR_NONE;
+
+       if (!domain_name || !result_server_info)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       err = emcore_query_server_info(domain_name, result_server_info);
+
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_free_server_info(email_server_info_t **result_server_info)
+{
+       EM_DEBUG_FUNC_BEGIN("result_server_info [%p]", result_server_info);
+       int err = EMAIL_ERROR_NONE;
+
+       if (!result_server_info)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       err = emcore_free_server_info(result_server_info);
+
+       EM_DEBUG_FUNC_END("ret[%d]", err);
+       return err;
+}
+
+EXPORT_API int email_update_notification_bar(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d]", account_id);
+       int err = EMAIL_ERROR_NONE;
+
+       if (account_id == 0)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_UPDATE_NOTIFICATION_BAR_FOR_UNREAD_MAIL);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION(" emipc_add_parameter account_id  failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION(" emipc_execute_proxy_api failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("ret[%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_clear_all_notification_bar()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+
+       err = emcore_clear_all_notifications();
+
+       EM_DEBUG_FUNC_END("ret[%d]", err);
+       return err;
+}
+
+EXPORT_API int email_save_default_account_id(int input_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d]", input_account_id);
+       int err = EMAIL_ERROR_NONE;
+
+       err = emcore_save_default_account_id(input_account_id);
+
+       EM_DEBUG_FUNC_END("ret[%d]", err);
+       return err;
+}
+
+EXPORT_API int email_load_default_account_id(int *output_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("output_account_id [%p]", output_account_id);
+       int err = EMAIL_ERROR_NONE;
+
+       err = emcore_load_default_account_id(output_account_id);
+
+       EM_DEBUG_FUNC_END("ret[%d]", err);
+       return err;
+}
diff --git a/email-api/email-api-etc.c b/email-api/email-api-etc.c
new file mode 100755 (executable)
index 0000000..258dd6a
--- /dev/null
@@ -0,0 +1,214 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-etc.c
+ * @brief              This file contains the data structures and interfaces of functionalities provided by email-service .
+ */
+
+#include "email-api.h"
+#include "email-types.h"
+#include "email-ipc.h"
+#include "email-debug-log.h"
+#include "email-core-utils.h"
+#include "email-core-smtp.h"
+#include "email-core-mime.h"
+#include "email-convert.h"
+#include "email-utilities.h"
+
+EXPORT_API int email_show_user_message(int id, email_action_t action, int error_code)
+{
+       EM_DEBUG_FUNC_BEGIN("id [%d], action [%d], error_code [%d]", id, action, error_code);
+       int err = EMAIL_ERROR_NONE;
+
+       if(id < 0 || action < 0) {
+               EM_DEBUG_LOG("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_SHOW_USER_MESSAGE);
+
+       /* id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&id, sizeof(int))) {
+               EM_DEBUG_LOG("emipc_add_parameter failed  ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* action */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&action, sizeof(int))) {
+               EM_DEBUG_LOG("emipc_add_parameter failed  ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* error_code */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&error_code, sizeof(int))) {
+               EM_DEBUG_LOG("emipc_add_parameter failed  ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(!emipc_execute_proxy_api(hAPI))  {
+               EM_DEBUG_LOG("ipcProxy_ExecuteAsyncAPI failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_parse_mime_file(char *eml_file_path, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count)
+{
+       EM_DEBUG_FUNC_BEGIN("eml_file_path : [%s], output_mail_data : [%p], output_attachment_data : [%p]", eml_file_path, output_mail_data, output_attachment_data);
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(eml_file_path, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emcore_parse_mime_file_to_mail(eml_file_path, output_mail_data, output_attachment_data, output_attachment_count, &err) || !*output_mail_data)
+               EM_DEBUG_EXCEPTION("emcore_parse_mime_file_to_mail failed [%d]", err);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_write_mime_file(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data, int input_attachment_count, char **output_file_path)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data : [%p], input_attachment_data : [%p], input_attachment_count : [%d]", input_mail_data, input_attachment_data, input_attachment_count);
+
+       int err = EMAIL_ERROR_NONE;
+       int size = 0;
+       char *p_output_file_path = NULL;
+       char *mail_data_stream = NULL;
+       char *attachment_data_list_stream = NULL;
+       HIPC_API hAPI = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(input_mail_data, EMAIL_ERROR_INVALID_PARAM);
+
+       hAPI = emipc_create_email_api(_EMAIL_API_WRITE_MIME_FILE);
+       if (!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       mail_data_stream = em_convert_mail_data_to_byte_stream(input_mail_data, &size);
+       if (!mail_data_stream) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_data_to_byte_stream failed");
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, mail_data_stream, size)) {
+               EM_DEBUG_EXCEPTION("emipc_add_dynamic_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       attachment_data_list_stream = em_convert_attachment_data_to_byte_stream(input_attachment_data, input_attachment_count, &size);
+       if ((size > 0) && !emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, attachment_data_list_stream, size)) {
+               EM_DEBUG_EXCEPTION("emipc_add_dynamic_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (*output_file_path && (size = EM_SAFE_STRLEN(*output_file_path)) > 0) {
+               EM_DEBUG_LOG("output_file_path : [%s] size : [%d]", *output_file_path, size);
+               size = size + 1;
+       } else {
+               size = 0;
+       }
+
+       if (!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, *output_file_path, size)) {
+               EM_DEBUG_EXCEPTION("emipc_add_dynamic_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }       
+
+       if (emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       size = emipc_get_parameter_length(hAPI, ePARAMETER_OUT, 0);
+       if (size > 0) {
+               p_output_file_path = (char *)em_malloc(size);
+               if (p_output_file_path == NULL) {
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               if ((err = emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, size, p_output_file_path)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_get_parameter failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       
+       *output_file_path = p_output_file_path; 
+
+FINISH_OFF:
+
+       if (hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       if (err != EMAIL_ERROR_NONE)
+               EM_SAFE_FREE(p_output_file_path);
+
+       EM_DEBUG_FUNC_END("err : [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_delete_parsed_data(email_mail_data_t *input_mail_data)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_data : [%p]", input_mail_data);
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(input_mail_data, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emcore_delete_parsed_data(input_mail_data, &err))
+               EM_DEBUG_EXCEPTION("emcore_delete_parsed_data failed [%d]", err);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_mime_entity(char *mime_path, char **mime_entity)
+{
+       EM_DEBUG_FUNC_BEGIN("mime_path : [%s]", mime_path);
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(mime_path, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emcore_get_mime_entity(mime_path, mime_entity, &err)) 
+               EM_DEBUG_EXCEPTION("emcore_get_mime_entity failed [%d]", err);
+
+       EM_DEBUG_FUNC_END();
+       return err;
+}
+
+
diff --git a/email-api/email-api-init.c b/email-api/email-api-init.c
new file mode 100755 (executable)
index 0000000..0adc2c3
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-init.c
+ * @brief              This file contains the data structures and interfaces of Email FW intialization related Functionality provided by 
+ *                     email-service . 
+ */
+#include "email-api.h"
+#include "string.h"
+#include "email-convert.h"
+#include "email-storage.h"
+#include "email-ipc.h"
+#include "email-core-task-manager.h"
+#include <sqlite3.h>
+
+
+EXPORT_API int email_open_db(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error  = EMAIL_ERROR_NONE;
+       
+       if (emstorage_db_open(&error) == NULL)
+               EM_DEBUG_EXCEPTION("emstorage_db_open failed [%d]", error);
+
+       
+       EM_DEBUG_FUNC_END("error [%d]", error);
+
+       return error;   
+}
+
+EXPORT_API int email_close_db(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error  = EMAIL_ERROR_NONE;
+
+       if ( !emstorage_db_close(&error)) 
+               EM_DEBUG_EXCEPTION("emstorage_db_close failed [%d]", error);
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;   
+}
+
+
+EXPORT_API int email_service_begin(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = -1;
+
+       signal(SIGPIPE, SIG_IGN); /* to ignore signal 13(SIGPIPE) */
+       
+       ret = emipc_initialize_proxy();
+
+       emcore_init_task_handler_array();
+
+       EM_DEBUG_FUNC_END("err[%d]", ret);
+       return ret;
+}
+
+
+EXPORT_API int email_service_end(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = -1;
+       
+       ret = emipc_finalize_proxy();
+       if (ret != EMAIL_ERROR_NONE)
+               EM_DEBUG_FUNC_END("err[%d]", ret);
+       
+       return ret;
+}
+
+/* API - Exposed to External Application- core team.Creates all Email DB tables [ EXTERNAL] */
+
+
+EXPORT_API int email_init_storage(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error  = EMAIL_ERROR_NONE;
+       
+       if (!emstorage_create_table(EMAIL_CREATE_DB_CHECK, &error))  {
+               EM_DEBUG_EXCEPTION("emstorage_create_table failed [%d]", error);
+       }
+
+       EM_DEBUG_FUNC_END("error[%d]", error);
+       return error;
+}
+
+EXPORT_API int email_ping_service(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error  = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_PING_SERVICE);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+               
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &error);
+       
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err[%d]", error);
+       return error;
+}
diff --git a/email-api/email-api-mail.c b/email-api/email-api-mail.c
new file mode 100755 (executable)
index 0000000..3afde9e
--- /dev/null
@@ -0,0 +1,1785 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-mail.c
+ * @brief              This file contains the data structures and interfaces of Message related Functionality provided by 
+ *                     email-service . 
+ */
+
+#include <stdlib.h>
+#include <time.h>
+#include <string.h>
+#include "email-api.h"
+#include "email-ipc.h"
+#include "email-convert.h"
+#include "email-core-tasks.h"
+#include "email-core-utils.h"
+#include "email-core-mail.h"
+#include "email-core-smtp.h"
+#include "email-core-account.h"
+#include "email-core-task-manager.h"
+#include "email-storage.h"
+#include "email-utilities.h"
+#include "db-util.h"
+
+#define  DIR_SEPERATOR_CH '/'
+
+#define _DIRECT_TO_DB
+
+#define MAX_SEARCH_LEN 1000
+
+EXPORT_API int email_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count [%d], input_meeting_request [%p], input_from_eas [%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+
+       EM_IF_NULL_RETURN_VALUE(input_mail_data,               EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_mail_data->account_id,   EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_mail_data->mailbox_id,   EMAIL_ERROR_INVALID_PARAM);
+
+       if(input_attachment_count > 0 && !input_attachment_data_list) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int       err = EMAIL_ERROR_NONE;
+       int       size = 0;
+       char     *mail_data_stream = NULL;
+       char     *attachment_data_list_stream  = NULL;
+       char     *meeting_request_stream = NULL;
+       HIPC_API  hAPI = NULL;
+       
+       if(input_from_eas == 0) { /* native emails */
+               hAPI = emipc_create_email_api(_EMAIL_API_ADD_MAIL);
+
+               if(!hAPI) {
+                       EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+                       err = EMAIL_ERROR_NULL_VALUE;           
+                       goto FINISH_OFF;
+               }
+
+               /* email_mail_data_t */
+               mail_data_stream = em_convert_mail_data_to_byte_stream(input_mail_data, &size);
+
+               if(!mail_data_stream) {
+                       EM_DEBUG_EXCEPTION("em_convert_mail_data_to_byte_stream failed");
+                       err = EMAIL_ERROR_NULL_VALUE;
+                       goto FINISH_OFF;
+               }
+               emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, mail_data_stream, size);
+               
+               /* email_attachment_data_t */
+               attachment_data_list_stream = em_convert_attachment_data_to_byte_stream(input_attachment_data_list, input_attachment_count, &size);
+
+               if((size > 0) && !emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, attachment_data_list_stream, size)) {
+                       EM_DEBUG_EXCEPTION("emipc_add_dynamic_parameter failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               /*  email_meeting_request_t */
+               if ( input_mail_data->meeting_request_status != EMAIL_MAIL_TYPE_NORMAL ) {
+                       meeting_request_stream = em_convert_meeting_req_to_byte_stream(input_meeting_request, &size);
+
+                       if(!meeting_request_stream) {
+                               EM_DEBUG_EXCEPTION("em_convert_meeting_req_to_byte_stream failed");
+                               err = EMAIL_ERROR_NULL_VALUE;
+                               goto FINISH_OFF;
+                       }
+
+                       emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, meeting_request_stream, size);
+               }
+
+               /* input_from_eas */
+               emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_from_eas, sizeof(int));
+
+               /* Execute API */
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               /* get result from service */
+               err = *((int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 0));
+               if(err == EMAIL_ERROR_NONE) {
+                       /* result mail_id */
+                       input_mail_data->mail_id = *((int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 1));
+                       /* result thread_id */
+                       input_mail_data->thread_id = *((int*)emipc_get_nth_parameter_data(hAPI, ePARAMETER_OUT, 2));
+               }
+       } 
+       else { /* take care of mails from eas */
+               err = emcore_add_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+               if(err != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_add_mail failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       if(hAPI) 
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+
+}
+
+EXPORT_API int email_add_read_receipt(int input_read_mail_id, int *output_receipt_mail_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_read_mail_id [%d], output_receipt_mail_id [%p]", input_read_mail_id, output_receipt_mail_id);
+
+       EM_IF_NULL_RETURN_VALUE(output_receipt_mail_id, EMAIL_ERROR_INVALID_PARAM);
+
+       int      err = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_ADD_READ_RECEIPT);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_read_mail_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("Add Param mail body Fail");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+       EM_DEBUG_LOG("err [%d]", err);
+
+       if(err == EMAIL_ERROR_NONE) {
+               /* Get receipt mail id */
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), output_receipt_mail_id);
+               EM_DEBUG_LOG("output_receipt_mail_id [%d]", *output_receipt_mail_id);
+       }
+
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+#define TMP_BODY_PATH "/tmp/UTF-8"
+int email_create_db_full()
+{
+       int mailbox_index, mail_index, mailbox_count, mail_slot_size;
+       int account_id = 0;
+       emstorage_mail_tbl_t mail_table_data = {0};
+       email_mailbox_t *mailbox_list = NULL;
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       FILE *body_file = NULL;
+
+       if ( (err = email_open_db()) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("email_open_db failed [%d]", err);
+               return err;
+       }
+
+       if ((err = emcore_load_default_account_id(&account_id)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_load_default_account_id failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       body_file = fopen(TMP_BODY_PATH, "w");
+       if (body_file == NULL) {
+               EM_DEBUG_EXCEPTION("fopen failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < 10; i++)
+               fprintf(body_file, "Dummy test. [line:%d]\n", i);
+
+
+       fflush(body_file);
+
+       mail_table_data.subject = (char*) em_malloc(50); 
+       mail_table_data.full_address_from = strdup("<dummy_from@nowhere.com>");
+       mail_table_data.full_address_to = strdup("<dummy_to@nowhere.com>");
+       mail_table_data.account_id = account_id;
+       mail_table_data.file_path_plain = strdup(TMP_BODY_PATH);
+       mail_table_data.body_download_status = 1;
+
+       if( (err = email_get_mailbox_list_ex(1, -1, 0, &mailbox_list, &mailbox_count)) < EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("email_get_mailbox_list_ex failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for(mailbox_index = 0; mailbox_index < mailbox_count; mailbox_index++) {
+               mail_slot_size= mailbox_list[mailbox_index].mail_slot_size;
+               for(mail_index = 0; mail_index < mail_slot_size; mail_index++) {
+                       sprintf(mail_table_data.subject, "Subject #%d",mail_index);
+                       mail_table_data.mailbox_id   = mailbox_list[mailbox_index].mailbox_id;
+                       mail_table_data.mailbox_type = mailbox_list[mailbox_index].mailbox_type;
+                       if( !emstorage_add_mail(&mail_table_data, 1, true, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_add_mail failed [%d]",err);
+               
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+FINISH_OFF:
+       if ( (err = email_close_db()) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("email_close_db failed [%d]", err);
+       }       
+
+       if(body_file) fclose(body_file); /*prevent 39446*/
+       
+       if(mailbox_list)
+               email_free_mailbox(&mailbox_list, mailbox_count);
+
+       EM_SAFE_FREE(mail_table_data.subject);
+       EM_SAFE_FREE(mail_table_data.full_address_from);
+       EM_SAFE_FREE(mail_table_data.full_address_to);
+
+       return err;
+}
+
+EXPORT_API int email_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count [%d], input_meeting_request [%p], input_from_eas [%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+
+       EM_IF_NULL_RETURN_VALUE(input_mail_data,               EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_mail_data->account_id,   EMAIL_ERROR_INVALID_PARAM);
+
+       if(input_attachment_count > 0 && !input_attachment_data_list) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int       err = EMAIL_ERROR_NONE;
+       int       size = 0;
+       char     *mail_data_stream = NULL;
+       char     *attachment_data_list_stream  = NULL;
+       char     *meeting_request_stream = NULL;
+
+       HIPC_API  hAPI = NULL;
+       
+       if(input_from_eas == 0) {
+               hAPI = emipc_create_email_api(_EMAIL_API_UPDATE_MAIL);  
+
+               if(!hAPI) {
+                       EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+                       err = EMAIL_ERROR_NULL_VALUE;           
+                       goto FINISH_OFF;
+               }
+
+               /* email_mail_data_t */
+               mail_data_stream = em_convert_mail_data_to_byte_stream(input_mail_data, &size);
+
+               if(!mail_data_stream) {
+                       EM_DEBUG_EXCEPTION("em_convert_mail_data_to_byte_stream failed");
+                       err = EMAIL_ERROR_NULL_VALUE;
+                       goto FINISH_OFF;
+               }
+               
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, mail_data_stream, size)) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter for head failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               
+               /* email_attachment_data_t */
+               attachment_data_list_stream = em_convert_attachment_data_to_byte_stream(input_attachment_data_list, input_attachment_count, &size);
+               if ((size > 0) && !emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, attachment_data_list_stream, size)) {
+                       EM_DEBUG_EXCEPTION("emipc_add_dynamic_parameter failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               /*  email_meeting_request_t */
+               if (input_mail_data->meeting_request_status != EMAIL_MAIL_TYPE_NORMAL) {
+                       meeting_request_stream = em_convert_meeting_req_to_byte_stream(input_meeting_request, &size);
+
+                       if(!meeting_request_stream) {
+                               EM_DEBUG_EXCEPTION("em_convert_meeting_req_to_byte_stream failed");
+                               err = EMAIL_ERROR_NULL_VALUE;
+                               goto FINISH_OFF;
+                       }
+
+                       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, meeting_request_stream, size)) {
+                               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+               }
+
+               /* input_from_eas */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_from_eas, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               /* Execute API */
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               
+               if(err == EMAIL_ERROR_NONE) {
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &input_mail_data->mail_id);
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 2, sizeof(int), &input_mail_data->thread_id);
+               }
+       } 
+       else {
+               if( (err = emcore_update_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_update_mail failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       if(hAPI) 
+               emipc_destroy_email_api(hAPI);
+
+       EM_SAFE_FREE(mail_data_stream);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+
+}
+
+EXPORT_API int email_clear_mail_data()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_CLEAR_DATA);  
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+       
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api Fail");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+       
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_count_mail(email_list_filter_t *input_filter_list, int input_filter_count, int *output_total_mail_count, int *output_unseen_mail_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_filter_list[%p], input_filter_count [%d], output_total_mail_count[%p], output_unseen_mail_count[%p]", input_filter_list, input_filter_count, output_total_mail_count, output_unseen_mail_count);
+       
+       int total_count = 0;
+       int unread = 0;
+       int err = EMAIL_ERROR_NONE;
+       char *conditional_clause_string = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(input_filter_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_filter_count, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(output_total_mail_count, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(output_unseen_mail_count, EMAIL_ERROR_INVALID_PARAM);
+
+       if( (err = emstorage_write_conditional_clause_for_getting_mail_list(input_filter_list, input_filter_count, NULL, 0, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_query_mail_count(conditional_clause_string, true, &total_count, &unread)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_count failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       *output_total_mail_count = total_count;
+       *output_unseen_mail_count = unread;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_delete_mail(int input_mailbox_id, int *input_mail_ids, int input_num, int input_from_server)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_mail_ids[%p], input_num[%d], input_from_server[%d]", input_mailbox_id, input_mail_ids, input_num, input_from_server);
+
+       int err = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(input_mail_ids, EMAIL_ERROR_INVALID_PARAM);
+       
+       if (input_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("input_mailbox_id = %d", input_mailbox_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       if (input_num <= 0) {
+               EM_DEBUG_EXCEPTION("input_num = %d", input_num);
+               err = EMAIL_ERROR_INVALID_PARAM;                
+               return err;
+       }
+
+       hAPI = emipc_create_email_api(_EMAIL_API_DELETE_MAIL);
+       
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       /* mailbox id*/
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_mailbox_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Number of mail_ids */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_num, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* set of mail_ids */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)input_mail_ids, input_num * sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* from-server */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_from_server, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;   
+               goto FINISH_OFF;
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_delete_all_mails_in_mailbox(int input_mailbox_id, int input_from_server)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_from_server[%d]", input_mailbox_id, input_from_server);
+
+       int err = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = NULL;
+       
+       if(input_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("input_mailbox_id = %d", input_mailbox_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+       
+       hAPI = emipc_create_email_api(_EMAIL_API_DELETE_ALL_MAIL);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+       
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_mailbox_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_from_server, sizeof(int))){
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;           
+               goto FINISH_OFF;
+       }
+       
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int),&err );
+
+FINISH_OFF:
+
+       if(hAPI)        
+               emipc_destroy_email_api(hAPI);
+       
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_add_attachment(int mail_id, email_attachment_data_t* attachment)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], attachment[%p]", mail_id, attachment);
+       int err = EMAIL_ERROR_NONE;
+       char *attchment_stream = NULL;
+       int size = 0;
+       HIPC_API hAPI = NULL;
+       
+       EM_IF_NULL_RETURN_VALUE(mail_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(attachment, EMAIL_ERROR_INVALID_PARAM);
+       
+       hAPI = emipc_create_email_api(_EMAIL_API_ADD_ATTACHMENT);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       /* mail_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&mail_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Attachment */
+       attchment_stream = em_convert_attachment_data_to_byte_stream(attachment, 1, &size);
+
+       if(!attchment_stream) {
+               EM_DEBUG_EXCEPTION("em_convert_attachment_data_to_byte_stream failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, attchment_stream, size)){
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;           
+               goto FINISH_OFF;
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+       
+       if(EMAIL_ERROR_NONE == err) {
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &attachment->attachment_id);
+       }
+
+FINISH_OFF:
+       EM_SAFE_FREE(attchment_stream);
+       
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+       
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+ }
+
+
+EXPORT_API int email_delete_attachment(int attachment_id)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_id[%d]", attachment_id);
+       int err = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = NULL;
+       
+       EM_IF_NULL_RETURN_VALUE(attachment_id, EMAIL_ERROR_INVALID_PARAM);
+       
+       hAPI = emipc_create_email_api(_EMAIL_API_DELETE_ATTACHMENT);
+       
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       /* attachment_index */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&attachment_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;           
+               goto FINISH_OFF;
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       return err;
+}
+
+/* -----------------------------------------------------------
+                                             Mail Search API
+    -----------------------------------------------------------*/
+
+EXPORT_API int email_query_mails(char *conditional_clause_string, email_mail_data_t** mail_list,  int *result_count)
+{
+       EM_DEBUG_FUNC_BEGIN("conditional_clause_string [%s], mail_list [%p], result_count [%p]", conditional_clause_string, mail_list, result_count);
+
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *result_mail_tbl;
+       
+       EM_IF_NULL_RETURN_VALUE(result_count, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(conditional_clause_string, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_query_mail_tbl(conditional_clause_string, true, &result_mail_tbl, result_count, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if(!em_convert_mail_tbl_to_mail_data(result_mail_tbl, *result_count, mail_list, &err)) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_tbl_to_mail_data failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:    
+       if(result_mail_tbl && !emstorage_free_mail(&result_mail_tbl, *result_count, &err))
+               EM_DEBUG_EXCEPTION("emstorage_free_mail failed [%d]", err);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_query_mail_list(char *input_conditional_clause_string, email_mail_list_item_t** output_mail_list,  int *output_result_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_conditional_clause_string [%s], output_mail_list [%p], output_result_count [%p]", input_conditional_clause_string, output_mail_list, output_result_count);
+
+       int err = EMAIL_ERROR_NONE;
+       
+       EM_IF_NULL_RETURN_VALUE(input_conditional_clause_string, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(output_result_count, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_query_mail_list(input_conditional_clause_string, true, output_mail_list, output_result_count, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:    
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+/* -----------------------------------------------------------
+                                             Mail Get Info API
+    -----------------------------------------------------------*/
+EXPORT_API int email_get_attachment_data(int attachment_id, email_attachment_data_t** attachment)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_id[%d], attachment[%p]", attachment_id, attachment);
+       
+       int err = EMAIL_ERROR_NONE;
+       int nSize = 0;
+       int attachment_count = 0;
+       char* attchment_stream = NULL;
+       email_attachment_data_t* attachment_data = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(attachment_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(attachment, EMAIL_ERROR_INVALID_PARAM);
+
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_GET_ATTACHMENT);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* attachment_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&attachment_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;           
+               goto FINISH_OFF;
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+       if(EMAIL_ERROR_NONE == err) {
+               nSize = emipc_get_parameter_length(hAPI, ePARAMETER_OUT, 1);
+               if(nSize > 0) {
+                       attchment_stream = (char*)em_malloc(nSize+1);
+
+                       if(!attchment_stream) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+                               goto FINISH_OFF;
+                       }       
+               
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, nSize, attchment_stream);
+                       em_convert_byte_stream_to_attachment_data(attchment_stream, nSize, &attachment_data, &attachment_count);
+               }
+               
+               if(!attachment_data) {
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_NULL_VALUE");
+                       err = EMAIL_ERROR_NULL_VALUE;           
+                       goto FINISH_OFF;
+               }
+
+               *attachment = attachment_data;
+       }
+
+FINISH_OFF:
+       EM_SAFE_FREE(attchment_stream);
+
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+
+}
+
+EXPORT_API int email_get_attachment_data_list(int input_mail_id, email_attachment_data_t **output_attachment_data, int *output_attachment_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], output_attachment_data[%p], output_attachment_count[%p]", input_mail_id, output_attachment_data, output_attachment_count);
+       int err = EMAIL_ERROR_NONE;
+       
+       if((err = emcore_get_attachment_data_list(input_mail_id, output_attachment_data, output_attachment_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_attachment_data_list failed [%d]", err);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_free_attachment_data(email_attachment_data_t **attachment_data_list, int attachment_data_count)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_data_list[%p], attachment_data_count[%d]", attachment_data_list, attachment_data_count);        
+       
+       int err = EMAIL_ERROR_NONE;
+
+       emcore_free_attachment_data(attachment_data_list, attachment_data_count, &err);
+       
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_mail_list_ex(email_list_filter_t *input_filter_list, int input_filter_count, email_list_sorting_rule_t *input_sorting_rule_list, int input_sorting_rule_count, int input_start_index, int input_limit_count, email_mail_list_item_t** output_mail_list, int *output_result_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_filter_list [%p], input_filter_count[%d], input_sorting_rule_list[%p], input_sorting_rule_count [%d], input_start_index [%d], input_limit_count [%d], output_mail_list [%p], output_result_count [%p]", input_filter_list, input_filter_count, input_sorting_rule_list, input_sorting_rule_count, input_start_index, input_limit_count, output_mail_list, output_result_count);
+
+       int err = EMAIL_ERROR_NONE;
+       char *conditional_clause_string = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(output_mail_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(output_result_count, EMAIL_ERROR_INVALID_PARAM);
+
+       if( (err = emstorage_write_conditional_clause_for_getting_mail_list(input_filter_list, input_filter_count, input_sorting_rule_list, input_sorting_rule_count, input_start_index, input_limit_count, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("conditional_clause_string[%s].", conditional_clause_string);
+
+       if(!emstorage_query_mail_list(conditional_clause_string, true, output_mail_list, output_result_count, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_list [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+       EM_SAFE_FREE(conditional_clause_string);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_free_list_filter(email_list_filter_t **input_filter_list, int input_filter_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_filter_list [%p], input_filter_count[%d]", input_filter_list, input_filter_count);
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(input_filter_list, EMAIL_ERROR_INVALID_PARAM);
+
+       err = emstorage_free_list_filter(input_filter_list, input_filter_count);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_mails(int account_id , int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_data_t** mail_list,  int* result_count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *mail_tbl_list = NULL;
+       EM_IF_NULL_RETURN_VALUE(result_count, EMAIL_ERROR_INVALID_PARAM);
+
+       if( account_id < ALL_ACCOUNT) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM ;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_mails(account_id, mailbox_id, NULL, thread_id, start_index, limit_count, sorting, true, &mail_tbl_list, result_count, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mails failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if(!em_convert_mail_tbl_to_mail_data(mail_tbl_list, *result_count, mail_list, &err)) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_tbl_to_mail_data failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:    
+       if(mail_tbl_list && !emstorage_free_mail(&mail_tbl_list, *result_count, &err))
+               EM_DEBUG_EXCEPTION("emstorage_free_mail failed [%d]", err);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_mail_list(int account_id , int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       
+       EM_IF_NULL_RETURN_VALUE(result_count, EMAIL_ERROR_INVALID_PARAM);
+
+       if( account_id < ALL_ACCOUNT) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if (!emstorage_get_mail_list(account_id, mailbox_id, NULL, thread_id, start_index, limit_count, 0, NULL, sorting, true, mail_list, result_count, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:    
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_mail_by_address(int account_id , int mailbox_id, email_email_address_list_t* addr_list,
+                                                                       int start_index, int limit_count, int search_type, const char *search_value, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+
+       email_mail_list_item_t* mail_list_item = NULL;
+       
+       EM_IF_NULL_RETURN_VALUE(mail_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(result_count, EMAIL_ERROR_INVALID_PARAM);
+
+       if( account_id < ALL_ACCOUNT) {
+               EM_DEBUG_EXCEPTION("Invalid account id param");
+               err = EMAIL_ERROR_INVALID_PARAM ;
+               return err;
+       }
+
+       if (!emstorage_get_mail_list(account_id, mailbox_id, addr_list, EMAIL_LIST_TYPE_NORMAL, start_index, limit_count, search_type, search_value, sorting, true, &mail_list_item, result_count, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       *mail_list = mail_list_item;
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_thread_information_by_thread_id(int thread_id, email_mail_data_t** thread_info)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *mail_table_data = NULL;
+       
+       EM_IF_NULL_RETURN_VALUE(thread_info, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_get_thread_information(thread_id, &mail_table_data , true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_thread_information  failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(!em_convert_mail_tbl_to_mail_data(mail_table_data, 1, thread_info, &err)) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_tbl_to_mail_data failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:    
+
+       if(mail_table_data && !emstorage_free_mail(&mail_table_data, 1, &err)) 
+               EM_DEBUG_EXCEPTION("emstorage_free_mail failed [%d]", err);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_thread_information_ex(int thread_id, email_mail_list_item_t** thread_info)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *mail_table_data = NULL;
+       email_mail_list_item_t *temp_thread_info = NULL;
+       
+       EM_IF_NULL_RETURN_VALUE(thread_info, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_get_thread_information(thread_id, &mail_table_data , true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_thread_information -- failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       temp_thread_info = em_malloc(sizeof(email_mail_list_item_t));
+
+       if(!temp_thread_info) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       EM_SAFE_STRNCPY(temp_thread_info->full_address_from       , mail_table_data->full_address_from, STRING_LENGTH_FOR_DISPLAY);
+       EM_SAFE_STRNCPY(temp_thread_info->email_address_sender    , mail_table_data->email_address_sender, MAX_EMAIL_ADDRESS_LENGTH);
+       EM_SAFE_STRNCPY(temp_thread_info->email_address_recipient , mail_table_data->email_address_recipient, STRING_LENGTH_FOR_DISPLAY);
+       EM_SAFE_STRNCPY(temp_thread_info->subject                 , mail_table_data->subject, STRING_LENGTH_FOR_DISPLAY);
+       EM_SAFE_STRNCPY(temp_thread_info->preview_text            , mail_table_data->preview_text, MAX_PREVIEW_TEXT_LENGTH);
+       temp_thread_info->mail_id                                 = mail_table_data->mail_id;
+       temp_thread_info->mailbox_id                              = mail_table_data->mailbox_id;
+       temp_thread_info->account_id                              = mail_table_data->account_id;
+       temp_thread_info->date_time                               = mail_table_data->date_time;
+       temp_thread_info->body_download_status                    = mail_table_data->body_download_status;
+       temp_thread_info->flags_seen_field                        = mail_table_data->flags_seen_field;
+       temp_thread_info->priority                                = mail_table_data->priority;
+       temp_thread_info->save_status                             = mail_table_data->save_status;
+       temp_thread_info->lock_status                             = mail_table_data->lock_status;
+       temp_thread_info->report_status                           = mail_table_data->report_status;
+       temp_thread_info->attachment_count                        = mail_table_data->attachment_count;
+       temp_thread_info->DRM_status                              = mail_table_data->DRM_status;
+       temp_thread_info->thread_id                               = mail_table_data->thread_id;
+       temp_thread_info->thread_item_count                       = mail_table_data->thread_item_count;
+       temp_thread_info->meeting_request_status                  = mail_table_data->meeting_request_status;
+
+       *thread_info = temp_thread_info;
+
+FINISH_OFF:    
+
+       if(mail_table_data)
+               emstorage_free_mail(&mail_table_data, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_mail_data(int input_mail_id, email_mail_data_t **output_mail_data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       
+       if ( ((err = emcore_get_mail_data(input_mail_id, output_mail_data)) != EMAIL_ERROR_NONE) || !output_mail_data) 
+               EM_DEBUG_EXCEPTION("emcore_get_mail_data failed [%d]", err);    
+               
+       EM_DEBUG_FUNC_END("err [%d]", err);     
+       return err;
+}
+
+
+/* -----------------------------------------------------------
+                                             Mail Flag API
+    -----------------------------------------------------------*/
+
+EXPORT_API int email_modify_seen_flag(int *mail_ids, int num, int seen_flag, int onserver)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], num[%d],seen_flag[%d], on_server [ %d]", mail_ids, num, seen_flag, onserver);
+       EM_DEBUG_FUNC_END("EMAIL_ERROR_NOT_IMPLEMENTED");
+       return EMAIL_ERROR_NOT_IMPLEMENTED;
+}
+
+EXPORT_API int email_set_flags_field(int account_id, int *mail_ids, int num, email_flags_field_type field_type, int value, int onserver)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], mail_ids[%p], num[%d], field_type [%d], seen_flag[%d], on_server [ %d]", account_id, mail_ids, num, field_type, value, onserver);
+       
+       int err = EMAIL_ERROR_NONE;
+
+               
+       EM_IF_NULL_RETURN_VALUE(mail_ids, EMAIL_ERROR_INVALID_PARAM);
+       if (account_id == 0 || num <= 0 || (onserver != 0 && onserver != 1)) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;                       
+       }
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_SET_FLAGS_FIELD);
+       
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+       
+       /* account_id*/
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Number of mail_ids */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&num, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* set of mail_ids */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)mail_ids, num * sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* field_type */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&field_type, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* value */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&value, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* onserver  */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &(onserver), sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;   
+               goto FINISH_OFF;
+       }
+       
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+/* -----------------------------------------------------------
+                                             Mail Move API
+    -----------------------------------------------------------*/
+EXPORT_API int email_move_mail_to_mailbox(int *mail_ids, int num, int input_target_mailbox_id)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], num [%d], input_target_mailbox_id[%d]",  mail_ids, num, input_target_mailbox_id);
+       
+       int err = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = NULL;
+
+       if(input_target_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("input_target_mailbox_id is invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+       EM_IF_NULL_RETURN_VALUE(mail_ids, EMAIL_ERROR_INVALID_PARAM);
+       
+       if (num <= 0)  {
+               EM_DEBUG_LOG("num = %d", num);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       hAPI = emipc_create_email_api(_EMAIL_API_MOVE_MAIL);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+       
+       /* Number of mail_ids */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&num, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* set of mail_ids */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)mail_ids, num * sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* input_target_mailbox_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_target_mailbox_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;           
+               goto FINISH_OFF;
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:            
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+EXPORT_API int  email_move_all_mails_to_mailbox(int input_source_mailbox_id, int input_target_mailbox_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_source_mailbox_id[%d] , input_target_mailbox_id[%d]",  input_source_mailbox_id, input_target_mailbox_id);
+       
+       int err = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = NULL;
+       
+       if(input_source_mailbox_id <= 0 || input_target_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("mailbox_id is invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+       
+       hAPI = emipc_create_email_api(_EMAIL_API_MOVE_ALL_MAIL);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+       
+       /* input_source_mailbox_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_source_mailbox_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* input_target_mailbox_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_target_mailbox_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;           
+               goto FINISH_OFF;
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+       
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_move_mails_to_mailbox_of_another_account(int input_source_mailbox_id, int *input_mail_id_array, int input_mail_id_count, int input_target_mailbox_id, int *output_task_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_source_mailbox_id[%d] input_mail_id_array[%p] input_mail_id_count[%d] input_target_mailbox_id[%d] output_task_id[%p]",  input_source_mailbox_id, input_mail_id_array, input_mail_id_count, input_target_mailbox_id, output_task_id);
+
+       int err = EMAIL_ERROR_NONE;
+       task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT task_parameter;
+
+       if(input_source_mailbox_id <= 0 || input_target_mailbox_id <= 0 || input_mail_id_array == NULL || input_mail_id_count == 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       task_parameter.source_mailbox_id = input_source_mailbox_id;
+       task_parameter.mail_id_array     = input_mail_id_array;
+       task_parameter.mail_id_count     = input_mail_id_count;
+       task_parameter.target_mailbox_id = input_target_mailbox_id;
+
+       if((err = emipc_execute_proxy_task(EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT, &task_parameter)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("execute_proxy_task failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+EXPORT_API int email_free_mail_data(email_mail_data_t** mail_list, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_list[%p], count[%d]", mail_list, count);
+       int err = EMAIL_ERROR_NONE;
+       emcore_free_mail_data_list(mail_list, count);
+       EM_DEBUG_FUNC_END("err [%d]", err);     
+       return err;
+}
+
+/* Convert Modified UTF-7 mailbox name to UTF-8 */
+/* returns modified UTF-8 Name if success else NULL */
+
+EXPORT_API int email_cancel_sending_mail(int mail_id)
+{
+       EM_DEBUG_FUNC_BEGIN("Mail ID [ %d]", mail_id);
+       EM_IF_NULL_RETURN_VALUE(mail_id, EMAIL_ERROR_INVALID_PARAM);
+       
+       int err = EMAIL_ERROR_NONE;
+       int account_id = 0;
+       email_mail_data_t* mail_data = NULL;
+
+       HIPC_API hAPI = NULL;
+       
+       
+       if ((err = emcore_get_mail_data(mail_id, &mail_data)) != EMAIL_ERROR_NONE)  {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_data failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!mail_data) {
+               EM_DEBUG_EXCEPTION("mail_data is null");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       account_id = mail_data->account_id;
+
+       hAPI = emipc_create_email_api(_EMAIL_API_SEND_MAIL_CANCEL_JOB);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       /* Account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Mail ID */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &(mail_id), sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;   
+               goto FINISH_OFF;
+       }
+       
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       emcore_free_mail_data_list(&mail_data, 1);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+
+}
+
+EXPORT_API int email_retry_sending_mail( int mail_id, int timeout_in_sec)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int err = EMAIL_ERROR_NONE;
+
+
+       EM_IF_NULL_RETURN_VALUE(mail_id, EMAIL_ERROR_INVALID_PARAM);
+       if( timeout_in_sec < 0 )  {
+               EM_DEBUG_EXCEPTION("Invalid timeout_in_sec");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_SEND_RETRY);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       /* Mail ID */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &(mail_id), sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* timeout */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &(timeout_in_sec), sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;   
+               goto FINISH_OFF;
+       }
+       
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+
+}
+
+EXPORT_API int email_get_max_mail_count(int *Count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       EM_IF_NULL_RETURN_VALUE(Count, EMAIL_ERROR_INVALID_PARAM);
+       *Count = emstorage_get_max_mail_count();
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+
+/* for setting application,disk usage of email in KB */
+EXPORT_API int email_get_disk_space_usage(unsigned long *total_size)
+{
+       EM_DEBUG_FUNC_BEGIN("total_size[%p]", total_size);
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(total_size, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_mail_get_total_diskspace_usage(total_size,true,&err))  {
+               EM_DEBUG_EXCEPTION("emstorage_mail_get_total_diskspace_usage failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+FINISH_OFF :   
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_address_info_list(int mail_id, email_address_info_list_t** address_info_list)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], address_info_list[%p]", mail_id, address_info_list);
+
+       int err = EMAIL_ERROR_NONE;
+
+       email_address_info_list_t *temp_address_info_list = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(address_info_list, EMAIL_ERROR_INVALID_PARAM);
+       if( mail_id <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM ;
+               return err;
+       }
+       
+       if ( !emcore_get_mail_address_info_list(mail_id, &temp_address_info_list, &err) ) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_address_info_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if ( address_info_list ) {
+               *address_info_list = temp_address_info_list;
+               temp_address_info_list = NULL;
+       }
+
+FINISH_OFF:
+       if ( temp_address_info_list )
+               emstorage_free_address_info_list(&temp_address_info_list);
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_free_address_info_list(email_address_info_list_t **address_info_list)
+{
+       EM_DEBUG_FUNC_BEGIN("address_info_list[%p]", address_info_list);
+
+       int err = EMAIL_ERROR_NONE;
+
+       if ( (err = emstorage_free_address_info_list(address_info_list)) != EMAIL_ERROR_NONE ) {
+               EM_DEBUG_EXCEPTION("address_info_list[%p] free failed.", address_info_list);
+       }
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_structure(const char*encoded_string, void **struct_var, email_convert_struct_type_e type)
+{
+       EM_DEBUG_FUNC_BEGIN("encoded_string[%s], struct_var[%p], type[%d]", encoded_string, struct_var, type);
+       EM_DEBUG_FUNC_END("err [%d]", EMAIL_ERROR_NOT_IMPLEMENTED);
+       return EMAIL_ERROR_NOT_IMPLEMENTED;
+}
+
+EXPORT_API int email_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d],meeting_req[%p]",  mail_id, meeting_req);
+
+       int err = EMAIL_ERROR_NONE;
+
+       email_meeting_request_t *temp_meeting_req = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(meeting_req, EMAIL_ERROR_INVALID_PARAM);
+       if( mail_id <= 0 ) {
+               EM_DEBUG_EXCEPTION(" Invalid Mail Id Param ");
+               err = EMAIL_ERROR_INVALID_PARAM ;
+               return err;
+       }
+       
+       if ( !emstorage_get_meeting_request(mail_id, &temp_meeting_req, 1, &err) ) {
+               EM_DEBUG_EXCEPTION("emstorage_get_meeting_request -- Failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if ( meeting_req )
+               *meeting_req = temp_meeting_req;
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_free_meeting_request(email_meeting_request_t** meeting_req, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("meeting_req[%p], count[%d]", meeting_req, count);
+       if( !meeting_req || !*meeting_req ) {
+               EM_DEBUG_EXCEPTION("NULL PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int i = 0;
+       email_meeting_request_t *cur = *meeting_req;
+       for ( ; i < count ; i++ )
+               emstorage_free_meeting_request(cur + i);
+
+       EM_SAFE_FREE(*meeting_req);
+
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+EXPORT_API int email_move_thread_to_mailbox(int thread_id, int target_mailbox_id, int move_always_flag)
+{
+       EM_DEBUG_FUNC_BEGIN("thread_id[%d], target_mailbox_id[%d], move_always_flag[%d]", thread_id, target_mailbox_id, move_always_flag);
+       int err = EMAIL_ERROR_NONE;
+       
+
+       EM_IF_NULL_RETURN_VALUE(target_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_MOVE_THREAD_TO_MAILBOX);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       /* thread_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&thread_id, sizeof(int))){
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* target mailbox information */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&target_mailbox_id, sizeof(int))){
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+       }
+
+       /* move_always_flag */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&move_always_flag, sizeof(int))){
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;   
+               goto FINISH_OFF;
+       }
+       
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_delete_thread(int thread_id, int delete_always_flag)
+{
+       EM_DEBUG_FUNC_BEGIN("thread_id[%d], delete_always_flag[%d]", thread_id, delete_always_flag);
+       int err = EMAIL_ERROR_NONE;
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_DELETE_THREAD);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       /* thread_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&thread_id, sizeof(int))){
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* delete_always_flag */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&delete_always_flag, sizeof(int))){
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;   
+               goto FINISH_OFF;
+       }
+       
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_modify_seen_flag_of_thread(int thread_id, int seen_flag, int on_server)
+{
+       EM_DEBUG_FUNC_BEGIN("thread_id[%d], seen_flag[%d], on_server[%d]", thread_id, seen_flag, on_server);
+       int err = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_MODIFY_SEEN_FLAG_OF_THREAD);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;           
+               goto FINISH_OFF;
+       }
+
+       /* thread_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&thread_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* seen_flag */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&seen_flag, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+
+       /* on_server */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&on_server, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;                
+               goto FINISH_OFF;
+       }
+       
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;   
+               goto FINISH_OFF;
+       }
+       
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_on_server[%d], output_handle[%p]", input_mailbox_id, input_on_server, output_handle);
+       int err = EMAIL_ERROR_NONE;
+       int return_value = 0;
+       HIPC_API hAPI = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl_data = NULL;
+
+       if( (err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       email_account_server_t account_server_type = EMAIL_SERVER_TYPE_NONE;
+       ASNotiData as_noti_data;
+
+       memset(&as_noti_data, 0, sizeof(ASNotiData)); /* initialization of union members */
+
+       if ( em_get_account_server_type_by_account_id(mailbox_tbl_data->account_id, &account_server_type, true, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC && input_on_server == true) {
+               int as_handle = 0;
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.expunge_mails_deleted_flagged.handle        = as_handle;
+               as_noti_data.expunge_mails_deleted_flagged.mailbox_id    = input_mailbox_id;
+               as_noti_data.expunge_mails_deleted_flagged.on_server     = input_on_server;
+
+               return_value = em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_EXPUNGE_MAILS_DELETED_FLAGGED, &as_noti_data);
+
+               if ( return_value == false ) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(output_handle)
+                       *output_handle = as_handle;
+       }
+       else
+       {
+               hAPI = emipc_create_email_api(_EMAIL_API_EXPUNGE_MAILS_DELETED_FLAGGED);
+
+               if(!hAPI) {
+                       EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+                       err = EMAIL_ERROR_NULL_VALUE;
+                       goto FINISH_OFF;
+               }
+
+               /* input_mailbox_id */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_mailbox_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               /* input_on_server */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_on_server, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               /* Execute API */
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               if (err == EMAIL_ERROR_NONE) {
+                       if(output_handle)
+                               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), output_handle);
+               }
+       }
+
+FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       if(mailbox_tbl_data) {
+               emstorage_free_mailbox(&mailbox_tbl_data, 1, NULL);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-api/email-api-mailbox.c b/email-api/email-api-mailbox.c
new file mode 100755 (executable)
index 0000000..94edec3
--- /dev/null
@@ -0,0 +1,741 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email_api_mailbox.c
+ * @brief              This file contains the data structures and interfaces of mailbox related Functionality provided by 
+ *                     email-service . 
+ */
+#include "email-api.h"
+#include "string.h"
+#include "email-convert.h"
+#include "email-storage.h"
+#include "email-core-utils.h"
+#include "email-utilities.h"
+#include "email-ipc.h"
+#include "db-util.h"
+
+/* API - Create a mailbox */
+
+EXPORT_API int email_add_mailbox(email_mailbox_t* new_mailbox, int on_server, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int size = 0;
+       int err = EMAIL_ERROR_NONE;
+       char* local_mailbox_stream = NULL;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+
+       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+       EM_IF_NULL_RETURN_VALUE(new_mailbox, EMAIL_ERROR_INVALID_PARAM);
+
+       /*  check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(new_mailbox->account_id, &account_server_type, false, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC && on_server) {
+               int as_handle;
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.add_mailbox.handle        = as_handle;
+               as_noti_data.add_mailbox.account_id    = new_mailbox->account_id;
+               as_noti_data.add_mailbox.mailbox_alias = new_mailbox->alias;
+               as_noti_data.add_mailbox.mailbox_path  = new_mailbox->mailbox_name;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_ADD_MAILBOX, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(handle)
+                       *handle = as_handle;
+       }
+       else {
+               hAPI = emipc_create_email_api(_EMAIL_API_ADD_MAILBOX);
+
+               EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               local_mailbox_stream = em_convert_mailbox_to_byte_stream(new_mailbox, &size);
+
+               EM_PROXY_IF_NULL_RETURN_VALUE(local_mailbox_stream, hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, local_mailbox_stream, size)) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       EM_SAFE_FREE(local_mailbox_stream);
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &on_server, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               EM_DEBUG_LOG(" >>>>> error VALUE [%d]", err);
+       
+               if(handle) {
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+                       EM_DEBUG_LOG(" >>>>> Handle [%d]", *handle);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 2, sizeof(int), &(new_mailbox->mailbox_id));
+               EM_DEBUG_LOG(" >>>>> new_mailbox->mailbox_id [%d]", new_mailbox->mailbox_id);
+
+               emipc_destroy_email_api(hAPI);
+               hAPI = NULL;
+       }
+
+FINISH_OFF:
+       EM_SAFE_FREE(local_mailbox_stream);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_rename_mailbox(int input_mailbox_id, char *input_mailbox_name, char *input_mailbox_alias, int input_on_server, int *output_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_mailbox_name [%p], input_mailbox_alias [%p], input_on_server [%d], output_handle [%p]", input_mailbox_id, input_mailbox_name, input_mailbox_alias, input_on_server, output_handle);
+
+       int err = EMAIL_ERROR_NONE;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_id,    EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_name,  EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_alias, EMAIL_ERROR_INVALID_PARAM);
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE || !mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /*  check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(mailbox_tbl->account_id, &account_server_type, false, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC && input_on_server) {
+               int as_handle;
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.rename_mailbox.handle        = as_handle;
+               as_noti_data.rename_mailbox.account_id    = mailbox_tbl->account_id;
+               as_noti_data.rename_mailbox.mailbox_id    = input_mailbox_id;
+               as_noti_data.rename_mailbox.mailbox_name  = input_mailbox_name;
+               as_noti_data.rename_mailbox.mailbox_alias = input_mailbox_alias;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_RENAME_MAILBOX, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(output_handle)
+                       *output_handle = as_handle;
+       }
+       else {
+               hAPI = emipc_create_email_api(_EMAIL_API_RENAME_MAILBOX);
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_mailbox_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for input_mailbox_id failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, input_mailbox_name, EM_SAFE_STRLEN(input_mailbox_name)+1 )) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for input_mailbox_path failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, input_mailbox_alias, EM_SAFE_STRLEN(input_mailbox_alias)+1 )) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for input_mailbox_alias failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_on_server, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+               EM_DEBUG_LOG("error VALUE [%d]", err);
+               emipc_destroy_email_api(hAPI);
+       }
+FINISH_OFF:
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+/* API - Delete a mailbox */
+
+EXPORT_API int email_delete_mailbox(int input_mailbox_id, int input_on_server, int *output_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id, input_on_server, output_handle);
+       
+       int err = EMAIL_ERROR_NONE;
+       email_account_server_t account_server_type;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+       
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
+
+       if ( (err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /*  check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(mailbox_tbl->account_id, &account_server_type, false, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC && input_on_server) {
+               int as_handle;
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.delete_mailbox.handle        = as_handle;
+               as_noti_data.delete_mailbox.account_id    = mailbox_tbl->account_id;
+               as_noti_data.delete_mailbox.mailbox_id    = input_mailbox_id;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_DELETE_MAILBOX, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(output_handle)
+                       *output_handle = as_handle;
+       }
+       else {
+               hAPI = emipc_create_email_api(_EMAIL_API_DELETE_MAILBOX);
+
+               EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_mailbox_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_on_server, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               EM_DEBUG_LOG("error VALUE [%d]", err);
+
+               if(input_on_server) {
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), output_handle);
+                       EM_DEBUG_LOG("output_handle [%d]", output_handle);
+               }
+
+               emipc_destroy_email_api(hAPI);
+       }
+
+FINISH_OFF:
+       if (mailbox_tbl) {
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_delete_mailbox_ex(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, int input_on_server, int *output_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_mailbox_id_array[%p] input_mailbox_id_count[%d] input_on_server[%d] output_handle[%p]", input_mailbox_id_array, input_mailbox_id_array, input_mailbox_id_count, input_on_server, output_handle);
+       int err = EMAIL_ERROR_NONE;
+       email_account_server_t account_server_type;
+       task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX task_parameter;
+
+       if(input_account_id == 0 || input_mailbox_id_count <= 0 || input_mailbox_id_array == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /*  check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(input_account_id, &account_server_type, false, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC && input_on_server) {
+               int as_handle;
+               ASNotiData as_noti_data;
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.delete_mailbox_ex.handle            = as_handle;
+               as_noti_data.delete_mailbox_ex.account_id        = input_account_id;
+               as_noti_data.delete_mailbox_ex.mailbox_id_array  = input_mailbox_id_array;
+               as_noti_data.delete_mailbox_ex.mailbox_id_count  = input_mailbox_id_count;
+               as_noti_data.delete_mailbox_ex.on_server         = input_on_server;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_DELETE_MAILBOX_EX, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(output_handle)
+                       *output_handle = as_handle;
+       }
+       else {
+               task_parameter.account_id        = input_account_id;
+               task_parameter.mailbox_id_array  = input_mailbox_id_array;
+               task_parameter.mailbox_id_count  = input_mailbox_id_count;
+               task_parameter.on_server         = input_on_server;
+
+               if((err = emipc_execute_proxy_task(EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX, &task_parameter)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("execute_proxy_task failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_set_mailbox_type(int input_mailbox_id, email_mailbox_type_e input_mailbox_type)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_mailbox_type [%d]", input_mailbox_id, input_mailbox_type);
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_SET_MAILBOX_TYPE);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_mailbox_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_mailbox_type, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+       EM_DEBUG_LOG("error VALUE [%d]", err);
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_set_local_mailbox(int input_mailbox_id, int input_is_local_mailbox)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_is_local_mailbox [%d]", input_mailbox_id, input_is_local_mailbox);
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_SET_LOCAL_MAILBOX);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_mailbox_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_is_local_mailbox, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+       EM_DEBUG_LOG("error VALUE [%d]", err);
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_sync_mailbox_list(int account_id, email_mailbox_t** mailbox_list, int* count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int mailbox_count = 0;
+       int err = EMAIL_ERROR_NONE ;
+       int i = 0;
+       emstorage_mailbox_tbl_t* mailbox_tbl_list = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(mailbox_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_ACCOUNT_ID_NULL(account_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_get_mailbox_list(account_id, 0, EMAIL_MAILBOX_SORT_BY_NAME_ASC, &mailbox_count, &mailbox_tbl_list, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox failed [%d]", err);
+
+
+               goto FINISH_OFF;
+       } else
+               err = EMAIL_ERROR_NONE;
+       
+       if (mailbox_count > 0)  {
+               if (!(*mailbox_list = em_malloc(sizeof(email_mailbox_t) * mailbox_count)))  {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       err= EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               for (i = 0; i < mailbox_count; i++)
+                       em_convert_mailbox_tbl_to_mailbox(mailbox_tbl_list + i, (*mailbox_list) + i);
+       } else
+               *mailbox_list = NULL;
+       
+       *count = mailbox_count;
+       
+       FINISH_OFF:
+       if (mailbox_tbl_list != NULL)
+               emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_get_mailbox_list(int account_id, int mailbox_sync_type, email_mailbox_t** mailbox_list, int* count)
+{
+       EM_DEBUG_FUNC_BEGIN();  
+
+       int mailbox_count = 0;
+       emstorage_mailbox_tbl_t* mailbox_tbl_list = NULL; 
+       int err =EMAIL_ERROR_NONE;
+       int i;
+       
+       EM_IF_NULL_RETURN_VALUE(mailbox_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_ACCOUNT_ID_NULL(account_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_get_mailbox_list(account_id, mailbox_sync_type, EMAIL_MAILBOX_SORT_BY_NAME_ASC, &mailbox_count, &mailbox_tbl_list, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox failed [%d]", err);
+
+               goto FINISH_OFF;
+       } else
+               err = EMAIL_ERROR_NONE;
+       
+       if (mailbox_count > 0)  {
+               if (!(*mailbox_list = em_malloc(sizeof(email_mailbox_t) * mailbox_count)))  {
+                       EM_DEBUG_EXCEPTION("malloc failed for mailbox_list");
+                       err= EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               for (i = 0; i < mailbox_count; i++)
+                       em_convert_mailbox_tbl_to_mailbox(mailbox_tbl_list + i, (*mailbox_list) + i);
+       } else
+               *mailbox_list = NULL;
+       
+       *count = mailbox_count;
+
+FINISH_OFF:
+       if (mailbox_tbl_list != NULL)
+               emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+
+EXPORT_API int email_get_mailbox_list_ex(int account_id, int mailbox_sync_type, int with_count, email_mailbox_t** mailbox_list, int* count)
+{
+       EM_DEBUG_FUNC_BEGIN();  
+
+       int mailbox_count = 0;
+       emstorage_mailbox_tbl_t* mailbox_tbl_list = NULL; 
+       int err =EMAIL_ERROR_NONE;
+       int i;
+       
+       EM_IF_NULL_RETURN_VALUE(mailbox_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_ACCOUNT_ID_NULL(account_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_get_mailbox_list_ex(account_id, mailbox_sync_type, with_count, &mailbox_count, &mailbox_tbl_list, true, &err))  {        
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_list_ex failed [%d]", err);
+
+               goto FINISH_OFF;
+       } else
+               err = EMAIL_ERROR_NONE;
+       
+       if (mailbox_count > 0)  {
+               if (!(*mailbox_list = em_malloc(sizeof(email_mailbox_t) * mailbox_count)))  {
+                       EM_DEBUG_EXCEPTION("malloc failed for mailbox_list");
+                       err= EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               for (i = 0; i < mailbox_count; i++)
+                       em_convert_mailbox_tbl_to_mailbox(mailbox_tbl_list + i, (*mailbox_list) + i);
+       }
+       else
+               *mailbox_list = NULL;
+
+       if ( count )    
+               *count = mailbox_count;
+
+FINISH_OFF:
+       if (mailbox_tbl_list != NULL)
+               emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+/* sowmya.kr, 05-Apr-2010, new MAPI*/
+
+EXPORT_API int email_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type,  email_mailbox_t** mailbox)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int err = EMAIL_ERROR_NONE;
+       email_mailbox_t* curr_mailbox = NULL;
+       emstorage_mailbox_tbl_t* local_mailbox = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(mailbox, EMAIL_ERROR_INVALID_PARAM);    
+       EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM)  ;
+
+
+       if(mailbox_type < EMAIL_MAILBOX_TYPE_INBOX || mailbox_type > EMAIL_MAILBOX_TYPE_USER_DEFINED)
+               return EMAIL_ERROR_INVALID_PARAM;
+       if (!emstorage_get_mailbox_by_mailbox_type(account_id, mailbox_type, &local_mailbox, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+
+               goto FINISH_OFF;
+       } else {
+               err = EMAIL_ERROR_NONE;
+               curr_mailbox = em_malloc(sizeof(email_mailbox_t));
+               memset(curr_mailbox, 0x00, sizeof(email_mailbox_t));
+               em_convert_mailbox_tbl_to_mailbox(local_mailbox, curr_mailbox);
+       }
+
+       *mailbox = curr_mailbox;        
+FINISH_OFF:
+
+       if(local_mailbox)
+               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_mailbox_by_mailbox_id(int input_mailbox_id, email_mailbox_t** output_mailbox)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       email_mailbox_t* curr_mailbox = NULL;
+       emstorage_mailbox_tbl_t* local_mailbox = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(output_mailbox, EMAIL_ERROR_INVALID_PARAM);
+
+       if ( (err = emstorage_get_mailbox_by_id(input_mailbox_id, &local_mailbox)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+               return err;
+       } else {
+               curr_mailbox = em_malloc(sizeof(email_mailbox_t));
+
+               memset(curr_mailbox, 0x00, sizeof(email_mailbox_t));
+
+               em_convert_mailbox_tbl_to_mailbox(local_mailbox, curr_mailbox);
+       }
+
+       *output_mailbox = curr_mailbox;
+
+       emstorage_free_mailbox(&local_mailbox, 1, &err);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_set_mail_slot_size(int account_id, int mailbox_id, int new_slot_size)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_id[%d], new_slot_size[%d]", account_id, mailbox_id, new_slot_size);
+
+       int err = EMAIL_ERROR_NONE;
+
+       if(new_slot_size < 0) {
+               EM_DEBUG_EXCEPTION("new_slot_size should be greater than 0 or should be equal to 0");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_SET_MAIL_SLOT_SIZE);  
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       if (hAPI) {
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &account_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for account_id failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &mailbox_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for account_id failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &new_slot_size, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION(" emipc_add_parameter for new_slot_size failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               } 
+       
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               EM_DEBUG_LOG("email_set_mail_slot_size error VALUE [%d]", err);
+               /*prevent 23139*/
+/*             if(handle) {
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+                       EM_DEBUG_LOG("email_set_mail_slot_size handle VALUE [%d]", handle);
+               } */
+               emipc_destroy_email_api(hAPI);
+               hAPI = NULL;
+               
+       }
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_stamp_sync_time_of_mailbox(int input_mailbox_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d]", input_mailbox_id);
+
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_id, EMAIL_ERROR_INVALID_PARAM);
+
+       err = emstorage_stamp_last_sync_time_of_mailbox(input_mailbox_id, 1);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_free_mailbox(email_mailbox_t** mailbox_list, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_list[%p], count[%d]", mailbox_list, count);
+       int err = EMAIL_ERROR_NONE;
+
+       if (count <= 0 || !mailbox_list || !*mailbox_list) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       email_mailbox_t *p = *mailbox_list;
+       int i;
+
+       for (i = 0; i < count; i++)  {
+               EM_SAFE_FREE(p[i].mailbox_name);
+               EM_SAFE_FREE(p[i].alias);
+       }
+
+       EM_SAFE_FREE(p);
+       *mailbox_list = NULL;
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+
+}
diff --git a/email-api/email-api-network.c b/email-api/email-api-network.c
new file mode 100755 (executable)
index 0000000..3d86f48
--- /dev/null
@@ -0,0 +1,1074 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-network.c
+ * @brief              This file contains the data structures and interfaces of Network related Functionality provided by 
+ *                     email-service . 
+ */
+#include "email-api.h"
+#include "string.h"
+#include "email-convert.h"
+#include "email-api-mailbox.h"
+#include "email-types.h"
+#include "email-utilities.h"
+#include "email-ipc.h"
+#include "email-storage.h"
+
+
+
+
+EXPORT_API int email_send_mail(int mail_id, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], handle[%p]", mail_id, handle);
+       
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t* mail_table_data = NULL;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+
+       if(mail_id <= 0) {
+               EM_DEBUG_EXCEPTION("mail_id is not valid");
+               err= EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if(!emstorage_get_mail_by_id(mail_id, &mail_table_data, true, &err) || !mail_table_data) {
+               EM_DEBUG_EXCEPTION("Failed to get mail by mail_id [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mail_table_data->account_id <= 0) {
+               EM_DEBUG_EXCEPTION ("EM_IF_ACCOUNT_ID_NULL: Account ID [ %d ]  ", mail_table_data->account_id);
+               emstorage_free_mail(&mail_table_data, 1, NULL);
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       EM_DEBUG_LOG("mail_table_data->account_id[%d], mail_table_data->mailbox_name[%s]", mail_table_data->account_id, mail_table_data->mailbox_name);
+
+       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+       /*  check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(mail_table_data->account_id, &account_server_type, false, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+               int as_handle;
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+               
+               /*  noti to active sync */
+               as_noti_data.send_mail.handle     = as_handle;
+               as_noti_data.send_mail.account_id = mail_table_data->account_id;
+               as_noti_data.send_mail.mail_id    = mail_id;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_SEND_MAIL, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(handle)
+                       *handle = as_handle;
+       }
+       else {
+               hAPI = emipc_create_email_api(_EMAIL_API_SEND_MAIL);    
+
+               if (!hAPI ) {
+                       EM_DEBUG_EXCEPTION ("INVALID PARAM: hAPI NULL ");
+                       emstorage_free_mail(&mail_table_data, 1, NULL);
+                       return EMAIL_ERROR_NULL_VALUE;
+               }
+
+               /* mail_id */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&mail_id, sizeof(int))){
+                       EM_DEBUG_EXCEPTION("email_send_mail--Add Param mail_id failed");
+                       emstorage_free_mail(&mail_table_data, 1, NULL);
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("email_send_mail--emipc_execute_proxy_api failed  ");
+                       emstorage_free_mail(&mail_table_data, 1, NULL);
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_CRASH);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               if (err == EMAIL_ERROR_NONE) {
+                       if(handle)
+                               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+               }
+       }
+
+FINISH_OFF:
+       emipc_destroy_email_api(hAPI);
+       hAPI = (HIPC_API)NULL;
+
+       emstorage_free_mail(&mail_table_data, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;     
+}
+
+EXPORT_API int email_send_mail_with_downloading_attachment_of_original_mail(int input_mail_id, int *output_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], output_handle[%p]", input_mail_id, output_handle);
+
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t* mail_table_data = NULL;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL task_parameter;
+
+       if(input_mail_id <= 0) {
+               EM_DEBUG_EXCEPTION("mail_id is not valid");
+               err= EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if(!emstorage_get_mail_by_id(input_mail_id, &mail_table_data, true, &err) || !mail_table_data) {
+               EM_DEBUG_EXCEPTION("Failed to get mail by mail_id [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mail_table_data->account_id <= 0) {
+               EM_DEBUG_EXCEPTION ("EM_IF_ACCOUNT_ID_NULL: Account ID [ %d ]  ", mail_table_data->account_id);
+               emstorage_free_mail(&mail_table_data, 1, NULL);
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       EM_DEBUG_LOG("mail_table_data->account_id[%d], mail_table_data->mailbox_name[%s]", mail_table_data->account_id, mail_table_data->mailbox_name);
+
+       /*  check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(mail_table_data->account_id, &account_server_type, false, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+               int as_handle;
+               ASNotiData as_noti_data;
+
+               memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.send_mail_with_downloading_attachment_of_original_mail.handle     = as_handle;
+               as_noti_data.send_mail_with_downloading_attachment_of_original_mail.mail_id    = input_mail_id;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_SEND_MAIL_WITH_DOWNLOADING_OF_ORIGINAL_MAIL, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(output_handle)
+                       *output_handle = as_handle;
+       }
+       else {
+               task_parameter.mail_id        = input_mail_id;
+
+               if((err = emipc_execute_proxy_task(EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL, &task_parameter)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("execute_proxy_task failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       emipc_destroy_email_api(hAPI);
+       hAPI = (HIPC_API)NULL;
+
+       emstorage_free_mail(&mail_table_data, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_send_saved(int account_id, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], handle[%p]", account_id, handle);
+       
+       char* pOptionStream = NULL;
+       int err = EMAIL_ERROR_NONE;
+       
+       EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_ACCOUNT_ID_NULL(account_id, EMAIL_ERROR_INVALID_PARAM);
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_SEND_SAVED);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+       
+       /* Account ID */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &(account_id), sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter account_id failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_SAFE_FREE(pOptionStream);
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);        
+       emipc_destroy_email_api(hAPI);
+       
+       hAPI = NULL;
+       EM_SAFE_FREE(pOptionStream);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+}
+
+EXPORT_API int email_sync_header(int input_account_id, int input_mailbox_id, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id[%d], input_mailbox_id[%d] handle[%p]", input_account_id, input_mailbox_id, handle);
+       int err = EMAIL_ERROR_NONE;     
+       /* int total_count = 0; */
+       
+       EM_IF_ACCOUNT_ID_NULL(input_account_id, EMAIL_ERROR_INVALID_PARAM);
+
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+       /*  2010/02/12 ch715.lee : check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(input_account_id, &account_server_type, true, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+               int as_handle;
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       goto FINISH_OFF;
+               }
+               
+               /*  noti to active sync */
+               as_noti_data.sync_header.handle = as_handle;
+               as_noti_data.sync_header.account_id = input_account_id;
+               /* In case that Mailbox is NULL,   SYNC ALL MAILBOX */
+               as_noti_data.sync_header.mailbox_id = input_mailbox_id;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_SYNC_HEADER, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(handle)
+                       *handle = as_handle;
+
+       }
+       else {
+               hAPI = emipc_create_email_api(_EMAIL_API_SYNC_HEADER);  
+
+               EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               /* input_account_id */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_account_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               /* input_mailbox_id */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_mailbox_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+                       
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);        
+
+               if (err != EMAIL_ERROR_NONE)
+                       goto FINISH_OFF;
+
+               if(handle)
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);      
+       }
+
+FINISH_OFF:
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+}
+
+
+EXPORT_API int email_sync_header_for_all_account(int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("handle[%p]", handle);
+       char* mailbox_stream = NULL;
+       int err = EMAIL_ERROR_NONE;     
+       HIPC_API hAPI = NULL;
+       int return_handle;
+       ASNotiData as_noti_data;
+       int i, account_count = 0;
+       emstorage_account_tbl_t *account_tbl_array = NULL;
+       int as_err;
+       int input_account_id = ALL_ACCOUNT;
+       int input_mailbox_id = 0; /* all case */
+
+       hAPI = emipc_create_email_api(_EMAIL_API_SYNC_HEADER);  
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* input_account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       /* input_account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&input_mailbox_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_SAFE_FREE(mailbox_stream);
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+               
+        emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);       
+
+        if (err != EMAIL_ERROR_NONE)
+                goto FINISH_OFF;
+
+          emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), &return_handle);
+
+       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+       /*  Get all accounts for sending notification to active sync engine. */
+       if (!emstorage_get_account_list(&account_count, &account_tbl_array , true, false, &as_err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [ %d ]  ", as_err);
+
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < account_count; i++) {
+               if ( account_tbl_array[i].incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+                       /*  use returned handle value for a active sync handle */
+                       /* int as_handle; */
+                       /*
+                       if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                               EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                               goto FINISH_OFF;
+                       }
+                       */
+                       
+                       /*  noti to active sync */
+                       as_noti_data.sync_header.handle = return_handle;
+                       as_noti_data.sync_header.account_id = account_tbl_array[i].account_id;
+                       /* In case that Mailbox is NULL,   SYNC ALL MAILBOX */
+                       as_noti_data.sync_header.mailbox_id = 0;
+
+                       if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_SYNC_HEADER, &as_noti_data) == false) {
+                               EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+        
+        if(handle)
+               *handle = return_handle;
+
+FINISH_OFF:
+
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       if ( account_tbl_array )
+               emstorage_free_account(&account_tbl_array, account_count, NULL);
+       
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+}
+
+EXPORT_API int email_download_body(int mail_id, int with_attachment, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d],with_attachment[%d]", mail_id, with_attachment);
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t* mail_table_data = NULL;
+       int account_id = 0;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+       if(mail_id <= 0) {
+               EM_DEBUG_EXCEPTION("mail_id is not valid");
+               err= EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if(!emstorage_get_mail_by_id(mail_id, &mail_table_data, true, &err) || !mail_table_data ) {
+               EM_DEBUG_EXCEPTION("Failed to get mail by mail_id [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mail_table_data->account_id <= 0) {
+               EM_DEBUG_EXCEPTION("EM_IF_ACCOUNT_ID_NULL: Account ID [ %d ]  ", mail_table_data->account_id);
+               goto FINISH_OFF;
+       }
+
+       account_id = mail_table_data->account_id;
+               
+       /*  2010/02/12 ch715.lee : check account bind type and branch off  */
+       if ( em_get_account_server_type_by_account_id(account_id, &account_server_type, true, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+               int as_handle;
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       goto FINISH_OFF;
+               }
+               
+               /*  noti to active sync */
+               as_noti_data.download_body.handle = as_handle;
+               as_noti_data.download_body.account_id = account_id;
+               as_noti_data.download_body.mail_id = mail_id;
+               as_noti_data.download_body.with_attachment = with_attachment;
+
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_DOWNLOAD_BODY, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(handle)
+                       *handle = as_handle;
+       } else {
+               hAPI = emipc_create_email_api(_EMAIL_API_DOWNLOAD_BODY);
+
+               EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               /* Account Id */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+               /* Mail Id */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&mail_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               /* with_attachment */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&with_attachment, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+               
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+                       
+                emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);       
+                if (err != EMAIL_ERROR_NONE)           
+                        goto FINISH_OFF;
+                
+                if(handle)     
+                {
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+                       EM_DEBUG_LOG("RETURN VALUE : %d  handle %d", err, *handle);
+
+                }
+       }
+
+FINISH_OFF:
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       if(mail_table_data) {
+               emstorage_free_mail(&mail_table_data, 1, &err);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+
+}
+
+
+/* API - Downloads the Email Attachment Information [ INTERNAL ] */
+
+EXPORT_API int email_download_attachment(int mail_id, int nth, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], nth[%d], handle[%p]", mail_id, nth, handle);
+       char* mailbox_stream = NULL;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t* mail_table_data = NULL;
+       int account_id = 0;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+       if(mail_id <= 0) {
+               EM_DEBUG_EXCEPTION("mail_id is not valid");
+               err= EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if(!emstorage_get_mail_by_id(mail_id, &mail_table_data, true, &err) || !mail_table_data ) {
+               EM_DEBUG_EXCEPTION("Failed to get mail by mail_id [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mail_table_data->account_id <= 0) {
+               EM_DEBUG_EXCEPTION("EM_IF_ACCOUNT_ID_NULL: Account ID [ %d ]  ", mail_table_data->account_id);
+               goto FINISH_OFF;
+       }
+
+       account_id = mail_table_data->account_id;
+       
+       if ( em_get_account_server_type_by_account_id(account_id, &account_server_type, true, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+               int as_handle;
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       goto FINISH_OFF;
+               }
+               
+               /*  noti to active sync */
+               as_noti_data.download_attachment.handle = as_handle;
+               as_noti_data.download_attachment.account_id = account_id;
+               as_noti_data.download_attachment.mail_id = mail_id;
+               as_noti_data.download_attachment.attachment_order = nth;
+               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_DOWNLOAD_ATTACHMENT, &as_noti_data) == false) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(handle)
+                       *handle = as_handle;
+       } else {
+               hAPI = emipc_create_email_api(_EMAIL_API_DOWNLOAD_ATTACHMENT);
+
+               EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               /* Account Id */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               /* Mail ID */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &(mail_id), sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter mail_id failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               /* nth */
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &(nth), sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter mail_id failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+               }
+
+               /* Execute API */
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_SAFE_FREE(mailbox_stream);
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               if (err != EMAIL_ERROR_NONE)            
+                       goto FINISH_OFF;
+                
+               if(handle)
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+               
+       }
+       
+FINISH_OFF:
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       if(mail_table_data) {
+               emstorage_free_mail(&mail_table_data, 1, &err);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+       
+}
+
+
+EXPORT_API int email_cancel_job(int input_account_id, int input_handle, email_cancelation_type input_cancel_type)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_handle [%d], input_cancel_type [%d]", input_account_id, input_handle, input_cancel_type);
+       int err = EMAIL_ERROR_NONE;
+       email_account_server_t account_server_type;
+       HIPC_API hAPI = NULL;
+       ASNotiData as_noti_data;
+       emstorage_account_tbl_t *account_list = NULL;
+       int i, account_count = 0;
+
+       if(input_account_id < 0)
+               return EMAIL_ERROR_INVALID_PARAM;
+
+       if ( input_account_id == ALL_ACCOUNT ) {
+               /*  this means that job is executed with all account */
+               /*  Get all accounts for sending notification to active sync engine. */
+               if (!emstorage_get_account_list(&account_count, &account_list , true, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               for(i = 0; i < account_count; i++) {
+                       if ( em_get_account_server_type_by_account_id(account_list[i].account_id, &account_server_type, true, &err) == false ) {
+                               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+                               memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+                               as_noti_data.cancel_job.account_id  = account_list[i].account_id;
+                               as_noti_data.cancel_job.handle      = input_handle;
+                               as_noti_data.cancel_job.cancel_type = input_cancel_type;
+
+
+                               if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_CANCEL_JOB, &as_noti_data) == false) {
+                                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+
+               /*  request canceling to stub */
+               hAPI = emipc_create_email_api(_EMAIL_API_CANCEL_JOB);
+
+               if (!hAPI) {
+                       EM_DEBUG_EXCEPTION ("INVALID PARAM: hAPI NULL ");
+                       err = EMAIL_ERROR_NULL_VALUE;
+                       goto FINISH_OFF;
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_account_id, sizeof(int))) {         /*  input_account_id == 0 */
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_NULL_VALUE;
+                       goto FINISH_OFF;
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_handle, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                       err = EMAIL_ERROR_NULL_VALUE;
+                       goto FINISH_OFF;
+               }
+
+               /* Execute API */
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               emipc_destroy_email_api(hAPI);
+               hAPI = NULL;
+       }
+       else {
+               if ( em_get_account_server_type_by_account_id(input_account_id, &account_server_type, true, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+                       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+                       as_noti_data.cancel_job.account_id = input_account_id;
+                       as_noti_data.cancel_job.handle = input_handle;
+
+                       if ( em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_CANCEL_JOB, &as_noti_data) == false) {
+                               EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               } else {
+                       hAPI = emipc_create_email_api(_EMAIL_API_CANCEL_JOB);
+
+                       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+                       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_account_id, sizeof(int))) {
+                               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+                               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+                       }
+
+                       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &input_handle, sizeof(int))) {
+                               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+                               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+                       }
+
+                       /* Execute API */
+                       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+                       }
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+                       emipc_destroy_email_api(hAPI);
+                       hAPI = NULL;
+               }
+       }
+
+FINISH_OFF:
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+       if (account_list)
+               emstorage_free_account(&account_list, account_count, NULL);
+               
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+}
+
+
+
+EXPORT_API int email_get_pending_job(email_action_t action, int account_id, int mail_id, email_event_status_type_t * status)
+{
+       EM_DEBUG_FUNC_BEGIN("action[%d], account_id[%d], mail_id[%d], status[%p]", action, account_id, mail_id, status);
+       
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_ACCOUNT_ID_NULL(account_id, EMAIL_ERROR_NULL_VALUE);
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_GET_PENDING_JOB);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &action, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter action failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &account_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter account_id failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, &mail_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter account_id failed ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed  ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+       if(status) {
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), status);
+               EM_DEBUG_LOG("status : %d ", *status);
+       }
+       
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+
+}
+
+
+
+EXPORT_API int email_get_network_status(int* on_sending, int* on_receiving)
+{
+       EM_DEBUG_FUNC_BEGIN("on_sending[%p], on_receiving[%p]", on_sending, on_receiving);
+       int err = EMAIL_ERROR_NONE;
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_NETWORK_GET_STATUS);
+
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* Execute API */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               emipc_destroy_email_api(hAPI);
+               hAPI = NULL;
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE ;
+               EM_DEBUG_FUNC_END("err [%d]", err); return err;
+       }
+
+       if(on_sending)
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), on_sending );
+       if(on_receiving)        
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), on_receiving);
+
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+}
+
+EXPORT_API int email_sync_imap_mailbox_list(int account_id, int *handle)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+
+       if(account_id <= 0) {
+               EM_DEBUG_LOG("invalid parameters");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_GET_IMAP_MAILBOX_LIST);       
+
+       /* account_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&account_id, sizeof(int))) {
+               EM_DEBUG_LOG("emipc_add_parameter failed  ");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if(!emipc_execute_proxy_api(hAPI))  {
+               EM_DEBUG_LOG("ipcProxy_ExecuteAsyncAPI failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+       if(handle)
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);  
+       return err;
+}
+
+EXPORT_API int email_search_mail_on_server(int input_account_id, int input_mailbox_id, email_search_filter_t *input_search_filter_list, int input_search_filter_count, int *output_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_mailbox_id [%d], input_search_filter_list [%p], input_search_filter_count [%d], output_handle [%p]", input_account_id, input_mailbox_id, input_search_filter_list, input_search_filter_count, output_handle);
+
+       int       err = EMAIL_ERROR_NONE;
+       int       return_value = 0;
+       int       stream_size_for_search_filter_list = 0;
+       char     *stream_for_search_filter_list = NULL;
+       HIPC_API  hAPI = NULL;
+       email_account_server_t account_server_type = EMAIL_SERVER_TYPE_NONE;
+       ASNotiData as_noti_data;
+
+       EM_IF_NULL_RETURN_VALUE(input_account_id,         EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_mailbox_id,         EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(input_search_filter_list, EMAIL_ERROR_INVALID_PARAM);
+
+       memset(&as_noti_data, 0, sizeof(ASNotiData)); /* initialization of union members */
+
+       if ( em_get_account_server_type_by_account_id(input_account_id, &account_server_type, true, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+               int as_handle = 0;
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.search_mail_on_server.handle              = as_handle;
+               as_noti_data.search_mail_on_server.account_id          = input_account_id;
+               as_noti_data.search_mail_on_server.mailbox_id          = input_mailbox_id;
+               as_noti_data.search_mail_on_server.search_filter_list  = input_search_filter_list;
+               as_noti_data.search_mail_on_server.search_filter_count = input_search_filter_count;
+
+               return_value = em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_SEARCH_ON_SERVER, &as_noti_data);
+
+               if ( return_value == false ) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(output_handle)
+                       *output_handle = as_handle;
+       }
+       else
+       {
+               hAPI = emipc_create_email_api(_EMAIL_API_SEARCH_MAIL_ON_SERVER);
+
+               EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (void*)&input_account_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+                       err = EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (void*)&input_mailbox_id, sizeof(int))){
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+                       err = EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               stream_for_search_filter_list = em_convert_search_filter_to_byte_stream(input_search_filter_list, input_search_filter_count, &stream_size_for_search_filter_list);
+
+               EM_PROXY_IF_NULL_RETURN_VALUE(stream_for_search_filter_list, hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, stream_for_search_filter_list, stream_size_for_search_filter_list)) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+                       err = EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+               if (err != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("_EMAIL_API_SEARCH_MAIL_ON_SERVER failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if(output_handle)
+                       emipc_get_parameter(hAPI, ePARAMETER_OUT, 1, sizeof(int), output_handle);
+       }
+
+FINISH_OFF:
+       if(hAPI) {
+               emipc_destroy_email_api(hAPI);
+               hAPI = NULL;
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_clear_result_of_search_mail_on_server(int input_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d]", input_account_id);
+
+       int       err = EMAIL_ERROR_NONE;
+       int       return_value = 0;
+       HIPC_API  hAPI = NULL;
+       email_account_server_t account_server_type = EMAIL_SERVER_TYPE_NONE;
+       ASNotiData as_noti_data;
+
+       EM_IF_NULL_RETURN_VALUE(input_account_id,         EMAIL_ERROR_INVALID_PARAM);
+
+       memset(&as_noti_data, 0, sizeof(ASNotiData)); /* initialization of union members */
+
+       if ( em_get_account_server_type_by_account_id(input_account_id, &account_server_type, true, &err) == false ) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( account_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+               int as_handle = 0;
+
+               if ( em_get_handle_for_activesync(&as_handle, &err) == false ) {
+                       EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed[%d].", err);
+                       goto FINISH_OFF;
+               }
+
+               /*  noti to active sync */
+               as_noti_data.clear_result_of_search_mail_on_server.handle              = as_handle;
+               as_noti_data.clear_result_of_search_mail_on_server.account_id          = input_account_id;
+
+               return_value = em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_CLEAR_RESULT_OF_SEARCH_ON_SERVER, &as_noti_data);
+
+               if ( return_value == false ) {
+                       EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed.");
+                       err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+       else {
+               hAPI = emipc_create_email_api(_EMAIL_API_CLEAR_RESULT_OF_SEARCH_MAIL_ON_SERVER);
+
+               EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+               if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (void*)&input_account_id, sizeof(int))) {
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+                       err = EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+                       EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+               }
+
+               emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+               if (err != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("_EMAIL_API_CLEAR_RESULT_OF_SEARCH_MAIL_ON_SERVER failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       if(hAPI) {
+               emipc_destroy_email_api(hAPI);
+               hAPI = NULL;
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-api/email-api-rule.c b/email-api/email-api-rule.c
new file mode 100755 (executable)
index 0000000..74db35e
--- /dev/null
@@ -0,0 +1,227 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-rule.c
+ * @brief              This file contains the data structures and interfaces of Rule related Functionality provided by 
+ *                     email-service . 
+ */
+
+#include "email-api.h"
+#include "string.h"
+#include "email-convert.h"
+#include "email-storage.h"
+#include "email-utilities.h"
+#include "email-ipc.h"
+
+EXPORT_API int email_get_rule(int filter_id, email_rule_t** filtering_set)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_id[%d], filtering_set[%p]", filter_id, filtering_set);
+
+       int err = 0;
+
+       EM_IF_NULL_RETURN_VALUE(filtering_set, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(filter_id, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!emstorage_get_rule_by_id(0, filter_id, (emstorage_rule_tbl_t**)filtering_set, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_rule_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       } else
+               err = EMAIL_ERROR_NONE;
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("error value [%d]", err);
+       return err;
+}
+
+
+EXPORT_API int email_get_rule_list(email_rule_t** filtering_set, int* count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int err = EMAIL_ERROR_NONE;
+       int is_completed = 0;
+       
+       EM_IF_NULL_RETURN_VALUE(filtering_set, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
+
+       *count = 1000;
+       
+       if (!emstorage_get_rule(0, 0, 0, count, &is_completed, (emstorage_rule_tbl_t**)filtering_set, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_rule failed [%d]", err);
+
+
+               goto FINISH_OFF;
+       } else
+               err = EMAIL_ERROR_NONE;
+
+
+FINISH_OFF:
+       
+       return err;
+
+}
+
+EXPORT_API int email_add_rule(email_rule_t* filtering_set)
+{
+       EM_DEBUG_FUNC_BEGIN("filtering_set[%p]", filtering_set);
+       
+       int size = 0;
+       int err = EMAIL_ERROR_NONE;
+       char* stream = NULL;
+       
+       EM_IF_NULL_RETURN_VALUE(filtering_set, EMAIL_ERROR_INVALID_PARAM);
+
+       /* make rule info */
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_ADD_RULE);    
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       stream = em_convert_rule_to_byte_stream(filtering_set, &size);
+       EM_PROXY_IF_NULL_RETURN_VALUE(stream, hAPI, EMAIL_ERROR_NULL_VALUE);
+       if(!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, stream, size)) {
+               EM_DEBUG_EXCEPTION("Add Param Failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       /* pass rule info */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api Failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+               
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);        
+
+       emipc_destroy_email_api(hAPI);
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("error value [%d]", err);
+       return err;
+}
+
+
+
+EXPORT_API int email_update_rule(int filter_id, email_rule_t* new_set)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_id[%d], new_set[%p]", filter_id, new_set);
+       
+       int size = 0;
+       char* stream =  NULL;
+       int err = EMAIL_ERROR_NONE;
+
+       EM_IF_NULL_RETURN_VALUE(filter_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(new_set, EMAIL_ERROR_INVALID_PARAM);
+       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_UPDATE_RULE);
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       /* make filter info */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&filter_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("Add Param filter_id Failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       stream = em_convert_rule_to_byte_stream(new_set, &size);
+       if(NULL == stream) {
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+       if(!emipc_add_dynamic_parameter(hAPI, ePARAMETER_IN, stream, size)){
+               EM_DEBUG_EXCEPTION("Add Param new_set Failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+       
+       /* request update rule with filter info */
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api Failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+
+       /* get result */
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+               
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("error value [%d]", err);
+       return err;
+}
+
+
+
+
+EXPORT_API int email_delete_rule(int filter_id)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_id[%d]", filter_id);
+       
+       int err = EMAIL_ERROR_NONE;
+               
+       EM_IF_NULL_RETURN_VALUE(filter_id, EMAIL_ERROR_INVALID_PARAM);
+                       
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_DELETE_RULE);
+       
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+       
+       /* filter_id */
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)&filter_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+               
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_IPC_SOCKET_FAILURE);
+       }
+       
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       EM_DEBUG_FUNC_END("error value [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_free_rule (email_rule_t** filtering_set, int count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE, i;  
+
+       EM_IF_NULL_RETURN_VALUE(filtering_set, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(count, EMAIL_ERROR_INVALID_PARAM);
+       
+       if (count > 0)  {
+               email_rule_t* p = *filtering_set;
+               
+               for (i = 0; i < count; i++) {
+                       EM_SAFE_FREE(p[i].value);
+               }
+               
+               EM_SAFE_FREE(p); *filtering_set = NULL;
+       }
+       
+       EM_DEBUG_FUNC_END("error value [%d]", err);
+       return err;
+}
+
+
diff --git a/email-api/email-api-smime.c b/email-api/email-api-smime.c
new file mode 100755 (executable)
index 0000000..ade7f9c
--- /dev/null
@@ -0,0 +1,476 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with Email Engine.
+ * @file               email-api-smime.c
+ * @brief              This file contains the data structures and interfaces of SMIME related Functionality provided by
+ *                     Email Engine . 
+ */
+
+#include "email-api.h"
+#include "string.h"
+#include "email-convert.h"
+#include "email-api-account.h"
+#include "email-storage.h"
+#include "email-utilities.h"
+#include "email-core-mail.h"
+#include "email-core-mime.h"
+#include "email-core-account.h"
+#include "email-core-cert.h"
+#include "email-core-smime.h"
+#include "email-ipc.h"
+
+EXPORT_API int email_add_certificate(char *certificate_path, char *email_address)
+{
+       EM_DEBUG_FUNC_BEGIN("Certificate path : [%s]", certificate_path);
+       int result_from_ipc = 0;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (!certificate_path) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_ADD_CERTIFICATE);
+       if (hAPI == NULL) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (!emipc_add_parameter(hAPI, ePARAMETER_IN, certificate_path, EM_SAFE_STRLEN(certificate_path)+1)) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter certificate_path[%s] failed", certificate_path);
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (!emipc_add_parameter(hAPI, ePARAMETER_IN, email_address, EM_SAFE_STRLEN(email_address)+1)) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter certificate_path[%s] failed", email_address);
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (emipc_execute_proxy_api(hAPI) < 0) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       result_from_ipc = emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+       if (result_from_ipc != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_get_parameter failed");
+               err = EMAIL_ERROR_IPC_CRASH;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if (hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_delete_certificate(char *email_address)
+{
+       EM_DEBUG_FUNC_BEGIN("Eamil_address : [%s]", email_address);
+       int result_from_ipc = 0;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (!email_address) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_DELETE_CERTIFICATE);
+       if (hAPI == NULL) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (!emipc_add_parameter(hAPI, ePARAMETER_IN, email_address, EM_SAFE_STRLEN(email_address)+1)) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter email_address[%s] failed", email_address);
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (emipc_execute_proxy_api(hAPI) < 0) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       result_from_ipc = emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+       if (result_from_ipc != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_get_parameter failed");
+               err = EMAIL_ERROR_IPC_CRASH;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if (hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_certificate(char *email_address, email_certificate_t **certificate)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       char temp_email_address[130] = {0, };
+       emstorage_certificate_tbl_t *cert = NULL;
+       
+       EM_IF_NULL_RETURN_VALUE(email_address, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(certificate, EMAIL_ERROR_INVALID_PARAM);
+       SNPRINTF(temp_email_address, sizeof(temp_email_address), "<%s>", email_address);
+       
+       if (!emstorage_get_certificate_by_email_address(temp_email_address, &cert, false, 0, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_certificate_by_index failed - %d", err);
+               return err;
+       }
+
+       if (!em_convert_certificate_tbl_to_certificate(cert, certificate, &err)) {
+               EM_DEBUG_EXCEPTION("em_convert_certificate_tbl_to_certificate failed");
+               return err;
+       }       
+       
+       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_decrypt_message(int mail_id, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id : [%d]", mail_id);
+       int err = EMAIL_ERROR_NONE;
+       int p_output_attachment_count = 0;
+       char *decrypt_filepath = NULL;
+       email_mail_data_t *p_output_mail_data = NULL;
+       email_attachment_data_t *p_output_attachment_data = NULL;
+       emstorage_account_tbl_t *p_account_tbl = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(mail_id, EMAIL_ERROR_INVALID_PARAM);
+
+       if (!output_mail_data || !output_attachment_data || !output_attachment_count) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ((err = emcore_get_mail_data(mail_id, &p_output_mail_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_data failed");
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_account_by_id(p_output_mail_data->account_id, EMAIL_ACC_GET_OPT_OPTIONS, &p_account_tbl, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ((err = emcore_get_attachment_data_list(mail_id, &p_output_attachment_data, &p_output_attachment_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_attachment_data_list failed");
+               goto FINISH_OFF;
+       }
+
+       if (p_output_attachment_count != 1 || !p_output_attachment_data) {
+               EM_DEBUG_EXCEPTION("This is not the encrypted mail");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_smime_set_decrypt_message(p_output_attachment_data->attachment_path, p_account_tbl->certificate_path, &decrypt_filepath, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_smime_set_decrypt_message failed");
+               goto FINISH_OFF;
+       }
+
+       /* Change decrpyt_message to mail_data_t */
+       if (!emcore_parse_mime_file_to_mail(decrypt_filepath, output_mail_data, output_attachment_data, output_attachment_count, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_parse_mime_file_to_mail failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if (p_account_tbl)
+               emstorage_free_account(&p_account_tbl, 1, NULL);
+
+       if (p_output_mail_data)
+               email_free_mail_data(&p_output_mail_data, 1);
+
+       if (p_output_attachment_data)
+               email_free_attachment_data(&p_output_attachment_data, p_output_attachment_count);
+
+       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_verify_signature(int mail_id, int *verify)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id : [%d]", mail_id);
+       int result_from_ipc = 0;
+       int err = EMAIL_ERROR_NONE;
+       int p_verify = 0;
+
+       EM_IF_NULL_RETURN_VALUE(mail_id, EMAIL_ERROR_INVALID_PARAM);    
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_VERIFY_SIGNATURE);
+       if (hAPI == NULL) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (!emipc_add_parameter(hAPI, ePARAMETER_IN, &mail_id, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter pass_phrase[%d] failed", mail_id);
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (emipc_execute_proxy_api(hAPI) < 0) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       result_from_ipc = emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &p_verify);
+       if (result_from_ipc != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_get_parameter failed");
+               err = EMAIL_ERROR_IPC_CRASH;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if (hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       if (verify != NULL)
+               *verify = p_verify;
+
+       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_verify_certificate(char *certificate_path, int *verify)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate : [%s]", certificate_path);
+       int err = EMAIL_ERROR_NONE;
+       int result_from_ipc = 0;
+       int p_verify = 0;
+       
+       if (!certificate_path) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       HIPC_API hAPI = emipc_create_email_api(_EMAIL_API_VERIFY_CERTIFICATE);
+       if (hAPI == NULL) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (!emipc_add_parameter(hAPI, ePARAMETER_IN, certificate_path, EM_SAFE_STRLEN(certificate_path)+1)) {
+               EM_DEBUG_EXCEPTION("emipc_add_paramter failed : [%s]", certificate_path);
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if (emipc_execute_proxy_api(hAPI) < 0) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       result_from_ipc = emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &p_verify);
+       if (result_from_ipc != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_get_parameter failed");
+               err = EMAIL_ERROR_IPC_CRASH;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if (hAPI)       
+               emipc_destroy_email_api(hAPI);
+
+       if (verify != NULL)
+               *verify = p_verify;
+
+       EM_DEBUG_FUNC_END("ERROR CODE [%d]", err);
+       return err;
+}
+
+/*
+EXPORT_API int email_check_ocsp_status(char *email_address, char *response_url, unsigned *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("email_address : [%s], response_url : [%s], handle : [%p]", email_address, response_url, handle);
+
+       EM_IF_NULL_RETURN_VALUE(email_address, EMAIL_ERROR_INVALID_PARAM);
+
+       int err = EMAIL_ERROR_NONE;
+       HIPC_API hAPI = NULL;
+
+       hAPI = emipc_create_email_api(_EMAIL_API_CHECK_OCSP_STATUS);
+       
+       EM_IF_NULL_RETURN_VALUE(hAPI, EMAIL_ERROR_NULL_VALUE);
+
+       if (!emipc_add_parameter(hAPI, ePARAMETER_IN, email_address, EM_SAFE_STRLEN(email_address)+1)) {
+               EM_DEBUG_EXCEPTION("email_check_ocsp_status--ADD Param email_address failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if (!emipc_add_parameter(hAPI, ePARAMETER_IN, response_url, EM_SAFE_STRLEN(response_url)+1)) {
+               EM_DEBUG_EXCEPTION("email_check_ocsp_status--ADD Param response_url failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       if (emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("email_check_oscp_status--emipc_execute_proxy_api failed");
+               EM_PROXY_IF_NULL_RETURN_VALUE(0, hAPI, EMAIL_ERROR_NULL_VALUE);
+       }
+
+       emipc_get_paramter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+       if (err == EMAIL_ERROR_NONE) {
+               if (handle)
+                       emipc_get_paramter(hAPI, ePARAMETER_OUT, 1, sizeof(int), handle);
+       }
+}
+*/
+EXPORT_API int email_validate_certificate(int account_id, char *email_address, unsigned *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id : [%d], email_address : [%s], handle : [%p]", account_id, email_address, handle);
+       
+       EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(email_address, EMAIL_ERROR_INVALID_PARAM);
+
+       int err = EMAIL_ERROR_NONE;
+       int as_handle = 0;
+       email_account_server_t account_server_type;
+       ASNotiData as_noti_data;
+
+       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+       if (em_get_account_server_type_by_account_id(account_id, &account_server_type, false, &err)     == false) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (account_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               EM_DEBUG_EXCEPTION("This api is not supported except of active sync");
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (em_get_handle_for_activesync(&as_handle, &err) == false) {
+               EM_DEBUG_EXCEPTION("em_get_handle_for_activesync_failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;                
+       }
+
+       as_noti_data.validate_certificate.handle = as_handle;
+       as_noti_data.validate_certificate.account_id = account_id;
+       as_noti_data.validate_certificate.email_address = strdup(email_address);
+
+       if (em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_VALIDATE_CERTIFICATE, &as_noti_data) == false) {
+               EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed");
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (handle)
+               *handle = as_handle;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_get_resolve_recipients(int account_id, char *email_address, unsigned *handle)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id : [%d], email_address : [%s], handle : [%p]", account_id, email_address, handle);
+       
+       EM_IF_NULL_RETURN_VALUE(account_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(email_address, EMAIL_ERROR_INVALID_PARAM);
+
+       int err = EMAIL_ERROR_NONE;
+       int as_handle = 0;
+       email_account_server_t account_server_type;
+       ASNotiData as_noti_data;
+
+       memset(&as_noti_data, 0x00, sizeof(ASNotiData));
+
+       if (em_get_account_server_type_by_account_id(account_id, &account_server_type, false, &err)     == false) {
+               EM_DEBUG_EXCEPTION("em_get_account_server_type_by_account_id failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (account_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               EM_DEBUG_EXCEPTION("This api is not supported except of active sync");
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (em_get_handle_for_activesync(&as_handle, &err) == false) {
+               EM_DEBUG_EXCEPTION("em_get_handle_for_activesync_failed[%d]", err);
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;                
+       }
+
+       as_noti_data.get_resolve_recipients.handle = as_handle;
+       as_noti_data.get_resolve_recipients.account_id = account_id;
+       as_noti_data.get_resolve_recipients.email_address = strdup(email_address);
+
+       if (em_send_notification_to_active_sync_engine(ACTIVE_SYNC_NOTI_RESOLVE_RECIPIENT, &as_noti_data) == false) {
+               EM_DEBUG_EXCEPTION("em_send_notification_to_active_sync_engine failed");
+               err = EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (handle)
+               *handle = as_handle;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int email_free_certificate(email_certificate_t **certificate, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate[%p], count[%d]", certificate, count);
+       int err = EMAIL_ERROR_NONE;
+       emcore_free_certificate(certificate, count, &err);
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-api/include/email-api-account.h b/email-api/include/email-api-account.h
new file mode 100755 (executable)
index 0000000..0744bf9
--- /dev/null
@@ -0,0 +1,411 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_API_ACCOUNT_H__
+#define __EMAIL_API_ACCOUNT_H__
+
+#include "email-types.h"
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_API_ACCOUNT Email Account API
+* @{
+*/
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-account.h
+ * @author     Kyuho Jo <kyuho.jo@samsung.com>
+ * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
+ * @version    0.1
+ * @brief              This file contains the data structures and interfaces of Accounts provided by
+ *                     email-service .
+ *
+* @{
+
+* @code
+*      #include "email-api-account.h"
+*       bool
+*              other_app_invoke_uniform_api_sample(int* error_code)
+*      {
+*      email_account_t *account = NULL;
+*      email_account_t *new_account = NULL;
+*
+*      account = malloc(sizeof(email_account_t));
+*      memset(account, 0x00, sizeof(email_account_t));
+*
+*      account->retrieval_mode         = 1;
+*      account->incoming_server_secure_connection           = 1;
+*      account->outgoing_server_type    = EMAIL_SERVER_TYPE_SMTP;
+*      account->outgoing_server_port_number       = EMAIL_SMTP_PORT;
+*      account->outgoing_server_need_authentication           = 1;
+*      account->account_name           = strdup("gmail");
+*      account->display_name           = strdup("Tom");
+*      account->user_email_address             = strdup("tom@gmail.com");
+*      account->reply_to_addr          = strdup("tom@gmail.com");
+*      account->return_addr            = strdup("tom@gmail.com");
+*      account->incoming_server_type  = EMAIL_SERVER_TYPE_POP3;
+*      account->incoming_server_address  = strdup("pop3.gmail.com");
+*      account->incoming_server_port_number               = 995;
+*      account->incoming_server_secure_connection           = 1;
+*      account->retrieval_mode         = EMAIL_IMAP4_RETRIEVAL_MODE_ALL;
+*      account->incoming_server_user_name              = strdup("tom");
+*      account->password               = strdup("password");
+*      account->outgoing_server_type    = EMAIL_SERVER_TYPE_SMTP;
+*      account->outgoing_server_address    = strdup("smtp.gmail.com");
+*      account->outgoing_server_port_number       = 587;
+*      account->outgoing_server_secure_connection       = 0x02;
+*      account->outgoing_server_need_authentication           = 1;
+*      account->outgoing_server_user_name           = strdup("tom@gmail.com");
+*      account->sending_password       = strdup("password");
+*      account->pop_before_smtp        = 0;
+*      account->incoming_server_requires_apop                   = 0;
+*      account->flag1                  = 2;
+*      account->flag2                  = 1;
+*      account->is_preset_account         = 1;
+*      account->logo_icon_path         = strdup("Logo Icon Path");
+*      account->options.priority = 3;
+*      account->options.keep_local_copy = 0;
+*      account->options.req_delivery_receipt = 0;
+*      account->options.req_read_receipt = 0;
+*      account->options.download_limit = 0;
+*      account->options.block_address = 0;
+*      account->options.block_subject = 0;
+*      account->options.display_name_from = strdup("Display name from");
+*      account->options.reply_with_body = 0;
+*      account->options.forward_with_files = 0;
+*      account->options.add_myname_card = 0;
+*      account->options.add_signature = 0;
+*      account->options.signature= strdup("Signature");
+*      account->check_interval = 0;
+*      // Add account
+*      if(EMAIL_ERROR_NONE != email_add_account(account))
+*              //failure
+*      //else
+*      {
+*              //success
+*              if(account_id)
+*                      *account_id = account->account_id;
+*      }
+*      if(EMAIL_ERROR_NONE != email_validate_account(account_id,&account_handle))
+*              //failure
+*      else
+*            //success
+*      if(EMAIL_ERROR_NONE != email_delete_account(account_id))
+*              //failure
+*      else
+*              //success
+*      new_account = malloc(sizeof(email_account_t));
+*      memset(new_account, 0x00, sizeof(email_account_t));
+*      new_account->flag1                   = 1;
+*      new_account->account_name            = strdup("samsung001");
+*      new_account->display_name            = strdup("Tom001");
+*      new_account->options.keep_local_copy = 1;
+*      new_account->check_interval          = 55;
+*      // Update account
+*      if(EMAIL_ERROR_NONE != email_update_account(acount_id,new_account))
+*              //failure
+*      else
+*              //success
+*      // Get account
+*      if(EMAIL_ERROR_NONE != email_get_account(account_id,GET_FULL_DATA,&account))
+*              //failure
+*      else
+*              //success
+*      // Get list of accounts
+*      if(EMAIL_ERROR_NONE != email_get_account_list(&account_list,&count))
+*              //failure
+*      else
+*              //success
+*      // free account
+*      email_free_account(&account, 1);
+*      }
+ *
+ * @endcode
+ * @}
+ */
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/**
+
+ * @fn email_add_account(email_account_t* account)
+ * @brief      Create a new email account.This function is invoked when user wants to add new email account
+ *
+ * @param[in] account  Specifies the structure pointer of account.
+ * @exception  none
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see         email_account_t
+ * @remarks N/A
+ */
+EXPORT_API int email_add_account(email_account_t* account);
+
+/**
+
+ * @fn email_delete_account(int account_id)
+ * @brief       Delete a email account.This function is invoked when user wants to delete an existing email account
+ *
+ * @param[in] account_id       Specifies the account ID.
+ * @exception  EMAIL_ERROR_INVALID_PARAM               -Invalid argument
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see
+ * @remarks N/A
+ */
+EXPORT_API int email_delete_account(int account_id);
+
+/**
+
+ * @fn email_update_account(int account_id, email_account_t* new_account)
+ * @brief      Change the information of a email account.This function is getting invoked when user wants to change some information of existing email account.
+ *
+ * @param[in] account_id       Specifies the orignal account ID.
+ * @param[in] new_account      Specifies the information of new account.
+ * @param[in] with_validation  If this is 1, email-service will validate the account before updating. If this is 0, email-service will update the account without validation.
+ * @exception EMAIL_ERROR_INVALID_PARAM        -Invalid argument
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see email_account_t
+ * @remarks N/A
+ */
+EXPORT_API int email_update_account(int account_id, email_account_t* new_account);
+
+/**
+
+ * @fn email_update_account_with_validation(int account_id, email_account_t* new_account)
+ * @brief      Change the information of a email account.This function is getting invoked when user wants to change some information of existing email account.
+ *
+ * @param[in] account_id       Specifies the orignal account ID.
+ * @param[in] new_account      Specifies the information of new account.
+ * @param[in] with_validation  If this is 1, email-service will validate the account before updating. If this is 0, email-service will update the account without validation.
+ * @exception EMAIL_ERROR_INVALID_PARAM        -Invalid argument
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see email_account_t
+ * @remarks N/A
+ */
+EXPORT_API int email_update_account_with_validation(int account_id, email_account_t* new_account);
+
+/**
+
+ * @fn  email_get_account(int account_id, int pulloption, email_account_t** account)
+ * @brief      Get an email account by ID. This function is getting invoked when user wants to get the account informantion based on account id and option (GET_FULL_DATA/WITHOUT_OPTION/ONLY_OPTION).<br>
+ *                     Memory for account information will be allocated to 3rd param(account). The allocated memory should be freed by email_free_account().
+ *
+ * @param[in] account_id       Specifies the account ID.This function is invoked when user
+ * @param[in] pulloption       Option to specify to get full details or partial, see definition of EMAIL_ACC_GET_OPT_XXX
+ * @param[out] account         The returned account is saved here.
+ * @exception EMAIL_ERROR_INVALID_PARAM        -Invalid argument
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see email_account_t
+ * @remarks N/A
+ */
+
+EXPORT_API int email_get_account(int account_id, int pulloption, email_account_t** account);
+
+/**
+
+ * @fn email_get_account_list(email_account_t** account_list, int* count);
+ * @brief      Get Account List.This function is getting invoked when user wants to get all account information based on the count of accounts provided by user.<br>
+ *                     Memory for account information will be allocated to 3rd param(account). The allocated memory should be freed by email_free_account().
+ *
+ * @param[in] account_list     Specifies the structure pointer of account.
+ * @param[out] count                   Specifies the count of accounts.
+ * @exception EMAIL_ERROR_INVALID_PARAM        -Invalid argument
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see email_account_t
+ * @remarks N/A
+ */
+EXPORT_API int email_get_account_list(email_account_t** account_list, int* count);
+
+ /**
+
+ * @fn   email_free_account(email_account_t** account_list, int count);
+ * @brief      Free allocated memory.This function is getting invoked when user wants to delete all account information.
+ *
+ * @param[in] account_list     Specifies the structure pointer of account.
+ * @param[out] count                   Specifies the count of accounts.
+ * @exception EMAIL_ERROR_INVALID_PARAM        -Invalid argument
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see email_account_t
+ * @remarks N/A
+ */
+EXPORT_API int email_free_account(email_account_t** account_list, int count);
+
+
+/**
+
+ * @fn email_validate_account(int account_id, int *handle)
+ * @brief      Validate account.This function is getting invoked  after adding one account to validate it.If account is not validated then user should retry once again to add the account .
+ *
+ * @param[in] account_id              Specifies the account Id to validate.
+ * @param[out] handle          Specifies the sending handle.
+ * @remarks N/A
+ * @exception EMAIL_ERROR_INVALID_PARAM        -Invalid argument
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @see                none
+ * @remarks N/A
+ */
+EXPORT_API int email_validate_account(int account_id, int *handle);
+
+/**
+
+ * @fn email_add_account_with_validation(email_account_t* account, int *handle)
+ * @brief      Add an account when the account is validated. This function is getting invoked when user want to validate an account. If account is not validated then user should retry once again to add the account.<br>
+ *              Validation is executed without saving an account to DB
+ *
+ * @param[in] account      Specifies the structure pointer of account.
+ * @param[out] handle          Specifies the sending handle.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_add_account_with_validation(email_account_t* account, int *handle);
+
+
+/**
+
+ * @fn email_backup_accounts_into_secure_storage(const char *file_name)
+ * @brief      Back up information of all accounts into secure storage.
+ *          This function is getting invoked when user want to backup account information safely.
+ *
+ * @param[in] file_name            Specifies the file name in secure storage
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_backup_accounts_into_secure_storage(const char *file_name);
+
+/**
+
+ * @fn email_restore_accounts_from_secure_storage(const char *file_name)
+ * @brief      Restore accounts from stored file in secure storage.
+ *          This function is getting invoked when user want to restore accounts.
+ *
+ * @param[in] file_name            Specifies the file name in secure storage
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_restore_accounts_from_secure_storage(const char * file_name);
+
+/**
+
+ * @fn email_get_password_length_of_account(const int account_id, int *password_length)
+ * @brief      Get password length of an account.
+ *          This function is getting invoked when user want to know the length of an account.
+ *
+ * @param[in] account_id    Specifies the account id
+ * @param[out] handle          Specifies the password length.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_get_password_length_of_account(const int account_id, int *password_length);
+
+
+/**
+
+ * @fn email_query_server_info(const char* domain_name, email_server_info_t **result_server_info)
+ * @brief      Query email server information.
+ *          This function is getting invoked when user want to get email server information.
+ *
+ * @param[in] domain_name              Specifies the domain name of server
+ * @param[out] result_server_info      Specifies the information of email server.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_query_server_info(const char* domain_name, email_server_info_t **result_server_info);
+
+/**
+
+ * @fn email_free_server_info(email_server_info_t **result_server_info)
+ * @brief      Free email_server_info_t.
+ *          This function is getting invoked when user want to free email_server_info_t.
+ *
+ * @param[in] result_server_info       Specifies the pointer of  in secure storage
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_free_server_info(email_server_info_t **result_server_info);
+
+/**
+
+ * @fn email_update_notification_bar(int account_id)
+ * @brief      Update notifications on notification bar.
+ *          This function is getting invoked when user want to update notification bar.
+ *
+ * @param[in] account_id               Specifies the id of account.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_update_notification_bar(int account_id);
+
+/**
+
+ * @fn email_clear_all_notification_bar()
+ * @brief      Clear all notification on notification bar.
+ *          This function is getting invoked when user want to clear notification bar.
+ *
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_clear_all_notification_bar();
+
+
+/**
+
+ * @fn email_save_default_account_id()
+ * @brief      Save default account id to vconf storage.
+ *          This function is getting invoked when user want to save default account id.
+ *
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_save_default_account_id(int input_account_id);
+
+/**
+
+ * @fn email_load_default_account_id()
+ * @brief      Load default account id to vconf storage.
+ *          This function is getting invoked when user want to load default account id.
+ *
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+EXPORT_API int email_load_default_account_id(int *output_account_id);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/**
+* @} @}
+*/
+
+#endif /* __EMAIL_API_ACCOUNT_H__ */
+
+
diff --git a/email-api/include/email-api-etc.h b/email-api/include/email-api-etc.h
new file mode 100755 (executable)
index 0000000..f397fd9
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_API_ETC Email API
+* @{
+*/
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file       email-api-etc.h
+ * @author     Kyuho Jo <kyuho.jo@samsung.com>
+ * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
+ * @version    0.1
+ * @brief      This file contains the data structures and interfaces of Accounts provided by
+ *                     email-service .
+ */
+
+#ifndef __EMAIL_API_ETC_H__
+#define __EMAIL_API_ETC_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include "email-types.h"
+
+/**
+
+
+ * @fn email_show_user_message(void)
+ * @brief      This function show user message.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception  none
+ * @see        email_action_t
+ * @remarks N/A
+ */
+EXPORT_API int email_show_user_message(int id, email_action_t action, int error_code);
+
+EXPORT_API int email_parse_mime_file(char *eml_file_path, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
+
+EXPORT_API int email_write_mime_file(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data, int input_attachment_count, char **output_file_path);
+
+EXPORT_API int email_delete_parsed_data(email_mail_data_t *input_mail_data);
+
+EXPORT_API int email_get_mime_entity(char *mime_path, char **mime_entity);
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* __EMAIL_API_ETC_H__ */
+
+/**
+* @} @}
+*/
diff --git a/email-api/include/email-api-init.h b/email-api/include/email-api-init.h
new file mode 100755 (executable)
index 0000000..96ee737
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_API_INTI_H__
+#define __EMAIL_API_INTI_H__
+
+#include "email-types.h"
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_API_INIT Email Initialization API
+* @{
+*/
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-init.h
+ * @author     Kyuho Jo <kyuho.jo@samsung.com>
+ * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
+ * @version    0.1
+ * @brief              This file contains the data structures and interfaces of Email FW Initialization provided by
+ *                     email-service .
+ *@{
+ *@code
+ *
+ *     #include "email-api-init.h"
+ *
+ *     bool
+ *     other_app_invoke_uniform_api_sample(int* error_code)
+ *     {
+ *              int err = EMAIL_ERROR_NONE;
+ *
+ *             // Open connections to email-service and DB
+ *             // The connections will be maintain throughout application's execution
+ *             if(EMAIL_ERROR_NONE == email_service_begin())
+ *             {
+ *                     If(EMAIL_ERROR_NONE != email_open_db())
+ *                     {
+ *                             return false;
+ *                     }
+ *
+ *                     // Execute email_init_storage() if and only if there is no db file.
+ *                     // This fuction will create db file and tables for email service
+ *                     If(EMAIL_ERROR_NONE !=email_init_storage())
+ *                     {
+ *                             return false;
+ *                     }
+ *             }
+ *
+ *             ......
+ *
+ *             // Work with calling MAPI functions
+ *
+ *             ......
+ *
+ *             // Close the connections to email-service and DB after all email job is finished. (ex. close an email application)
+ *             // DO NOT have to call these funtions until the connections is not needed any more.
+ *             err =email_close_db();
+ *             err =email_service_end();
+ *      }
+ *
+ * @endcode
+ * @}
+ */
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/**
+
+
+ * @fn email_init_storage(void)
+ * @brief      Create all tables for email.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure
+ * @exception none
+ * @see none
+ * @remarks N/A
+ */
+EXPORT_API int email_init_storage(void);
+
+/**
+
+
+ * @fn email_open_db(void)
+ * @brief This function Open the email DB and register busy handler
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception none
+ * @see        none
+ * @remarks N/A
+ */
+EXPORT_API int email_open_db(void);
+
+
+/**
+
+
+ * @fn email_close_db(void)
+ * @brief      This function closes the connection of  the email DB
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception none
+ * @see none
+ * @remarks N/A
+ */
+EXPORT_API int email_close_db(void);
+
+/**
+
+
+ * @fn email_service_begin(void)
+ * @brief      Does the IPC Proxy Initialization by the Application which used the Email FW API's
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception none
+ * @see        none
+ * @remarks N/A
+ */
+EXPORT_API int email_service_begin(void);
+
+/**
+
+
+ * @fn email_service_end(void)
+ * @brief      This function does the IPC Proxy Finaization by the Application which used the Email FW API's
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception  none
+ * @see        none
+ * @remarks N/A
+ */
+EXPORT_API int email_service_end(void);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/**
+* @} @}
+*/
+
+
+#endif  /* __EMAIL_API_INTI_H__ */
diff --git a/email-api/include/email-api-mail.h b/email-api/include/email-api-mail.h
new file mode 100755 (executable)
index 0000000..12b1233
--- /dev/null
@@ -0,0 +1,1436 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_API_MAIL_H__
+#define __EMAIL_API_MAIL_H__
+
+#include "email-types.h"
+
+#include <time.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_API_MAIL Email Mail API
+* @{
+*/
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-mail.h
+ * @author     Kyuho Jo <kyuho.jo@samsung.com>
+ * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
+ * @version    0.1
+ * @brief              This file contains the data structures and interfaces of Messages provided by
+ *                     email-service .
+ */
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/**
+ * @fn email_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas)
+ * @brief      Save a mail. This function is invoked when user wants to add a mail.
+ *             If the option from_eas is 1 then this will save the message on server as well as on locally.
+ *             If the incoming_server_type is EMAIL_SERVER_TYPE_POP3 then from_eas value will be 0
+ *             If the incoming_server_type is EMAIL_SERVER_TYPE_IMAP4 then from_eas value will be 1/0
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mail_data  Specifies the saving mail.
+ * @param[in] input_attachment_data_list       Specifies the mailbox structure for saving email.
+ * @param[in] input_attachment_count   Specifies if the mail comes from composer.
+ * @param[in] input_meeting_request    Specifies if the mail comes from composer.
+ * @param[in] input_from_eas   Specifies if the mail will be saved on server.
+
+ * @exception  none
+ * @see email_mail_data_t and email_mailbox_t
+ * @remarks N/A
+ * @code
+ * #include "email-api-mail.h"
+ * int _test_add_mail ()
+ * {
+ *     int                    i = 0;
+ *     int                    account_id = 0;
+ *     int                    from_eas = 0;
+ *     int                    attachment_count = 0;
+ *     int                    err = EMAIL_ERROR_NONE;
+ *     char                   arg[50] = { 0 , };
+ *     char                  *body_file_path = MAILHOME"/tmp/mail.txt";
+ *     email_mailbox_t         *mailbox_data = NULL;
+ *     email_mail_data_t       *test_mail_data = NULL;
+ *     email_attachment_data_t *attachment_data = NULL;
+ *     email_meeting_request_t *meeting_req = NULL;
+ *     FILE                  *body_file;
+ *
+ *     printf("\n > Enter account id : ");
+ *     scanf("%d", &account_id);
+ *
+ *
+ *     memset(arg, 0x00, 50);
+ *     printf("\n > Enter mailbox name : ");
+ *     scanf("%s", arg);
+ *
+ *     email_get_mailbox_by_name(account_id, arg, &mailbox_data);
+ *
+ *     test_mail_data = malloc(sizeof(email_mail_data_t));
+ *     memset(test_mail_data, 0x00, sizeof(email_mail_data_t));
+ *
+ *     printf("\n From EAS? [0/1]> ");
+ *     scanf("%d", &from_eas);
+ *
+ *     test_mail_data->account_id        = account_id;
+ *     test_mail_data->save_status       = 1;
+ *     test_mail_data->flags_seen_field  = 1;
+ *     test_mail_data->file_path_plain   = strdup(body_file_path);
+ *     test_mail_data->mailbox_id        = mailbox_data->mailbox_id;
+ *     test_mail_data->mailbox_type      = mailbox_data->mailbox_type;
+ *     test_mail_data->full_address_from = strdup("<test1@test.com>");
+ *     test_mail_data->full_address_to   = strdup("<test2@test.com>");
+ *     test_mail_data->full_address_cc   = strdup("<test3@test.com>");
+ *     test_mail_data->full_address_bcc  = strdup("<test4@test.com>");
+ *     test_mail_data->subject           = strdup("Meeting request mail");
+ *
+ *     body_file = fopen(body_file_path, "w");
+ *
+ *     for(i = 0; i < 500; i++)
+ *             fprintf(body_file, "X2 X2 X2 X2 X2 X2 X2");
+ *     fflush(body_file);
+ *   fclose(body_file);
+ *
+ *     printf(" > Attach file? [0/1] : ");
+ *     scanf("%d",&attachment_count);
+ *
+ *     if ( attachment_count )  {
+ *             memset(arg, 0x00, 50);
+ *             printf("\n > Enter attachment name : ");
+ *             scanf("%s", arg);
+ *
+ *             attachment_data = malloc(sizeof(email_attachment_data_t));
+ *
+ *             attachment_data->attachment_name  = strdup(arg);
+ *
+ *             memset(arg, 0x00, 50);
+ *             printf("\n > Enter attachment absolute path : ");
+ *             scanf("%s",arg);
+ *
+ *             attachment_data->attachment_path  = strdup(arg);
+ *             attachment_data->save_status      = 1;
+ *             test_mail_data->attachment_count  = attachment_count;
+ *     }
+ *
+ *     printf("\n > Meeting Request? [0: no, 1: yes (request from server), 2: yes (response from local)]");
+ *     scanf("%d", &(test_mail_data->meeting_request_status));
+ *
+ *     if ( test_mail_data->meeting_request_status == 1
+ *             || test_mail_data->meeting_request_status == 2 ) {
+ *             time_t current_time;
+ *             meeting_req = malloc(sizeof(email_meeting_request_t));
+ *             memset(meeting_req, 0x00, sizeof(email_meeting_request_t));
+ *
+ *             meeting_req->meeting_response     = 1;
+ *             current_time = time(NULL);
+ *             gmtime_r(&current_time, &(meeting_req->start_time));
+ *             gmtime_r(&current_time, &(meeting_req->end_time));
+ *             meeting_req->location = malloc(strlen("Seoul") + 1);
+ *             memset(meeting_req->location, 0x00, strlen("Seoul") + 1);
+ *             strcpy(meeting_req->location, "Seoul");
+ *             strcpy(meeting_req->global_object_id, "abcdef12345");
+ *
+ *             meeting_req->time_zone.offset_from_GMT = 9;
+ *             strcpy(meeting_req->time_zone.standard_name, "STANDARD_NAME");
+ *             gmtime_r(&current_time, &(meeting_req->time_zone.standard_time_start_date));
+ *             meeting_req->time_zone.standard_bias = 3;
+ *
+ *             strcpy(meeting_req->time_zone.daylight_name, "DAYLIGHT_NAME");
+ *             gmtime_r(&current_time, &(meeting_req->time_zone.daylight_time_start_date));
+ *             meeting_req->time_zone.daylight_bias = 7;
+ *
+ *     }
+ *
+ *     if((err = email_add_mail(test_mail_data, attachment_data, attachment_count, meeting_req, from_eas)) != EMAIL_ERROR_NONE)
+ *             printf("email_add_mail failed. [%d]\n", err);
+ *     else
+ *             printf("email_add_mail success.\n");
+ *
+ *     if(attachment_data)
+ *             email_free_attachment_data(&attachment_data, attachment_count);
+ *
+ *     if(meeting_req)
+ *             email_free_meeting_request(&meeting_req, 1);
+ *
+ *     email_free_mail_data(&test_mail_data, 1);
+ *     email_free_mailbox(&mailbox_data, 1);
+ *
+ *     printf("saved mail id = [%d]\n", test_mail_data->mail_id);
+ *
+ *     return 0;
+ * }
+ * @endcode
+ */
+EXPORT_API int email_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas);
+
+ /**
+
+  * @fn email_add_read_receipt(int input_read_mail_id,  int *output_handle)
+  * @brief     Add a read receipt mail. This function is invoked when user receives a mail with read report enable and wants to send a read report for the same.
+  *
+  * @return    This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+  * @param[in]  input_read_mail_id     Specifies the id of mail which has been read.
+  * @param[out] output_receipt_mail_id Specifies the receipt mail id .
+  * @exception none
+  * @see
+  * @remarks N/A
+  */
+EXPORT_API int email_add_read_receipt(int input_read_mail_id, int *output_receipt_mail_id);
+
+/**
+ * @fn email_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_composer)
+ * @brief      Update a existing email information. This function is invoked when user wants to change some existing email information with new email information.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mail_data          Specifies the mail ID.
+ * @param[in] input_attachment_data_list       Specifies the pointer of attachment data.
+ * @param[in] input_attachment_count   Specifies the number of attachment data.
+ * @param[in] input_meeting_request    Specifies the meeting request data.
+ * @param[in] input_from_eas Specifies whether sync server.
+
+ * @exception  none
+ * @see        email_mail_data_t
+ * @code
+ * #include "email-api-account.h"
+ * int email_test_update_mail()
+ * {
+ *     int                    mail_id = 0;
+ *     int                    err = EMAIL_ERROR_NONE;
+ *     int                    test_attachment_data_count = 0;
+ *     char                   arg[50];
+ *     email_mail_data_t       *test_mail_data = NULL;
+ *     email_attachment_data_t *test_attachment_data_list = NULL;
+ *     email_meeting_request_t *meeting_req = NULL;
+ *
+ *     printf("\n > Enter mail id : ");
+ *     scanf("%d", &mail_id);
+ *
+ *     email_get_mail_data(mail_id, &test_mail_data);
+ *
+ *     printf("\n > Enter Subject: ");
+ *     scanf("%s", arg);
+ *
+ *     test_mail_data->subject= strdup(arg);
+ *
+ *
+ *
+ *     if (test_mail_data->attachment_count > 0) {
+ *             if ( (err = email_get_attachment_data_list(mail_id, &test_attachment_data_list, &test_attachment_data_count)) != EMAIL_ERROR_NONE ) {
+ *                     printf("email_get_meeting_request() failed [%d]\n", err);
+ *                     return -1;
+ *             }
+ *     }
+ *
+ *     if ( test_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_REQUEST
+ *             || test_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_RESPONSE
+ *             || test_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST) {
+ *
+ *             if ( (err = email_get_meeting_request(mail_id, &meeting_req)) != EMAIL_ERROR_NONE ) {
+ *                     printf("email_get_meeting_request() failed [%d]\n", err);
+ *                     return -1;
+ *             }
+ *
+ *             printf("\n > Enter meeting response: ");
+ *             scanf("%d", (int*)&(meeting_req->meeting_response));
+ *     }
+ *
+ *     if ( (err = email_update_mail(test_mail_data, test_attachment_data_list, test_attachment_data_count, meeting_req, 0)) != EMAIL_ERROR_NONE)
+ *                     printf("email_update_mail failed.[%d]\n", err);
+ *             else
+ *                     printf("email_update_mail success\n");
+ *
+ *     if(test_mail_data)
+ *             email_free_mail_data(&test_mail_data, 1);
+ *
+ *     if(test_attachment_data_list)
+ *             email_free_attachment_data(&test_attachment_data_list, test_attachment_data_count);
+ *
+ *     if(meeting_req)
+ *             email_free_meeting_request(&meeting_req, 1);
+ *
+ *     return 0;
+ * }
+
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas);
+
+EXPORT_API int email_update_mail_attribute(int *input_mail_id_array, int input_mail_id_count, email_mail_attribute_type input_attribute, email_mail_attribute_value_t input_value);
+
+/**
+ * @fn email_count_mail(email_mailbox_t* mailbox, int* total, int* unseen)
+ * @brief      Get mail count from mailbox.This function is invoked when user wants to know how many toatl mails and out of that
+ *             how many unseen mails are there in a given mailbox.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mailbox  Specifies the pointer of mailbox structure.
+ * @param[out] total   Total email count is saved here.
+ * @param[out] unseen  Unread email count is saved here.
+ * @exception  none
+ * @see        email_mailbox_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_count_mail()
+ *     {
+ *             int total = 0;
+ *             int unseen = 0;
+ *             email_list_filter_t *filter_list = NULL;
+ *             int err = EMAIL_ERROR_NONE;
+ *             int i = 0;
+ *             filter_list = malloc(sizeof(email_list_filter_t) * 3);
+ *             memset(filter_list, 0 , sizeof(email_list_filter_t) * 3);
+ *
+ *             filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+ *             filter_list[0].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SUBJECT;
+ *             filter_list[0].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+ *             filter_list[0].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+ *             filter_list[0].list_filter_item.rule.case_sensitivity              = false;
+ *
+ *             filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+ *             filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+ *
+ *             filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+ *             filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_TO;
+ *             filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+ *             filter_list[2].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+ *             filter_list[2].list_filter_item.rule.case_sensitivity              = false;
+ *
+ *             if(EMAIL_ERROR_NONE == email_count_mail(filter_list, 3, &total, &unseen))
+ *                     printf("\n Total: %d, Unseen: %d \n", total, unseen);
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_count_mail(email_list_filter_t *input_filter_list, int input_filter_count, int *output_total_mail_count, int *output_unseen_mail_count);
+
+/**
+ * @fn email_get_max_mail_count(int *Count)
+ * @brief      Gets the max count of mails which can be supported by email-service
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[out] Count   max count of mails which can be supported by email-service
+ * @exception          none
+ * @code
+ *     #include "email-api-account.h"
+ *             bool
+ *             _api_sample_get_max_mail_count()
+ *             {
+ *                     int max_count = -1;
+ *
+ *                     if(EMAIL_ERROR_NONE == email_get_max_mail_count(&max_count))
+ *                             printf("\n\t>>>>> email_get_max_mail_count() return [%d]\n\n", max_count);
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_max_mail_count(int *count);
+
+/**
+ * @fn         email_delete_mail(email_mailbox_t* mailbox, int *mail_ids, int num, int from_server)
+ * @brief      Delete a mail or multiple mails.Based on from_server value this function will delte a mail or multiple mails from server or loaclly.
+ * @param[in] mailbox                  Reserved.
+ *             If the incoming_server_type is EMAIL_SERVER_TYPE_POP3 then from_server value will be 0
+ *             If the incoming_server_type is EMAIL_SERVER_TYPE_IMAP4 then from_server value will be 1/0
+ *
+ * @param[in] mail_ids[]       Specifies the array of mail id.
+ * @param[in] num                      Specifies the number of mail id.
+ * @param[in] from_server      Specifies whether mails are deleted from server.
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception none
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_delete_mail()
+ *     {
+ *             int count, i, mail_id=0, mailbox_id =0;
+ *
+ *             printf("\n > Enter Mail_id: ");
+ *             scanf("%d",&mail_id);
+ *             printf("\n > Enter Mailbox ID: ");
+ *             scanf("%d",&mailbox_id);
+ *             if(EMAIL_ERROR_NONE == email_delete_mail(mailbox_id, &mail_id, 1, 1))
+ *                     printf("\n email_delete_mail success");
+ *             else
+ *                     printf("\n email_delete_mail failed");
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_delete_mail(int input_mailbox_id, int *input_mail_ids, int input_num, int input_from_server);
+
+
+/**
+ * @fn email_delete_all_mails_in_mailbox(int input_mailbox_id, int input_from_server)
+ * @brief      Delete all mail from a mailbox.
+ *             If the incoming_server_type is EMAIL_SERVER_TYPE_POP3 then from_server value will be 0
+ *             If the incoming_server_type is EMAIL_SERVER_TYPE_IMAP4 then from_server value will be 1/0
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mailbox                  Specifies the structure of mailbox.
+ * @param[in] from_server              Specifies whether mails are also deleted from server.
+ * @exception          none
+ * @see                email_mailbox_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_delete_all_mails_in_mailbox()
+ *     {
+ *             int count, mailbox_id =0;
+ *
+ *             printf("\n > Enter mailbox_id: ");
+ *             scanf("%d",&mailbox_id);
+ *
+ *             if (EMAIL_ERROR_NONE != email_delete_all_mails_in_mailbox(mailbox_id, 0))
+ *                     printf("email_delete_all_mails_in_mailbox failed");
+ *             else
+ *                     printf("email_delete_all_mails_in_mailbox Success");
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_delete_all_mails_in_mailbox(int input_mailbox_id, int input_from_server);
+
+/**
+
+ *  @fn email_clear_mail_data()
+ * @brief      delete email data from storage. This API will be used by the Settings Application
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @exception          none
+ * @see                none
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_clear_mail_data()
+ *     {
+ *             if(EMAIL_ERROR_NONE == email_clear_mail_data())
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int  email_clear_mail_data();
+
+
+/**
+
+ * @fn email_add_attachment(int mail_id, email_attachment_data_t* attachment)
+ * @brief      Append a attachment to email.This function is invoked when user wants to add attachment to existing mail.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id          Specifies the mail ID.
+ * @param[in] attachment       Specifies the structure of attachment.
+ * @exception          none
+ * @see email_attachment_data_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_mail_add_attachment()
+ *     {
+ *             int mail_id = 0;
+ *             email_attachment_data_t attachment;
+ *
+ *             printf("\n > Enter Mail Id: ");
+ *             scanf("%d", &mail_id);
+ *             memset(&attachment, 0x00, sizeof(email_attachment_data_t));
+ *             printf("\n > Enter attachment name: ");
+ *             attachment.name = strdup("Test");
+ *             printf("\n > Enter attachment absolute path: ");
+ *             attachment.savename = strdup("/tmp/test.txt");
+ *             attachment.next = NULL;
+ *             if(EMAIL_ERROR_NONE != email_add_attachment(mail_id, &attachment))
+ *                     printf("email_add_attachment failed\n");
+ *             else
+ *                     printf(email_add_attachment success\n");
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_add_attachment(int mail_id, email_attachment_data_t* attachment);
+
+
+/**
+
+ * @fn email_delete_attachment(int mail_id, const char * attachment_id)
+ * @brief      delete a attachment from email.This function is invoked when user wants to delete a attachment from existing mailbased on mail Id and attachment Id
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id                  Specifies the mail ID.
+ * @param[in] attachment_id            Specifies the attachment id.
+ * @exception          none
+ * @see                email_mailbox_t
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_mail_delete_attachment()
+ *     {
+ *
+ *             if(EMAIL_ERROR_NONE != email_delete_attachment(1))
+ *                     //failure
+ *             else
+ *                     //success
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_delete_attachment(int attachment_id);
+
+/**
+
+ * @fn email_get_attachment_data(int mail_id, const char* attachment_id, email_attachment_data_t** attachment)
+ * @brief      Get a mail attachment.This function is invoked when user wants to get the attachment information based on attachment id for the specified mail Id.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id          Specifies the mail ID.
+ * @param[in] attachment_id    Specifies the buffer that a attachment ID been saved.
+ * @param[out] attachment      The returned attachment is save here.
+ * @exception          none
+ * @see                email_mailbox_t and email_mail_attachment_info_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_mail_get_attachment_info()
+ *     {
+ *             email_mail_attachment_info_t *mail_attach_info = NULL;
+ *             int mail_id = 0;
+ *             char arg[10];
+ *             int err = EMAIL_ERROR_NONE;
+ *
+ *
+ *             printf("\n > Enter Mail Id: ");
+ *             scanf("%d", &mail_id);
+ *             printf("> attachment Id\n");
+ *             scanf("%s",arg);
+ *             if (EMAIL_ERROR_NONE != email_get_attachment_data(mail_id, &mail_attach_info))
+ *                     printf("email_get_attachment_data failed\n");
+ *             else
+ *             {
+ *                     printf("email_get_attachment_data SUCCESS\n");
+ *                     //do something
+ *                     email_free_attachment_data(&mail_attach_info,1);
+ *             }
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_attachment_data(int attachment_id, email_attachment_data_t** attachment);
+
+EXPORT_API int email_get_attachment_data_list(int input_mail_id, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
+
+/**
+
+ * @fn email_free_attachment_data(email_attachment_data_t **attachment_data_list, int attachment_data_count)
+ * @brief      Free allocated memroy for email attachment.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] atch_info        Specifies the pointer of mail attachment structure pointer.
+ * @exception          none
+ * @see                email_mail_attachment_info_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_mail_free_attachment_info()
+ *     {
+ *             email_mailbox_t mailbox;
+ *             email_mail_attachment_info_t *mail_attach_info = NULL;
+ *             int mail_id = 0,account_id = 0;
+ *             char arg[10];
+ *             int err = EMAIL_ERROR_NONE;
+ *
+ *             memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+ *
+ *             printf("\n > Enter Mail Id: ");
+ *             scanf("%d", &mail_id);
+ *             printf("\n > Enter account Id: ");
+ *             scanf("%d", &account_id);
+ *             printf("> attachment Id\n");
+ *             scanf("%s",arg);
+ *             mailbox.account_id = account_id;
+ *             if (EMAIL_ERROR_NONE != email_get_attachment_data(&mailbox, mail_id, &mail_attach_info))
+ *                     printf("email_get_attachment_data failed\n");
+ *             else
+ *             {
+ *                     printf("email_get_attachment_data SUCCESS\n");
+ *                     //do something
+ *                     email_free_attachment_info(&mail_attach_info,1);
+ *             }
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_free_attachment_data(email_attachment_data_t **attachment_data_list, int attachment_data_count);
+
+/* -----------------------------------------------------------
+                                             Mail Information API
+    -----------------------------------------------------------*/
+
+
+/**
+
+ * @fn email_query_mails(char *conditional_clause_string, email_mail_data_t** mail_list,  int *result_count)
+ * @brief                          Query the mail list information from DB based on the mailbox name.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] conditional_clause_string  Specifies the where clause string.
+ * @param[in/out] mail_list        Specifies the pointer to the structure email_mail_data_t.
+ * @param[in/out] result_count     Specifies the number of mails returned.
+ * @exception                      None
+ * @see                            email_mail_list_item_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_query_mail()
+ *     {
+ *             email_mail_data_t *mail_list = NULL;
+ *             char conditional_clause_string[500];
+ *             int result_count = 0;
+ *
+ *             memset(conditional_clause_string, 0x00, 10);
+ *             printf("\n > Enter where clause: ");
+ *             scanf("%s", conditional_clause_string);
+ *
+ *
+ *             if (EMAIL_ERROR_NONE != email_query_mails(conditional_clause_string, &mail_list, &result_count))
+ *                     printf("email_query_mails failed \n");
+ *             else {
+ *                     printf("Success\n");
+ *                     //do something
+ *                     free(mail_list);
+ *             }
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_query_mails(char *conditional_clause_string, email_mail_data_t** mail_list,  int *result_count);
+
+/**
+
+ * @fn email_query_mail_list(char *input_conditional_clause_string, email_mail_list_item_t** output_mail_list,  int *output_result_count)
+ * @brief Query the mail list information from DB.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_conditional_clause_string  Specifies the where clause string.
+ * @param[in/out] output_mail_list                             Specifies the pointer to the structure email_mail_list_item_t.
+ * @param[in/out] output_result_count                  Specifies the number of mails returned.
+ * @exception  None
+ * @see                        email_mail_list_item_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_query_mail_list()
+ *     {
+ *             email_mail_list_item_t *mail_list = NULL;
+ *             char conditional_clause_string[500];
+ *             int result_count = 0;
+ *
+ *             memset(conditional_clause_string, 0x00, 10);
+ *             printf("\n > Enter where clause: ");
+ *             scanf("%s", conditional_clause_string);
+ *
+ *
+ *             if (EMAIL_ERROR_NONE != email_query_mail_list(conditional_clause_string, &mail_list, &result_count))
+ *                     printf("email_query_mail_list failed \n");
+ *             else {
+ *                     printf("Success\n");
+ *                     //do something
+ *                     free(mail_list);
+ *             }
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_query_mail_list(char *input_conditional_clause_string, email_mail_list_item_t** output_mail_list,  int *output_result_count);
+
+/**
+
+ * @fn email_get_mail_data(int input_mail_id, email_mail_data_t **output_mail_data)
+ * @brief      Get a mail by its mail id. This function is invoked when user wants to get a mail based on mail id existing in DB.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mail_id    specifies the mail id.
+ * @param[out] output_mail_data                The returned mail is save here.
+ * @exception          none
+ * @see        email_mail_data_t
+
+ * @code
+ *    #include "email-api-account.h"
+ *     bool
+ *     _api_sample_get_mail_data()
+ *     {
+ *             email_mail_data_t *mail = NULL;
+ *             int mail_id = 0 ;
+ *             int err = EMAIL_ERROR_NONE;
+ *
+ *             printf("\n > Enter mail id: ");
+ *             scanf("%d", &mail_id);
+ *
+ *             if (EMAIL_ERROR_NONE != email_get_mail_data(mail_id, &mail))
+ *                     printf("email_get_mail_data failed\n");
+ *             else
+ *             {
+ *                     printf("email_get_mail_data SUCCESS\n");
+ *                     //do something
+ *                     email_free_mail_data(&mail,1);
+ *             }
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+
+EXPORT_API int email_get_mail_data(int input_mail_id, email_mail_data_t **output_mail_data);
+
+
+/**
+
+ * @fn email_free_mail_data(email_mail_data_t** mail_list, int count)
+ * @brief      Free allocated memroy for emails.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_list        Specifies the pointer of mail structure pointer.
+ * @param[in] count            Specifies the count of mails.
+ * @exception          none
+ * @see                 email_mail_data_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_free_mail()
+ *     {
+ *             email_mail_data_t *mail;
+ *
+ *             //fill the mail structure
+ *             //count - number of mail structure user want to free
+ *              if(EMAIL_ERROR_NONE == email_free_mail_data(&mail,count))
+ *                     //success
+ *              else
+ *                     //failure
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_free_mail_data(email_mail_data_t** mail_list, int count);
+
+/* -----------------------------------------------------------
+                                             Mail Flag API
+    -----------------------------------------------------------*/
+
+/**
+
+ * @fn email_set_flags_field(int *mail_ids, int num, email_flags_field_type field_type, int value, int onserver)
+ * @brief      Change email flags field.
+ *             If the incoming_server_type is EMAIL_SERVER_TYPE_POP3 then from_server value will be 0
+ *                     If the incoming_server_type is EMAIL_SERVER_TYPE_IMAP4 then from_server value will be 1/0
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id  Specifies account ID.
+ * @param[in] mail_ids         Specifies the array of mail ID.
+ * @param[in] num              Specifies the number of mail ID.
+ * @param[in] field_type  Specifies the field type what you want to set. Refer email_flags_field_type.
+ * @param[in] value          Specifies the value what you want to set.
+ * @param[in] onserver         Specifies whether mail Flag updation in server
+ * @exception          none
+ * @see                none
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_set_flags_field()
+ *     {
+ *             int account_id = 0;
+ *                     int mail_id = 0;
+ *                     int err = EMAIL_ERROR_NONE;
+ *
+ *                     printf("\n > Enter account id: ");
+ *                     scanf("%d", &account_id);
+ *
+ *                     printf("\n > Enter mail id: ");
+ *                     scanf("%d", &mail_id);
+ *                     if (EMAIL_ERROR_NONE != email_set_flags_field(&account_id, &mail_id, EMAIL_FLAGS_SEEN_FIELD, 1, 0))
+ *                             printf("email_set_flags_field failed\n");
+ *                     else
+ *                     {
+ *                             printf("email_set_flags_field succeed\n");
+ *                             //do something
+ *                     }
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+
+EXPORT_API int email_set_flags_field(int account_id, int *mail_ids, int num, email_flags_field_type field_type, int value, int onserver);
+
+/* -----------------------------------------------------------
+                                             Mail Move API
+    -----------------------------------------------------------*/
+
+/**
+
+ * @fn email_move_mail_to_mailbox(int *mail_ids, int num, int input_target_mailbox_id)
+ * @brief      Move a email to another mailbox.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id                                  Specifies the array of mail ID.
+ * @param[in] num                                              Specifies the count of mail IDs.
+ * @param[in] input_target_mailbox_id  Specifies the mailbox ID for moving email.
+ * @exception          none
+ * @see                email_mailbox_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_move_mail_to_mailbox()
+ *     {
+ *             int mail_id = 0;
+ *      int mailbox_id = 0;
+ *             int err = EMAIL_ERROR_NONE;
+
+ *             printf("\n > Enter mail_id: ");
+ *             scanf("%d",&mail_id);
+ *
+ *             printf("\n > Enter target mailbox_id: ");
+ *             scanf("%d",&mailbox_id);
+ *
+ *             if(EMAIL_ERROR_NONE == email_move_mail_to_mailbox(&mail_id,     1, mailbox_id))
+ *                     printf("Success\n");
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_move_mail_to_mailbox(int *mail_ids, int num, int input_target_mailbox_id);
+
+
+/**
+ * @fn email_move_all_mails_to_mailbox(int input_source_mailbox_id, int input_target_mailbox_id)
+ * @brief      Move all email to another mailbox.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_source_mailbox_id  Specifies the source mailbox ID for moving email.
+ * @param[in] input_target_mailbox_id  Specifies the destination mailbox ID for moving email.
+ * @exception          none
+ * @see                email_mailbox_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_move_all_mails_to_mailbox()
+ *     {
+ *     int src_mailbox_id;
+ *     int dst_mailbox_id;
+ *             int total_count;
+ *             int err = EMAIL_ERROR_NONE;
+ *             char temp[128];
+ *
+ *
+ *             // input mailbox information : need  account_id and name (src & dest)
+ *             printf("src mail maibox id> ");
+ *             scanf("%d", &src_mailbox_id);
+ *
+ *             // Destination mailbox
+ *             printf("dest mailbox id> ");
+ *             scanf("%d", &dst_mailbox_id);
+ *
+ *             if( EMAIL_ERROR_NONE == email_move_all_mails_to_mailbox(src_mailbox_id, dst_mailbox_id))
+ *             {
+ *                     printf("  fail email_move_all_mails_to_mailbox: \n");
+ *             }
+ *             else
+ *                     //success
+ * }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_move_all_mails_to_mailbox(int input_source_mailbox_id, int input_target_mailbox_id);
+
+/**
+ * @fn email_move_mails_to_mailbox_of_another_account(int input_source_mailbox_id, int *mail_id_array, int mail_id_count, int input_target_mailbox_id, int *output_task_id)
+ * @brief      Move mails to a mailbox of another account.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_source_mailbox_id  Specifies the source mailbox ID for moving email.
+ * @param[in] mail_id_array    Specifies the source mail id array for moving email.
+ * @param[in] mail_id_count    Specifies the count of source mail for moving email.
+ * @param[in] input_target_mailbox_id  Specifies the destination mailbox ID for moving email.
+ * @param[out] output_task_id  Specifies the task id for handling the task.
+ * @exception          none
+ * @remarks N/A
+ */
+EXPORT_API int email_move_mails_to_mailbox_of_another_account(int input_source_mailbox_id, int *mail_id_array, int mail_id_count, int input_target_mailbox_id, int *output_task_id);
+
+
+/**
+
+ * @fn email_get_mail_list_ex(email_list_filter_t *input_filter_list, int input_filter_count, email_list_sorting_rule_t *input_sorting_rule_list, int input_sorting_rule_count, int input_start_index, int input_limit_count, email_mail_list_item_t** output_mail_list, int *output_result_count)
+ * @brief      Get the Mail List information from DB.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_filter_list                        Specifies the filter list
+ * @param[in] input_filter_count               Specifies the number of filter
+ * @param[in] input_sorting_rule_list  Specifies the sorting rule list.
+ * @param[in] input_sorting_rule_count Specifies the number of sorting rule
+ * @param[in] input_start_index                        Specifies start index for LIMIT clause of SQL query.
+ * @param[in] input_limit_count                        Specifies limit count for LIMIT clause of SQL query.
+ * @param[in/out] output_mail_list             Specifies the pointer to the structure email_mail_list_item_t.
+ * @param[in/out] output_result_count  Specifies the number of mails returned.
+ * @exception          none
+ * @see             email_mail_list_item_t
+ * @code
+ * email_list_filter_t *filter_list = NULL;
+ * email_list_sorting_rule_t *sorting_rule_list = NULL;
+ * email_mail_list_item_t *result_mail_list = NULL;
+ * int result_mail_count = 0;
+ * int err = EMAIL_ERROR_NONE;
+ * int i = 0;
+ * filter_list = malloc(sizeof(email_list_filter_t) * 9);
+ * memset(filter_list, 0 , sizeof(email_list_filter_t) * 9);
+ *
+ * filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+ * filter_list[0].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SUBJECT;
+ * filter_list[0].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+ * filter_list[0].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+ * filter_list[0].list_filter_item.rule.case_sensitivity              = false;
+ *
+ * filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+ * filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+ *
+ * filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+ * filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_TO;
+ * filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+ * filter_list[2].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+ * filter_list[2].list_filter_item.rule.case_sensitivity              = false;
+ *
+ * filter_list[3].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+ * filter_list[3].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+ *
+ * filter_list[4].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+ * filter_list[4].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_CC;
+ * filter_list[4].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+ * filter_list[4].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+ * filter_list[4].list_filter_item.rule.case_sensitivity              = false;
+ *
+ * filter_list[5].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+ * filter_list[5].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+ *
+ * filter_list[6].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+ * filter_list[6].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_BCC;
+ * filter_list[6].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+ * filter_list[6].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+ * filter_list[6].list_filter_item.rule.case_sensitivity              = false;
+ *
+ * filter_list[7].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+ * filter_list[7].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+ *
+ * filter_list[8].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+ * filter_list[8].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_FROM;
+ * filter_list[8].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+ * filter_list[8].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+ * filter_list[8].list_filter_item.rule.case_sensitivity              = false;
+ *
+ * sorting_rule_list = malloc(sizeof(email_list_sorting_rule_t) * 2);
+ * memset(sorting_rule_list, 0 , sizeof(email_list_sorting_rule_t) * 2);
+ *
+ * sorting_rule_list[0].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_FLAGS_SEEN_FIELD;
+ * sorting_rule_list[0].sort_order                                    = EMAIL_SORT_ORDER_ASCEND;
+ *
+ * sorting_rule_list[1].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_DATE_TIME;
+ * sorting_rule_list[1].sort_order                                    = EMAIL_SORT_ORDER_ASCEND;
+ *
+ * err = email_get_mail_list_ex(filter_list, 9, sorting_rule_list, 2, -1, -1, &result_mail_list, &result_mail_count);
+ *
+ * if(err == EMAIL_ERROR_NONE) {
+ * printf("email_get_mail_list_ex succeed.\n");
+ *
+ * for(i = 0; i < result_mail_count; i++) {
+ *     printf("mail_id [%d], subject [%s], from [%s]\n", result_mail_list[i].mail_id, result_mail_list[i].subject, result_mail_list[i].from);
+ *     }
+ * }
+ * else {
+ *     printf("email_get_mail_list_ex failed.\n");
+ * }
+ *
+ * email_free_list_filter(&filter_list, 9);
+ *
+ * return FALSE;
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_mail_list_ex(email_list_filter_t *input_filter_list, int input_filter_count, email_list_sorting_rule_t *input_sorting_rule_list, int input_sorting_rule_count, int input_start_index, int input_limit_count, email_mail_list_item_t** output_mail_list, int *output_result_count);
+
+EXPORT_API int email_free_list_filter(email_list_filter_t **input_filter_list, int input_filter_count);
+
+/**
+
+ * @fn email_get_mails(int account_id , int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_data_t** mail_list,  int* result_count)
+ * @brief      Get the Mail List information from DB based on the mailbox name.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id               Specifies the account ID
+ * @param[in] mailbox_id               Specifies the mailbox id
+ * @param[in] thread_id                Specifies the thread id. It can be EMAIL_LIST_TYPE_THREAD, EMAIL_LIST_TYPE_NORMAL or thread id.
+ * @param[in] start_index      Specifies start index for LIMIT clause of SQL query.
+ * @param[in] limit_count      Specifies limit count for LIMIT clause of SQL query.
+ * @param[in] sorting          Specifies the sorting type.
+ * @param[in/out] mail_list            Specifies the pointer to the structure email_mail_data_t.
+ * @param[in/out] result_count Specifies the number of mails returned.
+ * @exception          none
+ * @see                 email_mail_data_t
+
+ * @code
+ *    #include "email-api-account.h"
+ *     bool
+ *     _api_sample_get_mail()
+ *     {
+ *             email_mail_data_t *mail_list = NULL;
+ *             int mailbox_id;
+ *             int result_count = 0;
+ *             int account_id = 0;
+ *             int err_code = EMAIL_ERROR_NONE;
+ *
+ *             printf("\n > Enter Mailbox id: ");
+ *             scanf("%d", mailbox_id);
+ *
+ *             printf("\n > Enter Account_id: ");
+ *             scanf("%d",&account_id);
+ *
+ *             if (EMAIL_ERROR_NONE != email_get_mails(account_id, mailbox_id, EMAIL_LIST_TYPE_NORMAL, 0, 100, EMAIL_SORT_DATETIME_HIGH,  &mail_list, &result_count)) {
+ *                     printf("email_get_mails failed \n");
+ *             }
+ *             else {
+ *                     printf("Success\n");
+ *                     //do something
+ *                     free(mail_list);
+ *             }
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+
+EXPORT_API int email_get_mails(int account_id , int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_data_t** mail_list,  int* result_count);
+
+/**
+
+ * @fn email_get_mail_list(int account_id, int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count)
+ * @brief      Get the Mail List information from DB based on the mailbox name.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id               Specifies the account id
+ * @param[in] mailbox_id               Specifies the mailbox id
+ * @param[in] thread_id                Specifies the thread id. It can be EMAIL_LIST_TYPE_THREAD, EMAIL_LIST_TYPE_NORMAL or thread id.
+ * @param[in] start_index      Specifies start index for LIMIT clause of SQL query.
+ * @param[in] limit_count      Specifies limit count for LIMIT clause of SQL query.
+ * @param[in] sorting          Specifies the sorting type.
+ * @param[in/out] mail_list            Specifies the pointer to the structure email_mail_list_item_t.
+ * @param[in/out] result_count Specifies the number of mails returned.
+ * @exception          none
+ * @see                 email_mail_list_item_t
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_get_mail()
+ *     {
+ *             email_mail_list_item_t *mail_list = NULL;
+ *             int mailbox_id;
+ *             int result_count = 0;
+ *             int account_id = 0;
+ *             int err_code = EMAIL_ERROR_NONE;
+ *
+ *             printf("\n > Enter Mailbox id: ");
+ *             scanf("%d", mailbox_id);
+ *
+ *             printf("\n > Enter Account_id: ");
+ *             scanf("%d",&account_id);
+ *
+ *             if (EMAIL_ERROR_NONE != email_get_mail_list(account_id, mailbox_id, EMAIL_LIST_TYPE_NORMAL, 0, 100, EMAIL_SORT_DATETIME_HIGH,  &mail_list, &result_count))
+ *             {
+ *                     printf("email_get_mail_list_ex failed \n");
+ *             }
+ *             else
+ *             {
+ *                     printf("Success\n");
+ *                     //do something
+ *                     free(mail_list);
+ *             }
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_mail_list(int account_id, int mailbox_id, int thread_id, int start_index, int limit_count, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count);
+
+/**
+
+ * @fn         email_get_mail_by_address(int account_id, int mailbox_id, email_email_address_list_t* addr_list,
+                                                                       int start_index, int limit_count, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count)
+ * @brief      Get the Mail List information from the DB based on the mailbox name account_id and sender address.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id       Specifies the Account ID
+ * @param[in] mailbox_id       Specifies the Mailbox ID
+ * @param[in] addr_list                Specifies the addresses of senders. see email_email_address_list_t
+ * @param[in] start_index              Specifies the first mail index of searched mail. This function will return mails whose index in the result list are from start_index to start_index + limit_count
+ * @param[in] limit_count              Specifies the max number of returned mails.
+ * @param[in] search_type   Specifies the search type.
+ * @param[in] search_value  Specifies the search value.
+ * @param[in] sorting                   Specifies the sorting order. see email_sort_type_t
+ * @param[in/out] mail_list    Specifies the Pointer to the structure email_mail_list_item_t.
+ * @param[in/out] result_count         Specifies the Number of searched Mails
+ * @exception          none
+ * @see                 email_email_address_list_t, email_sort_type_t, email_mail_list_item_t
+ * @code
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_mail_by_address(int account_id , int mailbox_id, email_email_address_list_t* addr_list,
+                                                                       int start_index, int limit_count, int search_type, const char *search_value, email_sort_type_t sorting, email_mail_list_item_t** mail_list,  int* result_count);
+
+/**
+
+ * @fn email_get_thread_information_by_thread_id(int thread_id, email_mail_data_t** thread_info)
+ * @brief      Get the thread information for specific thread from DB based on the mailbox name.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] thread_id            Specifies the thread_id
+ * @param[in/out] thread_info  Specifies the Pointer to the structure email_mail_data_t.
+ * @exception          none
+ * @see             email_mail_data_t
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_get_thread_information()
+ *     {
+ *             email_mail_data_t *thread_info = NULL;
+ *             int thread_id = 0;
+ *             int err_code = EMAIL_ERROR_NONE;
+ *
+ *             printf("\n > Enter thread_id: ");
+ *             scanf("%d",&thread_id);
+ *
+ *             if ( EMAIL_ERROR_NONE != email_get_thread_information_by_thread_id(thread_id, &thread_info))
+ *             {
+ *                     printf("email_get_thread_information_by_thread_id failed :\n"); *
+ *             }
+ *             else
+ *             {
+ *                     printf("Success\n");
+ *                     //do something
+ *             }
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+
+
+EXPORT_API int email_get_thread_information_by_thread_id(int thread_id, email_mail_data_t** thread_info);
+
+/**
+
+ * @fn email_get_thread_information_ex(int thread_id, email_mail_list_item_t** thread_info)
+ * @brief      Get the Mail List information for specific thread from DB based on the mailbox name.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] thread_id            Specifies the thread_id
+ * @param[in/out] thread_info  Specifies the Pointer to the structure email_mail_list_item_t.
+ * @exception          none
+ * @see             email_mail_list_item_t
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_get_thread_information_ex()
+ *     {
+ *             email_mail_list_item_t *thread_info = NULL;
+ *             int thread_id = 0;
+ *             int err_code = EMAIL_ERROR_NONE;
+ *
+ *             printf("\n > Enter thread_id: ");
+ *             scanf("%d",&thread_id);
+ *
+ *             if ( EMAIL_ERROR_NONE != email_get_thread_information_ex(thread_id, &thread_info))
+ *             {
+ *                     printf("email_get_mail_list_of_thread failed :\n"); *
+ *             }
+ *             else
+ *             {
+ *                     printf("Success\n");
+ *                     //do something
+ *             }
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_thread_information_ex(int thread_id, email_mail_list_item_t** thread_info);
+
+
+
+/**
+
+ * @fn email_retry_sending_mail( int mail_id, int timeout_in_sec)
+ * @brief      Retry mail send
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id                  Specifies the mail id for the mail to resend
+ * @param[in] timeout_in_sec   Specifies the timeout value in seconds
+ * @exception          none
+ * @see                 none
+
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_retry_send_mail()
+ *     {
+ *             int mail_id = 1;
+ *             int timeout_in_sec = 2;
+ *
+ *              if(EMAIL_ERROR_NONE == email_retry_sending_mail(mail_id,timeout_in_sec))
+ *                     //success
+ *              else
+ *                     //failure
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_retry_sending_mail(int mail_id, int timeout_in_sec);
+
+EXPORT_API int email_create_db_full();
+
+/**
+
+ * @fn email_cancel_sending_mail( int mail_id)
+ * @brief      Callback function for cm popup. We set the status as EMAIL_MAIL_STATUS_SEND_CANCELED
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id          Specifies the mailID
+ * @exception          none
+ * @see                 none
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_cancel_send_mail()
+ *     {
+ *             int mail_id = 10;
+ *
+ *
+ *              if(EMAIL_ERROR_NONE == email_cancel_sending_mail(mail_id,))
+ *                     //success
+ *              else
+ *                     //failure
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_cancel_sending_mail(int mail_id) ;
+
+ /**
+
+ * @fn email_get_disk_space_usage(unsigned long *total_size)
+ * @brief      Gets the total disk usage of emails in KB.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[out] total_size      total disk usage of emails
+ * @exception          none
+ * @code
+ *     #include "email-api-account.h"
+ *             bool
+ *             _api_sample_get_disk_space_usage()
+ *             {
+ *                     unsigned long total_size = 0;
+ *
+ *                     if ( EMAIL_ERROR_NONE  != email_get_disk_space_usage(&total_size))
+ *                             printf("email_get_disk_space_usage failed err : %d\n",err_code);
+ *                     else
+ *                             printf("email_get_disk_space_usage SUCCESS, total disk usage in KB : %ld \n", total_size);
+ *             }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_disk_space_usage(unsigned long *total_size);
+
+/**
+
+ * @fn         email_get_address_info_list(int mail_id, email_address_info_list_t** address_info_list)
+ * @brief      Get the address info list. The address info list contains from, to, cc, bcc addresses and their display name, contact id and etc. (see email_address_info_list_t)
+ *                     Each GList (from, to, cc, bcc) is the list of email_address_info_t data.
+ *                     "data" variable of GList structure contains email_address_info_t data. <br>
+ *                     To get email_address_info_t data from GList, Use type casting from GList node.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id          Specifies the mail id to get the list.
+ * @param[out] address_info_list       Specifies the Pointer to the structure email_address_info_list_t. Memory for a new address info list will be allocated to this. Call email_free_address_info_list() to free the memory allocated to this.
+ * @exception          none
+ * @see                 email_address_info_list_t, email_address_info_t, email_free_address_info_list()
+ * @code
+ *     #include "email-api-account.h"
+ *     bool
+ *     _api_sample_get_address_info_list()
+ *     {
+ *             email_address_info_list_t *p_address_info_list= NULL;
+ *             email_address_info_t *p_address_info = NULL;
+ *             int mai_id;
+ *             int err_code = EMAIL_ERROR_NONE;
+ *
+ *             mail_id = 1;
+ *
+ *             if ( EMAIL_ERROR_NONE != (err_code = email_get_address_info_list(mail_id, &p_address_info_list)) )
+ *             {
+ *                     printf("email_get_address_info_list failed :\n"); *
+ *                     return false;
+ *             }
+ *             else
+ *             {
+ *                     printf("Success\n");
+ *                     //do something with p_address_info_list
+ *                     GList *list = p_address_info_list->from;
+ *                     GList *node = g_list_first(list);
+ *                     while ( node != NULL )
+ *                     {
+ *                             p_address_info = (email_address_info_t*)node->data;
+ *                             printf("%d,  %s, %s, %d\n", p_address_info->address_type, p_address_info->address, p_address_info->display_name, p_address_info->contact_id);
+ *
+ *                             node = g_list_next(node);
+ *                     }
+ *             }
+ *
+ *             // Free sender list
+ *             if ( p_address_info_list )
+ *             {
+ *                     email_free_address_info_list(&p_address_info_list);
+ *             }
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_address_info_list(int mail_id, email_address_info_list_t** address_info_list);
+
+/**
+
+ * @fn email_free_address_info_list(email_address_info_list_t **address_info_list)
+ * @brief      Free the address info list allocated by email_get_address_info_list(). This function will free the memory which is allocated to address_info_list itself.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] address_info_list        Specifies the Pointer to the structure email_address_info_list_t to be freed.
+ * @exception          none
+ * @see                 email_address_info_list_t, email_get_address_info_list()
+ */
+EXPORT_API int email_free_address_info_list(email_address_info_list_t **address_info_list);
+
+/**
+
+ * @fn email_get_structure(const char*encoded_string, void **struct_var, email_convert_struct_type_e type)
+ * @brief      This function returns the structure of the type which is indicated by 'type' variable. This function will allocate new memory to 'struct_var' for structure.<br>
+ *                     Some notifications such as NOTI_DOWNLOAD_NEW_MAIL are published with string parameter. The string contains various values that might be divided by delimiter.<br>
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] encoded_string           Specifies the Pointer to the string from notification.
+ * @param[out] struct_var                      Specifies the Pointer to the structure to be returned. If success, new memory for structure will be allocated.
+ * @param[in] type                             Specifies the converting type. see email_convert_struct_type_e
+ * @exception          none
+ * @see                 email_convert_struct_type_e
+ */
+EXPORT_API int email_get_structure(const char*encoded_string, void **struct_var, email_convert_struct_type_e type);
+
+/**
+
+ * @fn email_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req)
+ * @brief      Get the information of meeting request.  The information of meeting request is based on Mail Id. <br>
+ *                     The information of meeting request is corresponding to only one mail.
+ *                     For this reason, the information of meeting request can be added by using email_add_message_with_meeting_request() with a matched mail information.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success. This function returns EMAIL_ERROR_DATA_NOT_FOUND if there isn't a matched mail. Otherwise it returns error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id          Specifies the Mail id for which  meeting request details need to be fetched
+ * @param[in/out] meeting_req  Specifies the Pointer to the structure email_meeting_request_t.
+ * @exception          none
+ * @see                 email_meeting_request_t
+ */
+EXPORT_API int email_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req);
+
+
+/**
+
+ * @fn email_free_meeting_request(email_meeting_request_t** meeting_req, int count)
+ * @brief      Free the meeting request allocated by email_get_meeting_request() or alloacted to add. This function will free the memory which is allocated to meeting_req (= *meeting_req) itself.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] email_meeting_request_t  Specifies the Pointer to the structure email_meeting_request_t to be freed.
+ * @param[in] count    Specifies the number of elements in meeting_req array. this is usually 1.
+ * @exception          none
+ * @see                 email_meeting_request_t, email_get_meeting_request()
+ */
+EXPORT_API int email_free_meeting_request(email_meeting_request_t** meeting_req, int count);
+
+EXPORT_API int email_move_thread_to_mailbox(int thread_id, int target_mailbox_id, int move_always_flag);
+
+EXPORT_API int email_delete_thread(int thread_id, int delete_always_flag);
+
+EXPORT_API int email_modify_seen_flag_of_thread(int thread_id, int seen_flag, int on_server);
+
+EXPORT_API int email_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/**
+* @} @}
+*/
+
+
+#endif /* __EMAIL_API_MAIL_H__ */
diff --git a/email-api/include/email-api-mailbox.h b/email-api/include/email-api-mailbox.h
new file mode 100755 (executable)
index 0000000..aefe23b
--- /dev/null
@@ -0,0 +1,349 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_API_MAILBOX_H__
+#define __EMAIL_API_MAILBOX_H__
+
+#include "email-types.h"
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_API_MAILBOX Email Mailbox API
+* @{
+*/
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-mailbox.h
+ * @author     Kyuho Jo <kyuho.jo@samsung.com>
+ * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
+ * @version    0.1
+ * @brief              This file contains the data structures and interfaces of mailbox provided by
+ *                     email-service .
+ * @{
+ * @code
+ *
+ *  #include "email_api_mailbox.h"
+ *
+ *  bool other_app_invoke_uniform_api_sample(int *error_code)
+ *     {
+ *             email_mailbox_t mailbox;
+ *             email_mailbox_t *new_mailbox =NULL;
+ *             email_mailbox_t *mailbox_list = NULL;
+ *             int count = 0;
+ *             int mailbox_type;
+ *             int handle = 0;
+ *             char *pMaiboxName;
+ *             char *pParentMailbox;
+ *
+ *             memset(&mailbox,0x00,sizeof(email_mailbox_t));
+ *             mailbox.mailbox_name = strdup("test");
+ *             mailbox.alias = strdup("Personal");
+ *             mailbox.account_id = 1;
+ *             printf("Enter local_yn(1/0)");
+ *             scanf("%d",&local_yn);
+ *             mailbox.local=local_yn;
+ *             mailbox.mailbox_type = 7;
+ *
+ *             //create new mailbox
+ *
+ *             if(EMAIL_ERR_NONE != email_add_mailbox(&mailbox,local_yn,&handle))
+ *                     printf("email_add_mailbox failed\n");
+ *             else
+ *                     printf("email_add_mailbox success");
+ *
+ *             //delete mailbox
+ *
+ *             if(EMAIL_ERROR_NONE != email_delete_mailbox(mailbox,local_yn,&handle))
+ *                     printf("email_delete_mailbox failed\n");
+ *             else
+ *                     printf("email_delete_mailbox success\n");
+ *
+ *             //free mailbox
+ *             email_free_mailbox("new_mailbox,1");
+ *
+ *             //Get mailbox list
+ *             if(EMAIL_ERROR_NONE != email_get_mailbox_list(account_id,local_yn,&mailbox_list,&count))
+ *                     //failure
+ *             else
+ *                     //success
+ *
+ *             //Get mailbox by name
+ *             pMailboxName = strdup("test");
+ *             if(EMAIL_ERROR_NONE != email_get_mailbox_by_name(account_id,pMailboxName,&mailbox_list))
+ *                     //failure
+ *             else
+ *                     //success
+ *
+ *             //Get child mailbox list
+ *             pParentMailbox = strdup("test");
+ *             if(EMAIL_ERROR_NONE != email_get_child_mailbox_list(account_id, paerent_mailbox,&mailbox_list,&count))
+ *                     //failure
+ *             else
+ *                     //success
+ *
+ *             //Get mailbox by mailbox_type
+ *             printf("Enter mailbox_type\n");
+ *             scanf("%d",&mailbox_type);
+ *             if(EMAIL_ERROR_NONE != email_get_mailbox_by_mailbox_type(account_id,mailbox_type,&mailbox_list))
+ *                     //failure
+ *             else
+ *                     //success
+ *
+ *     }
+ *
+ * @endcode
+ * @}
+ */
+
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+/**
+ * @fn int email_add_mailbox(email_mailbox_t* new_mailbox, int on_server, int *handle)
+ * @brief      Create a new mailbox or mailbox.This function is invoked when user wants to create a new mailbox for the specified account.
+ *             If On_server is true then it will create the mailbox on server as well as in local also.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] new_mailbox      Specifies the pointer of creating mailbox information.
+*  @param[in] on_server                Specifies the creating mailbox on server.
+ * @param[out] handle          Specifies the sending handle.
+ * @exception  none
+ * @see        email_mailbox_t
+  * @remarks N/A
+ */
+EXPORT_API int email_add_mailbox(email_mailbox_t *new_mailbox, int on_server, int *handle);
+
+/**
+ * @fn int email_rename_mailbox(int input_mailbox_id, char *input_mailbox_name, char *input_mailbox_alias)
+ * @brief      Change mailbox name. This function is invoked when user wants to change the name of existing mail box.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mailbox_id Specifies the id of the mailbox.
+ * @param[in] input_mailbox_name       Specifies the name of the mailbox.
+ * @param[in] input_mailbox_alias      Specifies the alias of the mailbox.
+ * @param[in] input_on_server  Specifies the moving mailbox on server.
+ * @param[out] output_handle   Specifies the handle to manage tasks.
+ *
+ * @exception see email-errors.h
+ * @see        email_mailbox_t, email_mailbox_type_e
+ * @remarks N/A
+ */
+EXPORT_API int email_rename_mailbox(int input_mailbox_id, char *input_mailbox_name, char *input_mailbox_alias, int input_on_server, int *output_handle);
+
+/**
+ * @fn int email_delete_mailbox(int input_mailbox_id, int input_on_server, int *output_handle)
+ * @brief      Delete a mailbox or mailbox.This function deletes the existing mailbox for specified account based on the option on_server.
+ *             If the on_server is true then it deletes mailbox from server as well as locally.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mailbox_id Specifies the id of target mailbox .
+ * @param[in] input_on_server  Specifies the deleting mailbox on server.
+ * @param[out] output_handle   Specifies the sending handle.
+ * @exception  see email-errors.h
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_delete_mailbox(int input_mailbox_id, int input_on_server, int *output_handle);
+
+EXPORT_API int email_delete_mailbox_ex(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, int input_on_server, int *output_handle);
+
+/**
+ * @fn int email_set_mailbox_type(int input_mailbox_id, email_mailbox_type_e input_mailbox_type)
+ * @brief      Change the mailbox type. This function is invoked when user wants to change the mailbox type.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mailbox_id         Specifies the id of the mailbox.
+ * @param[in] input_mailbox_type       Specifies the mailbox type.
+ * @exception see email-errors.h
+ * @see        email_mailbox_type_e
+ * @remarks N/A
+ */
+EXPORT_API int email_set_mailbox_type(int input_mailbox_id, email_mailbox_type_e input_mailbox_type);
+
+
+/**
+ * @fn int email_set_local_mailbox(int input_mailbox_id, int input_is_local_mailbox)
+ * @brief      Change the attribute 'local' of email_mailbox_t. This function is invoked when user wants to change the attribute 'local'.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mailbox_id                 Specifies the id of the mailbox.
+ * @param[in] input_is_local_mailbox   Specifies the value of the attribute 'local' of email_mailbox_t.
+ * @exception see email-errors.h
+ * @see                none
+ * @remarks N/A
+ */
+EXPORT_API int email_set_local_mailbox(int input_mailbox_id, int input_is_local_mailbox);
+
+/**
+ * @fn email_get_mailbox_list(int account_id, int mailbox_sync_type, email_mailbox_t** mailbox_list, int* count)
+ * @brief      Get all mailboxes from account.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id               Specifies the account ID.
+ * @param[in] mailbox_sync_type                Specifies the sync type.
+ * @param[out] mailbox_list    Specifies the pointer of mailbox structure pointer.(possibly NULL)
+ * @param[out] count                   The mailbox count is saved here.(possibly 0)
+ * @exception          none
+ * @see        email_mailbox_t
+
+ * @code
+ *     #include "email-api-mailbox.h"
+ *     bool
+ *     _api_sample_get_mailbox_list()
+ *     {
+ *             int account_id =0,count = 0;
+ *             int mailbox_sync_type;
+ *             int error_code = EMAIL_ERROR_NONE;
+ *             email_mailbox_t *mailbox_list=NULL;
+ *
+ *             printf("\n > Enter account id: ");
+ *             scanf("%d", &account_id);
+ *             printf("\n > Enter mailbox_sync_type: ");
+ *             scanf("%d", &mailbox_sync_type);
+ *
+ *             if((EMAIL_ERROR_NONE != email_get_mailbox_list(account_id, mailbox_sync_type, &mailbox_list, &count)))
+ *             {
+ *                     printf(" Error\n");
+ *             }
+ *             else
+ *             {
+ *                     printf("Success\n");
+ *                     email_free_mailbox(&mailbox_list,count);
+ *             }
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_get_mailbox_list(int account_id, int mailbox_sync_type, email_mailbox_t** mailbox_list, int* count);
+
+EXPORT_API int email_get_mailbox_list_ex(int account_id, int mailbox_sync_type, int with_count, email_mailbox_t** mailbox_list, int* count);
+
+/**
+ * @fn email_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type,  email_mailbox_t** mailbox)
+ * @brief      Get mailbox by mailbox_type.This function is invoked when user wants to know the mailbox information by mailbox_type for the given account.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id               Specifies the account ID.
+ * @param[in] mailbox_type             Specifies the mailbox type.
+ * @param[out] mailbox         Specifies the pointer of mailbox structure pointer.(possibly NULL)
+ * @exception none
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type,  email_mailbox_t** mailbox);
+
+/**
+ * @fn email_get_mailbox_by_mailbox_id(int input_mailbox_id, email_mailbox_t** output_mailbox)
+ * @brief      Get mailbox by mailbox_id. This function is invoked when user wants to know the mailbox information by mailbox id.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in]  input_mailbox_id        Specifies the mailbox id.
+ * @param[out] output_mailbox  Specifies the pointer of mailbox structure pointer.(possibly NULL)
+ * @exception none
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_get_mailbox_by_mailbox_id(int input_mailbox_id, email_mailbox_t** output_mailbox);
+
+/**
+ * @fn email_set_mail_slot_size(int input_account_id, int input_mailbox_id, int input_new_slot_size)
+ * @brief      Set mail slot size.This function is invoked when user wants to set the size of mail slot.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_account_id         Specifies the account ID.
+ * @param[in] input_mailbox_id         Specifies the mailbox id.
+ * @param[in] input_new_slot_size      Specifies the mail slot size.
+ * @exception none
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_set_mail_slot_size(int input_account_id, int input_mailbox_id, int input_new_slot_size);
+
+/**
+ * @fn email_stamp_sync_time_of_mailbox(int input_mailbox_id)
+ * @brief      Stamp sync time of mailbox. This function is invoked when user wants to set the sync time of the mailbox.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code(refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_mailbox_id         Specifies the mailbox id.
+ * @exception none
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_stamp_sync_time_of_mailbox(int input_mailbox_id);
+
+
+/**
+ * @fn email_free_mailbox(email_mailbox_t** mailbox_list, int count)
+ * @brief      Free allocated memory for mailbox information.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mailbox_list     Specifies the pointer for searching mailbox structure pointer.
+ * @param[in] count                    Specifies the count of mailboxes.
+ * @exception          none
+ * @see                 email_mailbox_t
+
+ * @code
+ *     #include "email-api-mailbox.h"
+ *     bool
+ *     _api_sample_free_mailbox_info()
+ *     {
+ *             email_mailbox_t *mailbox;
+ *
+ *             //fill the mailbox structure
+ *             //count - number of mailbox structure user want to free
+ *              if(EMAIL_ERROR_NONE == email_free_mailbox(&mailbox,count))
+ *                     //success
+ *              else
+ *                     //failure
+ *
+ *     }
+ * @endcode
+ * @remarks N/A
+ */
+
+EXPORT_API int email_free_mailbox(email_mailbox_t** mailbox_list, int count);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/**
+* @} @}
+*/
+
+#endif /* __EMAIL_API_MAILBOX_H__ */
+
+
diff --git a/email-api/include/email-api-network.h b/email-api/include/email-api-network.h
new file mode 100755 (executable)
index 0000000..10375ea
--- /dev/null
@@ -0,0 +1,358 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_API_NETWORK_H__
+#define __EMAIL_API_NETWORK_H__
+
+#include "email-types.h"
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_API_NETWORK Email Network API
+* @{
+*/
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-network.h
+ * @author     Kyuho Jo <kyuho.jo@samsung.com>
+ * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
+ * @version    0.1
+ * @brief              This file contains the data structures and interfaces of Network related Functionality provided by
+ *                     email-service .
+ *
+ * @{
+
+ * @code
+
+ *     #include "email-api.h"
+ *
+ *     bool
+ *     other_app_invoke_uniform_api_sample(int* error_code)
+ *     {
+ *
+ *             // Send a mail
+ *             email_attachment_data_t attachment;
+ *             int account_id = 1;
+ *             int mailbox_id = 0;
+ *             int attachment_id = 0;
+ *             int err = EMAIL_ERROR_NONE;
+ *             int mail_id = 0;
+ *             int action = -1;
+ *
+ *             printf("Enter mail id\n");
+ *             scanf("%d",&mail_id);
+ *
+ *             if(EMAIL_ERROR_NONE == email_send_mail(mail_id, &handle))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *             // Download header of new emails from mail server
+ *             int handle = 0;
+ *
+ *             mailbox.account_id = account_id;
+ *             printf("Enter mailbox id\n");
+ *             scanf("%d",&mailbox_id);
+ *             if(EMAIL_ERROR_NONE == email_sync_header (account_id, mailbox_id, &handle))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *             //Sync mail header for all accounts
+ *             if(EMAIL_ERROR_NONE == email_sync_header_for_all_account(&handle))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *             //Download email body from server
+ *
+ *             if(EMAIL_ERROR_NONE == email_download_body (mail_id,0,&handle))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *             //Download a email nth-attachment from server
+ *             prinf("Enter attachment number\n");
+ *             scanf("%d",&attachment_id);
+ *             if(EMAIL_ERROR_NONE == email_download_attachment(mail_id, attachment_id, &handle))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *             //Cancel job
+ *             if(EMAIL_ERROR_NONE == email_cancel_job(account_id,handle))//canceling download email nth attachment from server job.
+ *                                                                     //so this handle contains the value return by the email_download_attachment()
+ *                     //success
+ *             else
+ *                     //failure
+ *             //Get pending job listfor an account
+ *
+ *             printf( " Enter Action \n SEND_MAIL = 0 \n SYNC_HEADER = 1 \n" \
+ *                         " DOWNLOAD_BODY,= 2 \n DOWNLOAD_ATTACHMENT = 3 \n" \
+ *                         " DELETE_MAIL = 4 \n SEARCH_MAIL = 5 \n SAVE_MAIL = 6 \n" \
+ *                         " NUM = 7 \n");
+ *             scanf("%d",&action);
+ *             if(EMAIL_ERROR_NONE == email_get_pending_job(action,account_id,mail_id,&status))
+ *                     //success
+ *             else
+ *                     //error
+ *
+ *             //Get Network status
+ *             if(EMAIL_ERROR_NONE == email_get_network_status(&sending,&receiving))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *             //Send read report
+ *             if(EMAIL_ERROR_NONE == email_send_report(mail ,&handle))
+ *                     //success
+ *             else
+ *                     //failure
+ *             //Save and send
+ *
+ *
+ *             if(EMAIL_ERROR_NONE  == email_add_mail(mail,NULL,0, NULL, 0))
+ *             {
+ *                     if(EMAIL_ERROR_NONE == email_send_saved(account_id,&option,&handle))
+ *                             //success
+ *                     else
+ *                             //failure
+ *             }
+ *             //Get Imap mailbox list
+ *             if(EMAIL_ERROR_NONE == email_sync_imap_mailbox_list(account_id,  &handle))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ * }
+ *
+ * @endcode
+ * @}
+
+ */
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/**
+
+ * @fn email_send_mail(int mail_id,    int *handle)
+ * @brief      Send a mail.This function is invoked when user wants to send a composed mail.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id                  Specifies the mail ID.
+ * @param[out] handle          Specifies the sending handle.
+ * @exception  none
+ * @see        email_mailbox_t and email_option_t
+ * @remarks N/A
+ */
+EXPORT_API int email_send_mail(int mail_id,    int *handle);
+
+EXPORT_API int email_send_mail_with_downloading_attachment_of_original_mail(int input_mail_id, int *output_handle);
+
+
+/**
+
+ * @fn email_sync_header(int input_account_id, int input_mailbox_id, int *handle)
+ * @brief      Download header of new emails from mail server.This function is invoked when user wants to download only header of new mails.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_account_id         Specifies the account ID.
+ * @param[in] input_mailbox_id         Specifies the mailbox ID.
+ * @param[out] handle          Specifies the handle for stopping downloading.
+ * @exception  none
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_sync_header(int input_account_id, int input_mailbox_id, int *handle);
+
+
+/**
+
+ * @fn email_sync_header_for_all_account(int *handle)
+ * @brief      Download header of new emails from mail server for all emails.This function is invoked when user wants to download header of new mails for all accounts.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[out] handle          Specifies the handle for stopping downloading.
+ * @exception none
+ * @see        none
+ * @remarks N/A
+ */
+EXPORT_API int email_sync_header_for_all_account(int *handle);
+
+
+/**
+
+ * @fn email_download_body(int mail_id, int with_attachment, int *handle)
+ * @brief      Download email body from server.This function is invoked when user wants to download email body with/without attachment based on the option with_attachment
+ *             from the server.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id                  Specifies the mail ID.
+ * @param[in] with_attachment  Specifies the whether attachment is there or not.
+ * @param[out] handle          Specifies the handle for stopping downloading.
+ * @exception none
+ * @see email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_download_body(int mail_id, int with_attachment, int *handle);
+
+
+
+
+
+
+/**
+
+ * @fn email_download_attachment(int mail_id, const char* nth, int *handle);
+ * @brief      Download a email nth-attachment from server.This function is invoked if user wants to download only specific attachment of a mail whose body is already downloaded.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] mail_id          Specifies the mail ID.
+ * @param[in] nth                      Specifies the attachment number been saved. the minimum number is "1".
+ * @param[out] handle          Specifies the handle for stopping downloading.
+ * @exception none
+ * @see        email_mailbox_t
+ * @remarks N/A
+ */
+EXPORT_API int email_download_attachment(int mail_id, int nth, int *handle);
+
+
+/**
+
+ * @fn email_cancel_job(int account_id, int handle);
+ * @brief      cancel the ongoing job.This function is invoked if user wants to cancel any ongoing job of a specified account.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] input_account_id Specifies the account ID.
+ * @param[in] input_handle             Specifies the handle for stopping the operation.
+ * @param[in] input_cancel_type        Specifies the type of cancellation.
+ * @exception   none
+ * @see        none
+ * @remarks N/A
+ */
+
+EXPORT_API int email_cancel_job(int input_account_id, int input_handle, email_cancelation_type input_cancel_type);
+
+
+/**
+
+ * @fn email_get_pending_job(email_action_t action, int account_id, int mail_id, email_event_status_type_t * status);
+ * @brief      get pending job list.This function is invoked if user wants to get the pending job list with status information .
+ *             Based on action item of a mail is for a specific account this will give all pending job list.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id       Specifies the action of the job.
+ * @param[in] account_id       Specifies the account ID.
+ * @param[in] mail_id          Specifies the mail ID.
+ * @param[out]status           Specifies the status of the job.
+ * @exception   none
+ * @see        email_action_t and email_event_status_type_t
+ * @remarks N/A
+ */
+EXPORT_API int email_get_pending_job(email_action_t action, int account_id, int mail_id, email_event_status_type_t * status);
+
+
+/**
+
+ * @fn email_get_network_status(int* on_sending, int* on_receiving)
+ * @brief      This function gives the  current network status.This gives the information to the user whether sending operation is in progress or receiving operation.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[out] on_sending              True if sending is in progress.
+ * @param[out] on_receiving            True if receivng is in progress.
+ * @exception  none
+ * @see        none
+ * @remarks N/A
+ */
+EXPORT_API int email_get_network_status(int* on_sending, int* on_receiving);
+
+/**
+
+ * @fn email_send_saved(int account_id, int *handle)
+ * @brief      Send all mails to been saved in Offline-mode.This function is invoked when user wants to send an email and after saving it.
+ *             This will save the email in draft mailbox and then sends.
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id                       Specifies the account ID.
+ * @param[out] handle                          Specifies the handle for stopping sending.
+ * @exception none
+ * @see email_option_t
+ * @remarks N/A
+ */
+EXPORT_API int email_send_saved(int account_id, int *handle);
+
+/**
+
+ * @fn email_sync_imap_mailbox_list(int account_id, int *handle)
+ *  @brief     fetch all the mailbox names from server and store the non-existing mailboxes in DB.This function is invoked when user wants to download all server mailboxes from IMAP server
+ *
+ * @return     This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id                       Specifies the account ID.
+ * @param[out] handle                  Specifies the handle for stopping Network operation.
+ * @exception  none
+ * @see        none
+ * @remarks N/A
+ */
+EXPORT_API int email_sync_imap_mailbox_list(int account_id, int *handle);
+
+/**
+
+ * @fn email_search_mail_on_server(int input_account_id, int input_mailbox_id, email_search_filter_t *input_search_filter_list, int input_search_filter_count, int *output_handle)
+ * @brief      Search the mails on server.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] account_id       Specifies the Account ID
+ * @param[in] mailbox_id       Specifies the Mailbox ID
+ * @param[in] search_type      Specifies the searching type(EMAIL_SEARCH_FILTER_SUBJECT,  EMAIL_SEARCH_FILTER_SENDER, EMAIL_SEARCH_FILTER_RECIPIENT, EMAIL_SEARCH_FILTER_ALL)
+ * @param[in] search_value     Specifies the value to use for searching. (ex : Subject, email address, display name)
+ * @exception          none
+ * @see email_search_filter_t,
+ * @code
+ * @endcode
+ * @remarks N/A
+ */
+EXPORT_API int email_search_mail_on_server(int input_account_id, int input_mailbox_id, email_search_filter_t *input_search_filter_list, int input_search_filter_count, int *output_handle);
+
+EXPORT_API int email_clear_result_of_search_mail_on_server(int input_account_id);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/**
+* @}
+*/
+
+
+#endif /* __EMAIL_API_NETWORK_H__ */
diff --git a/email-api/include/email-api-rule.h b/email-api/include/email-api-rule.h
new file mode 100755 (executable)
index 0000000..84df72c
--- /dev/null
@@ -0,0 +1,216 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_API_RULE_H__
+#define __EMAIL_API_RULE_H__
+
+#include "email-types.h"
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_API_RULE Email Rule API
+* @{
+*/
+
+ /**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api-rule.h
+ * @author     Kyuho Jo <kyuho.jo@samsung.com>
+ * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
+ * @version    0.1
+ * @brief              This file contains the data structures and interfaces of Rule related Functionality provided by
+ *                     email-service .
+ * @{
+
+ * @code
+ *     #include "email-api-rule.h"
+ *     bool
+ *     other_app_invoke_uniform_api_sample(int* error_code)
+ *     {
+ *             int err = EMAIL_ERROR_NONE;
+ *             email_rule_t*  rule = NULL;
+ *             int filter_id = 1;
+ *             int count = 0;
+ *
+ *             // Get a information of filtering
+ *             printf("Enter filter Id:\n");
+ *             scanf("%d",&filter_id);
+ *
+ *             if(EMAIL_ERROR_NONE == email_get_rule (filter_id,&rule))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *             // Get all filterings
+ *             if(EMAIL_ERROR_NONE == email_get_rule_list(&rule,&count))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *
+ *             // Add a filter information
+ *             if(EMAIL_ERROR_NONE == email_add_rule (rule))
+ *                     //success
+ *             else
+ *                     //failure
+ *             err = email_free_rule (&rule,1);
+ *
+ *             // Change a filter information
+ *             if(EMAIL_ERROR_NONE == email_update_rule (filter_id,rule))
+ *                     //success
+ *             else
+ *                     //failure
+ *             err = email_free_rule (&rule,1);
+ *
+ *             // Delete a filter information
+ *             printf("Enter filter Id:\n");
+ *             scanf("%d",&filter_id);
+ *
+ *             if(EMAIL_ERROR_NONE == email_delete_rule (filter_id))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *             // Free allocated memory
+ *             if(EMAIL_ERROR_NONE == email_free_rule (&rule,1))
+ *                     //success
+ *             else
+ *                     //failure
+ *
+ *     }
+ *
+ * @endcode
+ * @}
+ */
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/**
+
+
+ * @fn email_get_rule(int filter_id, email_rule_t** filtering_set)
+ * @brief      Get a information of filtering.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure
+ * @param[in] filter_id                        Specifies the filter ID.
+ * @param[out] filtering_set   The returned information of filter are saved here.
+ * @exception  EMAIL_ERROR_INVALID_PARAM       -Invalid argument
+ * @see        email_rule_t
+ * @remarks N/A
+ */
+EXPORT_API int email_get_rule(int filter_id, email_rule_t** filtering_set);
+
+/**
+
+
+ * @fn email_get_rule_list(email_rule_t** filtering_set, int* count)
+ * @brief      Get all filterings.This function gives all the filter rules already set before by user.
+ *             This will provide total number of filter rules available and information of all rules.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure
+ * @param[out] filtering_set           The returned filterings are saved here.(possibly NULL)
+ * @param[out] count                           The count of returned filters is saved here.(possibly 0)
+ * @exception  EMAIL_ERROR_INVALID_PARAM       -Invalid argument
+ * @see        email_rule_t
+ * @remarks N/A
+ */
+EXPORT_API int email_get_rule_list(email_rule_t** filtering_set, int* count);
+
+/**
+
+
+ * @fn email_add_rule(email_rule_t* filtering_set)
+ * @brief      Add a filter information.This function is invoked if user wants to add a new filter rule.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] filtering_set            Specifies the pointer of adding filter structure.
+ * @exception  EMAIL_ERROR_INVALID_PARAM       -Invalid argument
+ * @see        email_rule_t
+ * @remarks N/A
+ */
+EXPORT_API int email_add_rule(email_rule_t* filtering_set);
+
+/**
+
+
+ * @fn email_update_rule(int filter_id, email_rule_t* new_set)
+ * @brief      Change a filter information.This function will update the existing filter rule with new information.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure.
+ * @param[in] filter_id        Specifies the original filter ID.
+ * @param[in] new_set  Specifies the information of new filter.
+ * @exception  EMAIL_ERROR_INVALID_PARAM       -Invalid argument
+ * @see        email_rule_t
+ * @remarks N/A
+ */
+EXPORT_API int email_update_rule(int filter_id, email_rule_t* new_set);
+
+/**
+
+ * @fn email_delete_rule(int filter_id)
+ * @brief      Delete a filter information.This function will delete the exsting filter information by specified filter Id.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure
+ * @param[in] filter_id        Specifies the filter ID.
+ * @exception  EMAIL_ERROR_INVALID_PARAM       -Invalid argument
+ * @see        none
+ * @remarks N/A
+ */
+EXPORT_API int email_delete_rule(int filter_id);
+
+
+
+/**
+
+ * @fn email_free_rule (email_rule_t** filtering_set, int count)
+ * @brief      Free allocated memory.
+ *
+ * @return This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR_XXX) on failure
+ * @param[in] filtering_set    Specifies the pointer of pointer of filter structure for memory free.
+ * @param[in] count                    Specifies the count of filter.
+ * @exception  EMAIL_ERROR_INVALID_PARAM       -Invalid argument
+ * @see        email_rule_t
+ * @remarks N/A
+ */
+EXPORT_API int email_free_rule (email_rule_t** filtering_set, int count);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/**
+* @} @}
+*/
+
+
+#endif /* __EMAIL_API_RULE_H__ */
diff --git a/email-api/include/email-api-smime.h b/email-api/include/email-api-smime.h
new file mode 100755 (executable)
index 0000000..5188cd3
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 __EMAIL_API_SMIME_H__
+#define __EMAIL_API_SMIME_H__
+
+#include "email-types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+EXPORT_API int email_add_certificate(char *certificate_path, char *email_address);
+
+EXPORT_API int email_delete_certificate(char *email_address);
+
+EXPORT_API int email_get_certificate(char *email_address, email_certificate_t **certificate);
+
+EXPORT_API int email_get_decrypt_message(int mail_id, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
+
+EXPORT_API int email_verify_signature(int mail_id, int *verify);
+
+EXPORT_API int email_verify_certificate(char *certificate_path, int *verify);
+
+EXPORT_API int email_get_resolve_recipients(int account_id, char *email_address, unsigned *handle);
+
+EXPORT_API int email_validate_certificate(int account_id, char *email_address, unsigned *handle);
+
+EXPORT_API int email_free_certificate(email_certificate_t **certificate, int count);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* __EMAIL_API_SMIME_H__ */
diff --git a/email-api/include/email-api.h b/email-api/include/email-api.h
new file mode 100755 (executable)
index 0000000..8da1b26
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_API_H__
+#define __EMAIL_API_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "email-types.h"
+#include "email-api-account.h"
+#include "email-api-init.h"
+#include "email-api-mail.h"
+#include "email-api-mailbox.h"
+#include "email-api-network.h"
+#include "email-api-rule.h"
+#include "email-api-smime.h"
+#include "email-api-etc.h"
+
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+/**
+* @{
+*/
+
+/**
+ *
+ * This file contains the data structures and interfaces needed for application,
+ * to interact with email-service.
+ * @file               email-api.h
+ * @author     Kyuho Jo <kyuho.jo@samsung.com>
+ * @author     Sunghyun Kwon <sh0701.kwon@samsung.com>
+ * @version    0.1
+ * @brief              This file contains the data structures and interfaces provided by
+ *                     email-service.
+ */
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/**
+* @} @}
+*/
+
+#endif /* __EMAIL_MAPI_H__ */
+
+
diff --git a/email-common-use/CMakeLists.txt b/email-common-use/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..0244b78
--- /dev/null
@@ -0,0 +1,50 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(email-common-use)
+
+SET(CMAKE_SKIP_BUILD_RPATH TRUE)
+
+IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+       SET(CMAKE_BUILD_TYPE "Debug")
+ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+
+MESSAGE("")
+MESSAGE(">>> current directory: ${CMAKE_CURRENT_SOURCE_DIR}")
+MESSAGE(">>> Build type: ${CMAKE_BUILD_TYPE}")
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden")
+
+SET(COMMON-USE-LIB "email-common-use")
+SET(COMMON-USE-SRCS 
+       ${CMAKE_SOURCE_DIR}/email-common-use/email-convert.c
+       ${CMAKE_SOURCE_DIR}/email-common-use/email-utilities.c
+       ${CMAKE_SOURCE_DIR}/email-common-use/tpl.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/email-daemon/include
+       ${CMAKE_SOURCE_DIR}/email-common-use/include/ 
+       ${CMAKE_SOURCE_DIR}/email-core/include/
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include/
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(common_pkgs REQUIRED glib-2.0 dlog dbus-1 vconf contacts-service2 uw-imap-toolkit) 
+
+FOREACH(flag ${common_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+#message(">>>[${COMMON-USE-LIB}] extra_cflags ${EXTRA_CFLAGS}")
+#message(">>>[${COMMON-USE-LIB}] common_pkgs_cflags ${common_pkgs_CFLAGS}")
+#message(">>>[${COMMON-USE-LIB}] result ${CMAKE_C_FLAGS}")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${COMMON-USE-LIB} SHARED ${COMMON-USE-SRCS})
+TARGET_LINK_LIBRARIES(${COMMON-USE-LIB} ${common_pkgs_LDFLAGS})
+SET_TARGET_PROPERTIES(${COMMON-USE-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${COMMON-USE-LIB} PROPERTIES VERSION ${VERSION})
+
+INSTALL(TARGETS ${COMMON-USE-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
diff --git a/email-common-use/email-convert.c b/email-common-use/email-convert.c
new file mode 100755 (executable)
index 0000000..2c1e730
--- /dev/null
@@ -0,0 +1,1227 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 <stdlib.h>
+#include <stdio.h>
+#include "string.h"
+#include "email-convert.h"
+#include "email-core-mail.h"
+#include "email-debug-log.h"
+#include "email-core-utils.h"
+#include "email-utilities.h"
+#include "email-storage.h"
+#include "tpl.h"
+
+#define fSEEN 0x1
+#define fDELETED 0x2
+#define fFLAGGED 0x4
+#define fANSWERED 0x8
+#define fOLD 0x10
+#define fDRAFT 0x20
+#define fATTACHMENT 0x40
+#define fFORWARD    0x80
+
+INTERNAL_FUNC int em_convert_mail_tbl_to_mail_status(emstorage_mail_tbl_t *mail_tbl_data, int *result_mail_status, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_tbl_data[%p], result_mail_status [%p], err_code[%p]", mail_tbl_data, result_mail_status, err_code);
+       int ret = false, error_code = EMAIL_ERROR_NONE;
+       int attachment_count = 0;
+
+       if(!mail_tbl_data || !result_mail_status) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       attachment_count = (mail_tbl_data->attachment_count > mail_tbl_data->inline_content_count) ? 1 : 0;
+
+       *result_mail_status = (mail_tbl_data->flags_seen_field      ? fSEEN       : 0) |
+                             (mail_tbl_data->flags_deleted_field   ? fDELETED    : 0) |
+                             (mail_tbl_data->flags_flagged_field   ? fFLAGGED    : 0) |
+                             (mail_tbl_data->flags_answered_field  ? fANSWERED   : 0) |
+                             (mail_tbl_data->flags_recent_field    ? fOLD        : 0) |
+                             (mail_tbl_data->flags_draft_field     ? fDRAFT      : 0) |
+                             (attachment_count                       ? fATTACHMENT : 0) |
+                             (mail_tbl_data->flags_forwarded_field ? fFORWARD    : 0);
+
+       ret = true;
+FINISH_OFF:
+               if (err_code != NULL)
+               *err_code = error_code;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+       }
+
+INTERNAL_FUNC int em_convert_mail_status_to_mail_tbl(int mail_status, emstorage_mail_tbl_t *result_mail_tbl_data, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_status[%d], result_mail_tbl_data [%p], err_code[%p]", mail_status, result_mail_tbl_data, err_code);
+       int ret = false, error_code = EMAIL_ERROR_NONE;
+
+       if(!result_mail_tbl_data) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       result_mail_tbl_data->flags_seen_field           = (mail_status & fSEEN       ? 1 : 0);
+       result_mail_tbl_data->flags_deleted_field        = (mail_status & fDELETED    ? 1 : 0);
+       result_mail_tbl_data->flags_flagged_field        = (mail_status & fFLAGGED    ? 1 : 0);
+       result_mail_tbl_data->flags_answered_field       = (mail_status & fANSWERED   ? 1 : 0);
+       result_mail_tbl_data->flags_recent_field         = (mail_status & fOLD        ? 1 : 0);
+       result_mail_tbl_data->flags_draft_field          = (mail_status & fDRAFT      ? 1 : 0);
+       result_mail_tbl_data->flags_forwarded_field      = (mail_status & fFORWARD    ? 1 : 0);
+
+       ret = true;
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error_code;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int em_convert_account_to_account_tbl(email_account_t *account, emstorage_account_tbl_t *account_tbl)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p], account_tbl[%p]", account, account_tbl);
+       int ret = 1;
+
+       account_tbl->account_name                             = EM_SAFE_STRDUP(account->account_name);
+       account_tbl->incoming_server_type                     = account->incoming_server_type;
+       account_tbl->incoming_server_address                  = EM_SAFE_STRDUP(account->incoming_server_address);
+       account_tbl->user_email_address                       = EM_SAFE_STRDUP(account->user_email_address);
+       account_tbl->incoming_server_user_name                = EM_SAFE_STRDUP(account->incoming_server_user_name);
+       account_tbl->incoming_server_password                 = EM_SAFE_STRDUP(account->incoming_server_password);
+       account_tbl->retrieval_mode                           = account->retrieval_mode;
+       account_tbl->incoming_server_port_number              = account->incoming_server_port_number;
+       account_tbl->incoming_server_secure_connection        = account->incoming_server_secure_connection;
+       account_tbl->outgoing_server_type                     = account->outgoing_server_type;
+       account_tbl->outgoing_server_address                  = EM_SAFE_STRDUP(account->outgoing_server_address);
+       account_tbl->outgoing_server_port_number              = account->outgoing_server_port_number;
+       account_tbl->outgoing_server_need_authentication      = account->outgoing_server_need_authentication;
+       account_tbl->outgoing_server_secure_connection        = account->outgoing_server_secure_connection;
+       account_tbl->outgoing_server_user_name                = EM_SAFE_STRDUP(account->outgoing_server_user_name);
+       account_tbl->outgoing_server_password                 = EM_SAFE_STRDUP(account->outgoing_server_password);
+       account_tbl->user_display_name                        = EM_SAFE_STRDUP(account->user_display_name);
+       account_tbl->reply_to_address                         = EM_SAFE_STRDUP(account->reply_to_address);
+       account_tbl->return_address                           = EM_SAFE_STRDUP(account->return_address);
+       account_tbl->account_id                               = account->account_id;
+       account_tbl->keep_mails_on_pop_server_after_download  = account->keep_mails_on_pop_server_after_download;
+       account_tbl->auto_download_size                       = account->auto_download_size;
+       account_tbl->outgoing_server_use_same_authenticator   = account->outgoing_server_use_same_authenticator;
+       account_tbl->pop_before_smtp                          = account->pop_before_smtp;
+       account_tbl->incoming_server_requires_apop            = account->incoming_server_requires_apop;
+       account_tbl->logo_icon_path                           = EM_SAFE_STRDUP(account->logo_icon_path);
+
+       account_tbl->user_data                                = em_memdup(account->user_data, account->user_data_length);
+       account_tbl->user_data_length                         = account->user_data_length;
+
+       account_tbl->options.priority                         = account->options.priority;
+       account_tbl->options.keep_local_copy                  = account->options.keep_local_copy;
+       account_tbl->options.req_delivery_receipt             = account->options.req_delivery_receipt;
+       account_tbl->options.req_read_receipt                 = account->options.req_read_receipt;
+       account_tbl->options.download_limit                   = account->options.download_limit;
+       account_tbl->options.block_address                    = account->options.block_address;
+       account_tbl->options.block_subject                    = account->options.block_subject;
+       account_tbl->options.display_name_from                = EM_SAFE_STRDUP(account->options.display_name_from);
+       account_tbl->options.reply_with_body                  = account->options.reply_with_body;
+       account_tbl->options.forward_with_files               = account->options.forward_with_files;
+       account_tbl->options.add_myname_card                  = account->options.add_myname_card;
+       account_tbl->options.add_signature                    = account->options.add_signature;
+       account_tbl->options.signature                        = EM_SAFE_STRDUP(account->options.signature);
+       account_tbl->options.add_my_address_to_bcc            = account->options.add_my_address_to_bcc;
+       account_tbl->check_interval                           = account->check_interval;
+       account_tbl->account_svc_id                           = account->account_svc_id;
+       account_tbl->sync_status                              = account->sync_status;
+       account_tbl->sync_disabled                            = account->sync_disabled;
+       account_tbl->default_mail_slot_size                   = account->default_mail_slot_size;
+       account_tbl->smime_type                               = account->smime_type;
+       account_tbl->certificate_path                         = EM_SAFE_STRDUP(account->certificate_path);
+       account_tbl->cipher_type                              = account->cipher_type;
+       account_tbl->digest_type                              = account->digest_type;
+
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int em_convert_account_tbl_to_account(emstorage_account_tbl_t *account_tbl, email_account_t *account)
+{
+       EM_DEBUG_FUNC_BEGIN("account_tbl[%p], account[%p]", account_tbl, account);
+       int ret = 1;
+
+       account->account_name                             = EM_SAFE_STRDUP(account_tbl->account_name);
+       account->incoming_server_type                     = account_tbl->incoming_server_type;
+       account->incoming_server_address                  = EM_SAFE_STRDUP(account_tbl->incoming_server_address);
+       account->user_email_address                       = EM_SAFE_STRDUP(account_tbl->user_email_address);
+       account->incoming_server_user_name                = EM_SAFE_STRDUP(account_tbl->incoming_server_user_name);
+       account->incoming_server_password                 = EM_SAFE_STRDUP(account_tbl->incoming_server_password);
+       account->retrieval_mode                           = account_tbl->retrieval_mode;
+       account->incoming_server_port_number              = account_tbl->incoming_server_port_number;
+       account->incoming_server_secure_connection        = account_tbl->incoming_server_secure_connection;
+       account->outgoing_server_type                     = account_tbl->outgoing_server_type;
+       account->outgoing_server_address                  = EM_SAFE_STRDUP(account_tbl->outgoing_server_address);
+       account->outgoing_server_port_number              = account_tbl->outgoing_server_port_number;
+       account->outgoing_server_need_authentication      = account_tbl->outgoing_server_need_authentication;
+       account->outgoing_server_secure_connection        = account_tbl->outgoing_server_secure_connection;
+       account->outgoing_server_user_name                = EM_SAFE_STRDUP(account_tbl->outgoing_server_user_name);
+       account->outgoing_server_password                 = EM_SAFE_STRDUP(account_tbl->outgoing_server_password);
+       account->user_display_name                        = EM_SAFE_STRDUP(account_tbl->user_display_name);
+       account->reply_to_address                         = EM_SAFE_STRDUP(account_tbl->reply_to_address);
+       account->return_address                           = EM_SAFE_STRDUP(account_tbl->return_address);
+       account->account_id                               = account_tbl->account_id;
+       account->keep_mails_on_pop_server_after_download  = account_tbl->keep_mails_on_pop_server_after_download;
+       account->auto_download_size                       = account_tbl->auto_download_size;
+       account->outgoing_server_use_same_authenticator   = account_tbl->outgoing_server_use_same_authenticator;
+       account->pop_before_smtp                          = account_tbl->pop_before_smtp;
+       account->incoming_server_requires_apop            = account_tbl->incoming_server_requires_apop;
+       account->logo_icon_path                           = EM_SAFE_STRDUP(account_tbl->logo_icon_path);
+       account->user_data                     = em_memdup(account_tbl->user_data, account_tbl->user_data_length);
+       account->user_data_length              = account_tbl->user_data_length;
+       account->options.priority                         = account_tbl->options.priority;
+       account->options.keep_local_copy                  = account_tbl->options.keep_local_copy;
+       account->options.req_delivery_receipt             = account_tbl->options.req_delivery_receipt;
+       account->options.req_read_receipt                 = account_tbl->options.req_read_receipt;
+       account->options.download_limit                   = account_tbl->options.download_limit;
+       account->options.block_address                    = account_tbl->options.block_address;
+       account->options.block_subject                    = account_tbl->options.block_subject;
+       account->options.display_name_from                = EM_SAFE_STRDUP(account_tbl->options.display_name_from);
+       account->options.reply_with_body                  = account_tbl->options.reply_with_body;
+       account->options.forward_with_files               = account_tbl->options.forward_with_files;
+       account->options.add_myname_card                  = account_tbl->options.add_myname_card;
+       account->options.add_signature                    = account_tbl->options.add_signature;
+       account->options.signature                        = EM_SAFE_STRDUP(account_tbl->options.signature);
+       account->options.add_my_address_to_bcc            = account_tbl->options.add_my_address_to_bcc;
+       account->check_interval                           = account_tbl->check_interval;
+       account->account_svc_id                           = account_tbl->account_svc_id;
+       account->sync_status                              = account_tbl->sync_status;
+       account->sync_disabled                            = account_tbl->sync_disabled;
+       account->default_mail_slot_size                   = account_tbl->default_mail_slot_size;
+       account->smime_type                               = account_tbl->smime_type;
+       account->certificate_path                         = EM_SAFE_STRDUP(account_tbl->certificate_path);
+       account->cipher_type                              = account_tbl->cipher_type;
+       account->digest_type                              = account_tbl->digest_type;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int em_convert_mailbox_to_mailbox_tbl(email_mailbox_t *mailbox, emstorage_mailbox_tbl_t *mailbox_tbl)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox[%p], mailbox_tbl[%p]", mailbox, mailbox_tbl);
+       int ret = 1;
+
+       mailbox_tbl->account_id                 = mailbox->account_id;
+       mailbox_tbl->mailbox_id                 = mailbox->mailbox_id;
+       mailbox_tbl->mailbox_name               = EM_SAFE_STRDUP(mailbox->mailbox_name);
+       mailbox_tbl->alias                      = EM_SAFE_STRDUP(mailbox->alias);
+       mailbox_tbl->local_yn                   = mailbox->local;
+       mailbox_tbl->mailbox_type               = mailbox->mailbox_type;
+       mailbox_tbl->unread_count               = mailbox->unread_count;
+       mailbox_tbl->total_mail_count_on_local  = mailbox->total_mail_count_on_local;
+       mailbox_tbl->total_mail_count_on_server = mailbox->total_mail_count_on_server;
+       mailbox_tbl->mail_slot_size             = mailbox->mail_slot_size;
+       mailbox_tbl->no_select                  = mailbox->no_select;
+       mailbox_tbl->last_sync_time             = mailbox->last_sync_time;
+       mailbox_tbl->deleted_flag               = mailbox->deleted_flag;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int em_convert_mailbox_tbl_to_mailbox(emstorage_mailbox_tbl_t *mailbox_tbl, email_mailbox_t *mailbox)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_tbl[%p], mailbox[%p]", mailbox_tbl, mailbox);
+       int ret = 1;
+
+       mailbox->account_id                 = mailbox_tbl->account_id;
+       mailbox->mailbox_id                 = mailbox_tbl->mailbox_id;
+       mailbox->mailbox_name               = EM_SAFE_STRDUP(mailbox_tbl->mailbox_name);
+       mailbox->alias                      = EM_SAFE_STRDUP(mailbox_tbl->alias);
+       mailbox->local                      = mailbox_tbl->local_yn;
+       mailbox->mailbox_type               = mailbox_tbl->mailbox_type;
+       mailbox->unread_count               = mailbox_tbl->unread_count;
+       mailbox->total_mail_count_on_local  = mailbox_tbl->total_mail_count_on_local;
+       mailbox->total_mail_count_on_server = mailbox_tbl->total_mail_count_on_server;
+       mailbox->mail_slot_size             = mailbox_tbl->mail_slot_size;
+       mailbox->no_select                  = mailbox_tbl->no_select;
+       mailbox->last_sync_time             = mailbox_tbl->last_sync_time;
+       mailbox->deleted_flag               = mailbox_tbl->deleted_flag;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int em_convert_mail_tbl_to_mail_data(emstorage_mail_tbl_t *mail_table_data, int item_count, email_mail_data_t **mail_data, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_table_data[%p], item_count [%d], mail_data[%p]", mail_table_data, item_count, mail_data);
+       int i, ret = false, err_code = EMAIL_ERROR_NONE;
+       email_mail_data_t *temp_mail_data = NULL;
+
+       if (!mail_table_data || !mail_data || !item_count) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       temp_mail_data = em_malloc(sizeof(email_mail_data_t) * item_count);
+
+       if(!temp_mail_data) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < item_count; i++) {
+               temp_mail_data[i].mail_id                 = mail_table_data[i].mail_id;
+               temp_mail_data[i].account_id              = mail_table_data[i].account_id;
+               temp_mail_data[i].mailbox_id              = mail_table_data[i].mailbox_id;
+               temp_mail_data[i].mailbox_type            = mail_table_data[i].mailbox_type;
+               temp_mail_data[i].subject                 = EM_SAFE_STRDUP(mail_table_data[i].subject);
+               temp_mail_data[i].date_time               = mail_table_data[i].date_time;
+               temp_mail_data[i].server_mail_status      = mail_table_data[i].server_mail_status;
+               temp_mail_data[i].server_mailbox_name     = EM_SAFE_STRDUP(mail_table_data[i].server_mailbox_name);
+               temp_mail_data[i].server_mail_id          = EM_SAFE_STRDUP(mail_table_data[i].server_mail_id);
+               temp_mail_data[i].message_id              = EM_SAFE_STRDUP(mail_table_data[i].message_id);
+               temp_mail_data[i].reference_mail_id       = mail_table_data[i].reference_mail_id;
+               temp_mail_data[i].full_address_from       = EM_SAFE_STRDUP(mail_table_data[i].full_address_from);
+               temp_mail_data[i].full_address_reply      = EM_SAFE_STRDUP(mail_table_data[i].full_address_reply);
+               temp_mail_data[i].full_address_to         = EM_SAFE_STRDUP(mail_table_data[i].full_address_to);
+               temp_mail_data[i].full_address_cc         = EM_SAFE_STRDUP(mail_table_data[i].full_address_cc);
+               temp_mail_data[i].full_address_bcc        = EM_SAFE_STRDUP(mail_table_data[i].full_address_bcc);
+               temp_mail_data[i].full_address_return     = EM_SAFE_STRDUP(mail_table_data[i].full_address_return);
+               temp_mail_data[i].email_address_sender    = EM_SAFE_STRDUP(mail_table_data[i].email_address_sender);
+               temp_mail_data[i].email_address_recipient = EM_SAFE_STRDUP(mail_table_data[i].email_address_recipient);
+               temp_mail_data[i].alias_sender            = EM_SAFE_STRDUP(mail_table_data[i].alias_sender);
+               temp_mail_data[i].alias_recipient         = EM_SAFE_STRDUP(mail_table_data[i].alias_recipient);
+               temp_mail_data[i].body_download_status    = mail_table_data[i].body_download_status;
+               temp_mail_data[i].file_path_plain         = EM_SAFE_STRDUP(mail_table_data[i].file_path_plain);
+               temp_mail_data[i].file_path_html          = EM_SAFE_STRDUP(mail_table_data[i].file_path_html);
+               temp_mail_data[i].file_path_mime_entity   = EM_SAFE_STRDUP(mail_table_data[i].file_path_mime_entity);
+               temp_mail_data[i].mail_size               = mail_table_data[i].mail_size;
+               temp_mail_data[i].flags_seen_field        = mail_table_data[i].flags_seen_field;
+               temp_mail_data[i].flags_deleted_field     = mail_table_data[i].flags_deleted_field;
+               temp_mail_data[i].flags_flagged_field     = mail_table_data[i].flags_flagged_field;
+               temp_mail_data[i].flags_answered_field    = mail_table_data[i].flags_answered_field;
+               temp_mail_data[i].flags_recent_field      = mail_table_data[i].flags_recent_field;
+               temp_mail_data[i].flags_draft_field       = mail_table_data[i].flags_draft_field;
+               temp_mail_data[i].flags_forwarded_field   = mail_table_data[i].flags_forwarded_field;
+               temp_mail_data[i].DRM_status              = mail_table_data[i].DRM_status;
+               temp_mail_data[i].priority                = mail_table_data[i].priority;
+               temp_mail_data[i].save_status             = mail_table_data[i].save_status;
+               temp_mail_data[i].lock_status             = mail_table_data[i].lock_status;
+               temp_mail_data[i].report_status           = mail_table_data[i].report_status;
+               temp_mail_data[i].attachment_count        = mail_table_data[i].attachment_count;
+               temp_mail_data[i].inline_content_count    = mail_table_data[i].inline_content_count;
+               temp_mail_data[i].thread_id               = mail_table_data[i].thread_id;
+               temp_mail_data[i].thread_item_count       = mail_table_data[i].thread_item_count;
+               temp_mail_data[i].preview_text            = EM_SAFE_STRDUP(mail_table_data[i].preview_text);
+               temp_mail_data[i].meeting_request_status  = mail_table_data[i].meeting_request_status;
+               temp_mail_data[i].message_class           = mail_table_data[i].message_class;
+               temp_mail_data[i].digest_type             = mail_table_data[i].digest_type;
+               temp_mail_data[i].smime_type              = mail_table_data[i].smime_type;
+       }
+
+       *mail_data = temp_mail_data;
+
+       ret = true;
+FINISH_OFF:
+
+       if(error)
+               *error = err_code;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int   em_convert_mail_data_to_mail_tbl(email_mail_data_t *mail_data, int item_count, emstorage_mail_tbl_t **mail_table_data, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_data[%p], item_count [%d], mail_table_data[%p]", mail_data, item_count, mail_table_data);
+       int i, ret = false, err_code = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *temp_mail_tbl = NULL;
+
+       if (!mail_data || !mail_table_data || !item_count) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       temp_mail_tbl = em_malloc(sizeof(emstorage_mail_tbl_t) * item_count);
+
+       if(!temp_mail_tbl) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < item_count; i++) {
+               temp_mail_tbl[i].mail_id                 = mail_data[i].mail_id;
+               temp_mail_tbl[i].account_id              = mail_data[i].account_id;
+               temp_mail_tbl[i].mailbox_id              = mail_data[i].mailbox_id;
+               temp_mail_tbl[i].mailbox_type            = mail_data[i].mailbox_type;
+               temp_mail_tbl[i].date_time               = mail_data[i].date_time;
+               temp_mail_tbl[i].subject                 = EM_SAFE_STRDUP(mail_data[i].subject);
+               temp_mail_tbl[i].server_mail_status      = mail_data[i].server_mail_status;
+               temp_mail_tbl[i].server_mailbox_name     = EM_SAFE_STRDUP(mail_data[i].server_mailbox_name);
+               temp_mail_tbl[i].server_mail_id          = EM_SAFE_STRDUP(mail_data[i].server_mail_id);
+               temp_mail_tbl[i].message_id              = EM_SAFE_STRDUP(mail_data[i].message_id);
+               temp_mail_tbl[i].reference_mail_id       = mail_data[i].reference_mail_id;
+               temp_mail_tbl[i].full_address_from       = EM_SAFE_STRDUP(mail_data[i].full_address_from);
+               temp_mail_tbl[i].full_address_reply      = EM_SAFE_STRDUP(mail_data[i].full_address_reply);
+               temp_mail_tbl[i].full_address_to         = EM_SAFE_STRDUP(mail_data[i].full_address_to);
+               temp_mail_tbl[i].full_address_cc         = EM_SAFE_STRDUP(mail_data[i].full_address_cc);
+               temp_mail_tbl[i].full_address_bcc        = EM_SAFE_STRDUP(mail_data[i].full_address_bcc);
+               temp_mail_tbl[i].full_address_return     = EM_SAFE_STRDUP(mail_data[i].full_address_return);
+               temp_mail_tbl[i].email_address_sender    = EM_SAFE_STRDUP(mail_data[i].email_address_sender);
+               temp_mail_tbl[i].email_address_recipient = EM_SAFE_STRDUP(mail_data[i].email_address_recipient);
+               temp_mail_tbl[i].alias_sender            = EM_SAFE_STRDUP(mail_data[i].alias_sender);
+               temp_mail_tbl[i].alias_recipient         = EM_SAFE_STRDUP(mail_data[i].alias_recipient);
+               temp_mail_tbl[i].body_download_status    = mail_data[i].body_download_status;
+               temp_mail_tbl[i].file_path_plain         = EM_SAFE_STRDUP(mail_data[i].file_path_plain);
+               temp_mail_tbl[i].file_path_html          = EM_SAFE_STRDUP(mail_data[i].file_path_html);
+               temp_mail_tbl[i].file_path_mime_entity   = EM_SAFE_STRDUP(mail_data[i].file_path_mime_entity);
+               temp_mail_tbl[i].mail_size               = mail_data[i].mail_size;
+               temp_mail_tbl[i].flags_seen_field        = mail_data[i].flags_seen_field;
+               temp_mail_tbl[i].flags_deleted_field     = mail_data[i].flags_deleted_field;
+               temp_mail_tbl[i].flags_flagged_field     = mail_data[i].flags_flagged_field;
+               temp_mail_tbl[i].flags_answered_field    = mail_data[i].flags_answered_field;
+               temp_mail_tbl[i].flags_recent_field      = mail_data[i].flags_recent_field;
+               temp_mail_tbl[i].flags_draft_field       = mail_data[i].flags_draft_field;
+               temp_mail_tbl[i].flags_forwarded_field   = mail_data[i].flags_forwarded_field;
+               temp_mail_tbl[i].DRM_status              = mail_data[i].DRM_status;
+               temp_mail_tbl[i].priority                = mail_data[i].priority;
+               temp_mail_tbl[i].save_status             = mail_data[i].save_status;
+               temp_mail_tbl[i].lock_status             = mail_data[i].lock_status;
+               temp_mail_tbl[i].report_status           = mail_data[i].report_status;
+               temp_mail_tbl[i].attachment_count        = mail_data[i].attachment_count;
+               temp_mail_tbl[i].inline_content_count    = mail_data[i].inline_content_count;
+               temp_mail_tbl[i].thread_id               = mail_data[i].thread_id;
+               temp_mail_tbl[i].thread_item_count       = mail_data[i].thread_item_count;
+               temp_mail_tbl[i].preview_text            = EM_SAFE_STRDUP(mail_data[i].preview_text);
+               temp_mail_tbl[i].meeting_request_status  = mail_data[i].meeting_request_status;
+               temp_mail_tbl[i].message_class           = mail_data[i].message_class;
+               temp_mail_tbl[i].digest_type             = mail_data[i].digest_type;
+               temp_mail_tbl[i].smime_type              = mail_data[i].smime_type;
+       }
+
+       *mail_table_data = temp_mail_tbl;
+
+       ret = true;
+FINISH_OFF:
+
+       if(error)
+                       *error = err_code;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+
+}
+
+
+
+INTERNAL_FUNC int em_convert_string_to_time_t(char *input_datetime_string, time_t *output_time)
+{
+       EM_DEBUG_FUNC_BEGIN("input_datetime_string[%s], output_time[%p]", input_datetime_string, output_time);
+
+       char buf[16] = { 0, };
+       struct tm temp_time_info = { 0 };
+
+       if (!input_datetime_string || !output_time) {
+               EM_DEBUG_EXCEPTION("input_datetime_string[%p], output_time[%p]", input_datetime_string, output_time);
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       memset(buf, 0x00, sizeof(buf));
+       SNPRINTF(buf, sizeof(buf), "%.4s", input_datetime_string);
+       temp_time_info.tm_year = atoi(buf) - 1970;
+
+       memset(buf, 0x00, sizeof(buf));
+       SNPRINTF(buf, sizeof(buf), "%.2s", input_datetime_string + 4);
+       temp_time_info.tm_mon = atoi(buf) - 1;
+
+       memset(buf, 0x00, sizeof(buf));
+       SNPRINTF(buf, sizeof(buf), "%.2s", input_datetime_string + 6);
+       temp_time_info.tm_mday = atoi(buf);
+
+       memset(buf, 0x00, sizeof(buf));
+       SNPRINTF(buf, sizeof(buf), "%.2s", input_datetime_string + 8);
+       temp_time_info.tm_hour = atoi(buf);
+
+       memset(buf, 0x00, sizeof(buf));
+       SNPRINTF(buf, sizeof(buf), "%.2s", input_datetime_string + 10);
+       temp_time_info.tm_min = atoi(buf);
+
+       memset(buf, 0x00, sizeof(buf));
+       SNPRINTF(buf, sizeof(buf), "%.2s", input_datetime_string + 12);
+       temp_time_info.tm_sec = atoi(buf);
+
+       *output_time = timegm(&temp_time_info);
+
+       EM_DEBUG_LOG("*output_time [%d", *output_time);
+
+       EM_DEBUG_FUNC_END("err %d", EMAIL_ERROR_NONE);
+       return EMAIL_ERROR_NONE;
+}
+
+INTERNAL_FUNC int em_convert_time_t_to_string(time_t *input_time, char **output_datetime_string)
+{
+       EM_DEBUG_FUNC_BEGIN("input_time[%p], output_datetime_string[%p]", input_time, output_datetime_string);
+       char temp_buffer[20] = { 0, };
+       struct tm *temp_time_info;
+
+       if (!input_time || !output_datetime_string) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       temp_time_info = localtime(input_time);
+
+       if(!temp_time_info) {
+               EM_DEBUG_EXCEPTION("localtime failed.");
+               return EMAIL_ERROR_SYSTEM_FAILURE;
+       }
+       SNPRINTF(temp_buffer, sizeof(temp_buffer), "%04d%02d%02d%02d%02d%02d",
+               temp_time_info->tm_year + 1970, temp_time_info->tm_mon, temp_time_info->tm_mday, temp_time_info->tm_hour, temp_time_info->tm_min, temp_time_info->tm_sec);
+
+       *output_datetime_string = EM_SAFE_STRDUP(temp_buffer);
+
+       EM_DEBUG_FUNC_END("err %d", EMAIL_ERROR_NONE);
+       return EMAIL_ERROR_NONE;
+}
+
+static char* append_sized_data_to_stream(char *stream, int *stream_len, char *src, int src_len)
+{
+       /* EM_DEBUG_FUNC_BEGIN("input_stream [%p], input_output_stream_length [%p], input_sized_data [%p], input_data_size [%d]", input_stream, input_output_stream_length, input_sized_data, input_data_size); */
+       char *new_stream = NULL;
+
+       if( !stream_len || src_len == 0 || src == NULL || (stream != NULL && *stream_len == 0) ||
+                       (stream == NULL && *stream_len != 0) ) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return NULL;
+       }
+
+       int old_stream_len = *stream_len;
+
+       /*TODO: don't increase stream buffer incrementally when appending new data */
+       new_stream = (char*)em_malloc(old_stream_len + src_len);
+
+       if(!new_stream) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               return NULL;
+       }
+
+       if(stream != NULL)
+               memcpy(new_stream, stream, old_stream_len);
+
+       memcpy(new_stream + old_stream_len, src, src_len);
+
+       *stream_len = old_stream_len + src_len;
+
+       EM_SAFE_FREE(stream);
+       /* EM_DEBUG_FUNC_END("*input_output_stream_length [%d]", *input_output_stream_length); */
+       return new_stream;
+}
+
+
+static char* append_string_to_stream(char *input_stream, int *input_output_stream_length, char *input_source_string)
+{
+       EM_DEBUG_FUNC_BEGIN("input_stream [%p], input_output_stream_length [%p] input_source_string[%p]", input_stream, input_output_stream_length, input_source_string);
+       char *new_stream = NULL;
+       int   data_length = 0;
+
+       if( !input_output_stream_length || (input_stream != NULL && *input_output_stream_length == 0) ||
+               (input_stream == NULL && *input_output_stream_length != 0) ) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return NULL;
+       }
+
+       int source_stream_length = *input_output_stream_length;
+
+       data_length = EM_SAFE_STRLEN(input_source_string);
+
+       new_stream = (char*)em_malloc(source_stream_length + data_length + sizeof(int));
+
+       if(!new_stream) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               return NULL;
+       }
+
+       if(input_stream != NULL)
+               memcpy(new_stream, input_stream, source_stream_length);
+
+       /* write string length */
+       memcpy(new_stream + source_stream_length, (char*)&data_length, sizeof(int));
+
+       /* write string */
+       if(input_source_string)
+               memcpy(new_stream + source_stream_length + sizeof(int), input_source_string, data_length);
+
+       /* for example, "abc" is written to stream buffer with "3abc" */
+       *input_output_stream_length = source_stream_length + sizeof(int) + data_length;
+
+       EM_SAFE_FREE(input_stream);
+       EM_DEBUG_FUNC_END("*input_output_stream_length [%d]", *input_output_stream_length);
+       return new_stream;
+}
+
+static int fetch_sized_data_from_stream(char *input_stream, int *input_output_stream_offset, int input_data_size, char *output_data)
+{
+       /* EM_DEBUG_FUNC_BEGIN("input_stream [%p], input_output_stream_offset [%p] input_data_size [%d], output_data[%p]", input_stream, input_output_stream_offset, input_data_size, output_data); */
+       int stream_offset = 0;
+
+       if( !input_stream || !input_output_stream_offset || !input_data_size || !output_data) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       stream_offset = *input_output_stream_offset;
+
+       memcpy(output_data, input_stream + stream_offset, input_data_size);
+       stream_offset += input_data_size;
+
+       *input_output_stream_offset = stream_offset;
+
+       /* EM_DEBUG_FUNC_END("stream_offset [%d]", stream_offset); */
+       return EMAIL_ERROR_NONE;
+}
+
+
+static int fetch_string_from_stream(char *input_stream, int *input_output_stream_offset, char **output_string)
+{
+       /* EM_DEBUG_FUNC_BEGIN("input_stream [%p], input_output_stream_offset [%p] output_string[%p]", input_stream, input_output_stream_offset, output_string); */
+       int string_length = 0;
+       int stream_offset = 0;
+       char *result_string = NULL;
+
+       if( !input_stream || !input_output_stream_offset || !output_string) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       stream_offset = *input_output_stream_offset;
+       /*      EM_DEBUG_LOG("stream_offset [%d]", stream_offset);      */
+
+       memcpy(&string_length, input_stream + stream_offset, sizeof(int));
+       stream_offset +=  sizeof(int);
+
+       /*      EM_DEBUG_LOG("string_length [%d]", string_length);      */
+
+       if(string_length != 0) {
+               result_string = (char*)em_malloc(string_length + 1);
+               if(result_string) {
+                       memcpy(result_string, input_stream + stream_offset, string_length);
+                       stream_offset += string_length;
+               }
+       }
+       /*
+       if(result_string)
+               EM_DEBUG_LOG("result_string [%s]", result_string);
+       */
+
+       *output_string              = result_string;
+       *input_output_stream_offset = stream_offset;
+
+       /* EM_DEBUG_FUNC_END("stream_offset [%d]", stream_offset); */
+       return EMAIL_ERROR_NONE;
+}
+                                    /* divide struct at binary field (void* user_data)*/
+#define EMAIL_ACCOUNT_FMT   "S(" "isiii" "is" ")" "B" "S(" "issss"  "isiss" "iiiii" "isiss" "iii"\
+                                 "$(" "iiiii" "iisii" "iisi" ")" "iiisii" ")"
+
+
+INTERNAL_FUNC char* em_convert_account_to_byte_stream(email_account_t* account, int *stream_len)
+{
+       EM_DEBUG_FUNC_END();
+       EM_IF_NULL_RETURN_VALUE(account, NULL);
+
+       tpl_node *tn = NULL;
+       tpl_bin tb;
+
+       tn = tpl_map(EMAIL_ACCOUNT_FMT, account, &tb, &(account->user_data_length));
+       tb.sz = account->user_data_length;
+       tb.addr = account->user_data;
+       tpl_pack(tn, 0);
+
+       /* write account to buffer */
+       void *buf = NULL;
+       size_t len = 0;
+       tpl_dump(tn, TPL_MEM, &buf, &len);
+       tpl_free(tn);
+
+       *stream_len = len;
+       EM_DEBUG_FUNC_END();
+       return (char*) buf;
+}
+
+
+INTERNAL_FUNC void em_convert_byte_stream_to_account(char *stream, int stream_len, email_account_t *account)
+{
+       EM_DEBUG_FUNC_END();
+       EM_NULL_CHECK_FOR_VOID(stream);
+       EM_NULL_CHECK_FOR_VOID(account);
+
+       tpl_node *tn = NULL;
+       tpl_bin tb;
+
+       tn = tpl_map(EMAIL_ACCOUNT_FMT, account, &tb, &(account->user_data_length));
+       tpl_load(tn, TPL_MEM, stream, stream_len);
+       tpl_unpack(tn, 0);
+       tpl_free(tn);
+
+       /* tb will be destroyed at end of func, but tb.addr remains */
+       account->user_data = tb.addr;
+
+       EM_DEBUG_FUNC_END();
+}
+
+#define EMAIL_MAIL_DATA_FMT  "S(" "iiiis" "iisss" "issss" "sssss" "sisss"\
+                            "icccc" "cccii" "iiiii" "iisii" "ii" ")"
+
+INTERNAL_FUNC char* em_convert_mail_data_to_byte_stream(email_mail_data_t *mail_data, int *stream_len)
+{
+       EM_DEBUG_FUNC_END();
+       EM_IF_NULL_RETURN_VALUE(mail_data, NULL);
+       EM_IF_NULL_RETURN_VALUE(stream_len, NULL);
+
+       tpl_node *tn = NULL;
+
+       tn = tpl_map(EMAIL_MAIL_DATA_FMT, mail_data);
+       tpl_pack(tn, 0);
+
+       /* write account to buffer */
+       void *buf = NULL;
+       size_t len = 0;
+       tpl_dump(tn, TPL_MEM, &buf, &len);
+       tpl_free(tn);
+
+       *stream_len = len;
+       EM_DEBUG_FUNC_END();
+       return (char*) buf;
+}
+
+INTERNAL_FUNC void em_convert_byte_stream_to_mail_data(char *stream, int stream_len, email_mail_data_t *mail_data)
+{
+       EM_NULL_CHECK_FOR_VOID(stream);
+       EM_NULL_CHECK_FOR_VOID(mail_data);
+
+       tpl_node *tn = NULL;
+
+       tn = tpl_map(EMAIL_MAIL_DATA_FMT, mail_data);
+       tpl_load(tn, TPL_MEM, stream, stream_len);
+       tpl_unpack(tn, 0);
+       tpl_free(tn);
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+#define EMAIL_ATTACHMENT_DATA_FMT "A(S(" "issii" "iciii" "s" "))"
+
+INTERNAL_FUNC char* em_convert_attachment_data_to_byte_stream(email_attachment_data_t *attachment, int attachment_count, int* stream_len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_IF_NULL_RETURN_VALUE(stream_len, NULL);
+       if(!attachment) {
+               EM_DEBUG_LOG("no attachment to be included");
+               *stream_len = 0;
+               return NULL;
+       }
+
+
+       email_attachment_data_t cur = {0};
+       tpl_node *tn = NULL;
+
+       /* tpl_map adds value at 2nd param addr to packing buffer iterately */
+       /* 2nd param value (not addr via pointer) should be modified at each iteration */
+       tn = tpl_map(EMAIL_ATTACHMENT_DATA_FMT, &cur);
+       int i=0;
+       for( ; i < attachment_count ; i++ ) {
+               memcpy(&cur, attachment+i, sizeof(cur)); /* copy data to cur : swallow copy */
+               tpl_pack(tn, 1);                        /* pack data at &cur: deep copy */
+       }
+
+       /* write data to buffer */
+       void *buf = NULL;
+       size_t len = 0;
+       tpl_dump(tn, TPL_MEM, &buf, &len);
+       tpl_free(tn);
+
+       *stream_len = len;
+
+       EM_DEBUG_LOG("stream_len: %d", len);
+
+       EM_DEBUG_FUNC_END();
+       return (char*) buf;
+}
+
+INTERNAL_FUNC void em_convert_byte_stream_to_attachment_data(char *stream, int stream_len, email_attachment_data_t **attachment_data, int *attachment_count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_NULL_CHECK_FOR_VOID(stream);
+       EM_NULL_CHECK_FOR_VOID(attachment_data);
+       EM_NULL_CHECK_FOR_VOID(attachment_count);
+
+
+       email_attachment_data_t cur = {0};
+       tpl_node *tn = NULL;
+       tn = tpl_map(EMAIL_ATTACHMENT_DATA_FMT, &cur);
+       tpl_load(tn, TPL_MEM, stream, stream_len);
+
+       /* tpl does not return the size of variable-length array, but we need variable-length array */
+       /* so, make list and get list count in the first phase, */
+       /* and then copy list to var array after allocating memory */
+       GList *head = NULL;
+       int count = 0;
+       while( tpl_unpack(tn, 1) > 0) {
+               email_attachment_data_t* pdata = (email_attachment_data_t*) em_malloc(sizeof(email_attachment_data_t));
+               memcpy(pdata, &cur, sizeof(email_attachment_data_t)); /* copy unpacked data to list item */
+               head = g_list_prepend(head, pdata);                   /* add it to list */
+               memset(&cur, 0, sizeof(email_attachment_data_t));     /* initialize variable, used for unpacking */
+               count++;
+       }
+       tpl_free(tn);
+
+       /*finally we get the list count and allocate var length array */
+       email_attachment_data_t *attached = (email_attachment_data_t*) em_malloc(sizeof(email_attachment_data_t)*count);
+
+       /*write glist item into variable array*/
+       head = g_list_reverse(head);
+       GList *p = g_list_first(head);
+       int i=0;
+       for( ; p ; p = g_list_next(p), i++ ) {
+               email_attachment_data_t* pdata = (email_attachment_data_t*) g_list_nth_data(p, 0);
+               memcpy( attached+i, pdata, sizeof(email_attachment_data_t));
+               EM_SAFE_FREE(pdata);    /*now, list item is useless */
+       }
+
+       g_list_free(head);
+
+       *attachment_count = count;
+       *attachment_data = attached;
+       EM_DEBUG_FUNC_END();
+}
+
+
+#define EMAIL_MAILBOX_FMT  "S(" "isisi" "iiiii" "i" ")"
+
+INTERNAL_FUNC char* em_convert_mailbox_to_byte_stream(email_mailbox_t *mailbox_data, int *stream_len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_IF_NULL_RETURN_VALUE(mailbox_data, NULL);
+       EM_IF_NULL_RETURN_VALUE(stream_len, NULL);
+
+       tpl_node *tn = NULL;
+
+       tn = tpl_map(EMAIL_MAILBOX_FMT, mailbox_data);
+       tpl_pack(tn, 0);
+
+       /* write account to buffer */
+       void *buf = NULL;
+       size_t len = 0;
+       tpl_dump(tn, TPL_MEM, &buf, &len);
+       tpl_free(tn);
+
+       *stream_len = len;
+       EM_DEBUG_FUNC_END("serialized len: %d", len);
+       return (char*) buf;
+}
+
+
+INTERNAL_FUNC void em_convert_byte_stream_to_mailbox(char *stream, int stream_len, email_mailbox_t *mailbox_data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_NULL_CHECK_FOR_VOID(stream);
+       EM_NULL_CHECK_FOR_VOID(mailbox_data);
+
+       tpl_node *tn = NULL;
+
+       tn = tpl_map(EMAIL_MAILBOX_FMT, mailbox_data);
+       tpl_load(tn, TPL_MEM, stream, stream_len);
+       tpl_unpack(tn, 0);
+       tpl_free(tn);
+
+       EM_DEBUG_FUNC_END("deserialized len %d", stream_len);
+}
+
+#define EMAIL_OPTION_FMT "S(" "iiiii" "iisii" "iisi" ")"
+
+INTERNAL_FUNC char* em_convert_option_to_byte_stream(email_option_t* option, int* stream_len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_IF_NULL_RETURN_VALUE(option, NULL);
+       EM_IF_NULL_RETURN_VALUE(stream_len, NULL);
+
+       tpl_node *tn = NULL;
+
+       tn = tpl_map(EMAIL_OPTION_FMT, option);
+       tpl_pack(tn, 0);
+
+       /* write account to buffer */
+       void *buf = NULL;
+       size_t len = 0;
+       tpl_dump(tn, TPL_MEM, &buf, &len);
+       tpl_free(tn);
+
+       *stream_len = len;
+       EM_DEBUG_FUNC_END("serialized len: %d", len);
+       return (char*) buf;
+}
+
+INTERNAL_FUNC void em_convert_byte_stream_to_option(char *stream, int stream_len, email_option_t *option)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_NULL_CHECK_FOR_VOID(stream);
+       EM_NULL_CHECK_FOR_VOID(option);
+
+       tpl_node *tn = NULL;
+
+       tn = tpl_map(EMAIL_OPTION_FMT, option);
+       tpl_load(tn, TPL_MEM, stream, stream_len);
+       tpl_unpack(tn, 0);
+       tpl_free(tn);
+
+       EM_DEBUG_FUNC_END("deserialized len %d", stream_len);
+}
+
+
+#define EMAIL_RULE_FMT "S(" "iiisi" "iii" ")"
+
+INTERNAL_FUNC char* em_convert_rule_to_byte_stream(email_rule_t *rule, int *stream_len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_IF_NULL_RETURN_VALUE(rule, NULL);
+       EM_IF_NULL_RETURN_VALUE(stream_len, NULL);
+
+       tpl_node *tn = NULL;
+
+       tn = tpl_map(EMAIL_RULE_FMT, rule);
+       tpl_pack(tn, 0);
+
+       /* write account to buffer */
+       void *buf = NULL;
+       size_t len = 0;
+       tpl_dump(tn, TPL_MEM, &buf, &len);
+       tpl_free(tn);
+
+       *stream_len = len;
+       EM_DEBUG_FUNC_END("serialized len: %d", len);
+       return (char*) buf;
+}
+
+INTERNAL_FUNC void em_convert_byte_stream_to_rule(char *stream, int stream_len, email_rule_t *rule)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_NULL_CHECK_FOR_VOID(stream);
+       EM_NULL_CHECK_FOR_VOID(rule);
+
+       tpl_node *tn = NULL;
+
+       tn = tpl_map(EMAIL_RULE_FMT, rule);
+       tpl_load(tn, TPL_MEM, stream, stream_len);
+       tpl_unpack(tn, 0);
+       tpl_free(tn);
+
+       EM_DEBUG_FUNC_END("deserialized len %d", stream_len);
+}
+
+#define EMAIL_MEETING_REQUEST_FMT   "iiBBs" "sic#Bi" "c#Bi"
+
+INTERNAL_FUNC char* em_convert_meeting_req_to_byte_stream(email_meeting_request_t *meeting_req, int *stream_len)
+{
+
+       EM_DEBUG_FUNC_END();
+       EM_IF_NULL_RETURN_VALUE(meeting_req, NULL);
+
+       tpl_node *tn = NULL;
+       tpl_bin tb[4];
+
+       tn = tpl_map(EMAIL_MEETING_REQUEST_FMT,
+                                               &meeting_req->mail_id,
+                                               &meeting_req->meeting_response,
+                                               &tb[0],
+                                               &tb[1],
+                                               &meeting_req->location,
+                                               &meeting_req->global_object_id,
+                                               &meeting_req->time_zone.offset_from_GMT,
+                                               meeting_req->time_zone.standard_name, 32,
+                                               &tb[2],
+                                               &meeting_req->time_zone.standard_bias,
+                                               meeting_req->time_zone.daylight_name, 32,
+                                               &tb[3],
+                                               &meeting_req->time_zone.daylight_bias
+                               );
+       tb[0].sz = tb[1].sz = tb[2].sz = tb[3].sz = sizeof(struct tm);
+       tb[0].addr = &meeting_req->start_time;
+       tb[1].addr = &meeting_req->end_time;
+       tb[2].addr = &meeting_req->time_zone.standard_time_start_date;
+       tb[3].addr = &meeting_req->time_zone.daylight_time_start_date;
+
+
+       tpl_pack(tn, 0);
+
+       /* write account to buffer */
+       void *buf = NULL;
+       size_t len = 0;
+       tpl_dump(tn, TPL_MEM, &buf, &len);
+       tpl_free(tn);
+
+       *stream_len = len;
+       EM_DEBUG_FUNC_END();
+       return (char*) buf;
+}
+
+
+INTERNAL_FUNC void em_convert_byte_stream_to_meeting_req(char *stream, int stream_len, email_meeting_request_t *meeting_req)
+{
+       EM_DEBUG_FUNC_END();
+       EM_NULL_CHECK_FOR_VOID(stream);
+       EM_NULL_CHECK_FOR_VOID(meeting_req);
+
+       tpl_node *tn = NULL;
+       tpl_bin tb[4];
+
+       tn = tpl_map(EMAIL_MEETING_REQUEST_FMT,
+                                               &meeting_req->mail_id,
+                                               &meeting_req->meeting_response,
+                                               &tb[0],
+                                               &tb[1],
+                                               &meeting_req->location,
+                                               &meeting_req->global_object_id,
+                                               &meeting_req->time_zone.offset_from_GMT,
+                                               meeting_req->time_zone.standard_name, 32,
+                                               &tb[2],
+                                               &meeting_req->time_zone.standard_bias,
+                                               meeting_req->time_zone.daylight_name, 32,
+                                               &tb[3],
+                                               &meeting_req->time_zone.daylight_bias
+                               );
+       tpl_load(tn, TPL_MEM, stream, stream_len);
+       tpl_unpack(tn, 0);
+       tpl_free(tn);
+
+       /* tb will be destroyed at end of func, but tb.addr remains */
+       memcpy(&meeting_req->start_time, tb[0].addr, sizeof(struct tm));
+       memcpy(&meeting_req->end_time, tb[1].addr, sizeof(struct tm));
+       memcpy(&meeting_req->time_zone.standard_time_start_date, tb[2].addr, sizeof(struct tm));
+       memcpy(&meeting_req->time_zone.daylight_time_start_date, tb[3].addr, sizeof(struct tm));
+
+       int i=0;
+       for(i=0; i< 4 ; i++)
+               EM_SAFE_FREE(tb[i].addr);
+
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC char* em_convert_search_filter_to_byte_stream(email_search_filter_t *input_search_filter_list,
+                                                                       int input_search_filter_count, int *output_stream_size)
+{
+       EM_DEBUG_FUNC_BEGIN("input_search_filter_list [%p] input_search_filter_count [%d]", input_search_filter_list, input_search_filter_count);
+
+       char *result_stream = NULL;
+       int   stream_size   = 0;
+       int   i = 0;
+
+       EM_IF_NULL_RETURN_VALUE(input_search_filter_list, NULL);
+
+       result_stream = append_sized_data_to_stream(result_stream, &stream_size, (char*)&(input_search_filter_count), sizeof(int));
+
+       for( i = 0; i < input_search_filter_count; i++) {
+               result_stream = append_sized_data_to_stream(result_stream, &stream_size, (char*)&(input_search_filter_list->search_filter_type), sizeof(int));
+               switch(input_search_filter_list->search_filter_type) {
+                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO       :
+                       case EMAIL_SEARCH_FILTER_TYPE_UID              :
+                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER      :
+                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER     :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED   :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED    :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT      :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED     :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT     :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN       :
+                               result_stream = append_sized_data_to_stream(result_stream, &stream_size, (char*)&(input_search_filter_list->search_filter_key_value.integer_type_key_value), sizeof(int));
+                               break;
+
+                       case EMAIL_SEARCH_FILTER_TYPE_BCC              :
+                       case EMAIL_SEARCH_FILTER_TYPE_CC               :
+                       case EMAIL_SEARCH_FILTER_TYPE_FROM             :
+                       case EMAIL_SEARCH_FILTER_TYPE_KEYWORD          :
+                       case EMAIL_SEARCH_FILTER_TYPE_SUBJECT          :
+                       case EMAIL_SEARCH_FILTER_TYPE_TO               :
+                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       :
+                               result_stream = append_string_to_stream(result_stream, &stream_size, input_search_filter_list->search_filter_key_value.string_type_key_value);
+                               break;
+
+                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE :
+                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON     :
+                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE  :
+                               result_stream = append_sized_data_to_stream(result_stream, &stream_size, (char*)&(input_search_filter_list->search_filter_key_value.time_type_key_value), sizeof(struct tm));
+                               break;
+                       default :
+                               EM_DEBUG_EXCEPTION("Invalid filter type [%d]", input_search_filter_list->search_filter_type);
+                               break;
+               }
+       }
+
+       *output_stream_size = stream_size;
+
+       EM_DEBUG_FUNC_END();
+       return result_stream;
+}
+
+INTERNAL_FUNC void em_convert_byte_stream_to_search_filter(char *input_stream,
+                               email_search_filter_t **output_search_filter_list, int *output_search_filter_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_stream [%p] output_search_filter_list [%p] output_search_filter_count [%p]", input_stream, output_search_filter_list, output_search_filter_count);
+
+       int stream_offset = 0;
+       int i = 0;
+       int local_search_filter_count = 0;
+       email_search_filter_t *local_search_filter = NULL;
+
+       EM_NULL_CHECK_FOR_VOID(input_stream);
+       EM_NULL_CHECK_FOR_VOID(output_search_filter_list);
+       EM_NULL_CHECK_FOR_VOID(output_search_filter_count);
+
+       fetch_sized_data_from_stream(input_stream, &stream_offset, sizeof(int), (char*)&(local_search_filter_count));
+
+       if(local_search_filter_count == 0) {
+               EM_DEBUG_EXCEPTION("local_search_filter_count is 0.");
+               goto FINISH_OFF;
+       }
+
+       local_search_filter = em_malloc(sizeof(email_search_filter_t) * local_search_filter_count);
+
+       if(local_search_filter == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc for local_search_filter failed");
+               goto FINISH_OFF;
+       }
+
+       *output_search_filter_count = local_search_filter_count;
+
+       for( i = 0; i < local_search_filter_count; i++) {
+               fetch_sized_data_from_stream(input_stream, &stream_offset, sizeof(int), (char*)&(local_search_filter[i].search_filter_type));
+               switch(local_search_filter[i].search_filter_type) {
+                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO       :
+                       case EMAIL_SEARCH_FILTER_TYPE_UID              :
+                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER      :
+                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER     :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED   :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED    :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT      :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED     :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT     :
+                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN       :
+                               fetch_sized_data_from_stream(input_stream, &stream_offset, sizeof(int), (char*)&(local_search_filter[i].search_filter_key_value.integer_type_key_value));
+                               break;
+
+                       case EMAIL_SEARCH_FILTER_TYPE_BCC              :
+                       case EMAIL_SEARCH_FILTER_TYPE_CC               :
+                       case EMAIL_SEARCH_FILTER_TYPE_FROM             :
+                       case EMAIL_SEARCH_FILTER_TYPE_KEYWORD          :
+                       case EMAIL_SEARCH_FILTER_TYPE_SUBJECT          :
+                       case EMAIL_SEARCH_FILTER_TYPE_TO               :
+                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       :
+                               fetch_string_from_stream(input_stream, &stream_offset, &(local_search_filter[i].search_filter_key_value.string_type_key_value));
+                               break;
+
+                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE :
+                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON     :
+                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE  :
+                               fetch_sized_data_from_stream(input_stream, &stream_offset, sizeof(time_t), (char*)&(local_search_filter[i].search_filter_key_value.time_type_key_value));
+                               break;
+                       default :
+                               EM_DEBUG_EXCEPTION("Invalid filter type [%d]", local_search_filter[i].search_filter_type);
+                               break;
+               }
+       }
+
+       *output_search_filter_list = local_search_filter;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC int em_convert_certificate_tbl_to_certificate(emstorage_certificate_tbl_t *certificate_tbl, email_certificate_t **certificate, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("certficate_tbl[%p], certificate[%p]", certificate_tbl, certificate);
+
+       int err_code = EMAIL_ERROR_NONE;
+       int ret = false;
+       email_certificate_t *temp_certificate = NULL;
+
+       if (!certificate_tbl || !certificate)  {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       temp_certificate = em_malloc(sizeof(email_certificate_t)) ;
+       if (!temp_certificate) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       temp_certificate->certificate_id = certificate_tbl->certificate_id;
+       temp_certificate->issue_year = certificate_tbl->issue_year;
+       temp_certificate->issue_month = certificate_tbl->issue_month;
+       temp_certificate->issue_day = certificate_tbl->issue_day;
+       temp_certificate->expiration_year = certificate_tbl->expiration_year;
+       temp_certificate->expiration_month = certificate_tbl->expiration_month;
+       temp_certificate->expiration_day = certificate_tbl->expiration_day;
+       temp_certificate->issue_organization_name = EM_SAFE_STRDUP(certificate_tbl->issue_organization_name);
+       temp_certificate->email_address = EM_SAFE_STRDUP(certificate_tbl->email_address);
+       temp_certificate->subject_str = EM_SAFE_STRDUP(certificate_tbl->subject_str);
+       temp_certificate->filepath = EM_SAFE_STRDUP(certificate_tbl->filepath);
+
+       *certificate = temp_certificate;
+
+       ret = true;
+FINISH_OFF:
+       if (error)
+               *error = err_code;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+INTERNAL_FUNC int em_convert_certificate_to_certificate_tbl(email_certificate_t *certificate, emstorage_certificate_tbl_t *certificate_tbl)
+{
+       EM_DEBUG_FUNC_BEGIN("certficate[%p], certificate_tbl[%p]", certificate, certificate_tbl);
+
+       certificate_tbl->certificate_id = certificate->certificate_id;
+       certificate_tbl->issue_year = certificate->issue_year;
+       certificate_tbl->issue_month = certificate->issue_month;
+       certificate_tbl->issue_day = certificate->issue_day;
+       certificate_tbl->expiration_year = certificate->expiration_year;
+       certificate_tbl->expiration_month = certificate->expiration_month;
+       certificate_tbl->expiration_day = certificate->expiration_day;
+       certificate_tbl->issue_organization_name = EM_SAFE_STRDUP(certificate->issue_organization_name);
+       certificate_tbl->email_address = EM_SAFE_STRDUP(certificate->email_address);
+       certificate_tbl->subject_str = EM_SAFE_STRDUP(certificate->subject_str);
+       certificate_tbl->filepath = EM_SAFE_STRDUP(certificate->filepath);
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
diff --git a/email-common-use/email-utilities.c b/email-common-use/email-utilities.c
new file mode 100755 (executable)
index 0000000..a4b430f
--- /dev/null
@@ -0,0 +1,1124 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+/*
+ * email-utilities.c
+ *
+ *  Created on: 2012. 3. 6.
+ *      Author: kyuho.jo@samsung.com
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <errno.h>
+#include <sys/time.h>
+#include <sys/vfs.h>
+#include <unistd.h>
+#include <malloc.h>
+#include <pthread.h>
+#include <regex.h>
+
+#include "c-client.h"
+
+#include "email-types.h"
+#include "email-internal-types.h"
+#include "email-utilities.h"
+
+INTERNAL_FUNC void* em_malloc(int len)
+{
+       /* EM_DEBUG_LOG("Memory allocation size[%d] bytes", len); */
+       if (len <= 0) {
+               EM_DEBUG_EXCEPTION("len should be positive.[%d]", len);
+               return NULL;
+       }
+
+       void *p = calloc(1,len);
+       if (!p)
+               EM_DEBUG_PERROR("malloc failed");
+
+       return p;
+}
+
+
+INTERNAL_FUNC void* em_memdup(void* src, int len)
+{
+       /* EM_DEBUG_LOG("Memory allocation size[%d] bytes", len); */
+       if (len <= 0) {
+               EM_DEBUG_EXCEPTION("len should be positive.[%d]", len);
+               return NULL;
+       }
+
+       void *p = calloc(1,len);
+       if (!p) {
+               EM_DEBUG_EXCEPTION("malloc failed");
+               return NULL;
+       }
+
+       memcpy(p, src, len);
+
+       return p;
+}
+
+
+/*  remove left space, tab, CR, L */
+INTERNAL_FUNC char *em_trim_left(char *str)
+{
+       char *p, *temp_buffer = NULL;
+
+       /* EM_DEBUG_FUNC_BEGIN() */
+       if (!str) return NULL;
+
+       p = str;
+       while (*p && (*p == ' ' || *p == '\t' || *p == LF || *p == CR)) p++;
+
+       if (!*p) return NULL;
+
+       temp_buffer = EM_SAFE_STRDUP(p);
+
+       strncpy(str, temp_buffer, EM_SAFE_STRLEN(str));
+       str[EM_SAFE_STRLEN(temp_buffer)] = NULL_CHAR;
+
+       EM_SAFE_FREE(temp_buffer);
+
+       return str;
+}
+
+/*  remove right space, tab, CR, L */
+INTERNAL_FUNC char *em_trim_right(char *str)
+{
+       char *p;
+
+       /* EM_DEBUG_FUNC_BEGIN() */
+       if (!str) return NULL;
+
+       p = str+EM_SAFE_STRLEN(str)-1;
+       while (((int)p >= (int)str) && (*p == ' ' || *p == '\t' || *p == LF || *p == CR))
+               *p --= '\0';
+
+       if ((int) p < (int)str)
+               return NULL;
+
+       return str;
+}
+
+INTERNAL_FUNC char* em_upper_string(char *str)
+{
+       char *p = str;
+       while (*p)  {
+               *p = toupper(*p);
+               p++;
+       }
+       return str;
+}
+
+INTERNAL_FUNC char*  em_lower_string(char *str)
+{
+       char *p = str;
+       while (*p)  {
+               *p = tolower(*p);
+               p++;
+       }
+       return str;
+}
+
+INTERNAL_FUNC int em_upper_path(char *path)
+{
+       int i = 0, is_utf7 = 0, len = path ? (int)EM_SAFE_STRLEN(path) : -1;
+       for (; i < len; i++) {
+               if (path[i] == '&' || path[i] == 5) {
+                       is_utf7 = 1;
+               }
+               else {
+                       if (is_utf7) {
+                               if (path[i] == '-') is_utf7 = 0;
+                       }
+                       else {
+                               path[i] = toupper(path[i]);
+                       }
+               }
+       }
+
+       return 1;
+}
+
+INTERNAL_FUNC void em_skip_whitespace(char *addr_str, char **pAddr)
+{
+       EM_DEBUG_FUNC_BEGIN("addr_str[%p]", addr_str);
+
+       if (!addr_str)
+               return ;
+       char *str = addr_str;
+       char ptr[EM_SAFE_STRLEN(str)+1]  ;
+       int i, j = 0;
+
+       str = addr_str ;
+       for (i = 0; str[i] != NULL_CHAR ; i++) {
+               if (str[i] != SPACE && str[i] != TAB && str[i] != CR && str[i] != LF)
+                       ptr[j++] = str[i];
+       }
+       ptr[j] = NULL_CHAR;
+
+       *pAddr = EM_SAFE_STRDUP(ptr);
+       EM_DEBUG_FUNC_END("ptr[%s]", ptr);
+}
+
+INTERNAL_FUNC char* em_skip_whitespace_without_strdup(char *source_string)
+{
+       EM_DEBUG_FUNC_BEGIN("source_string[%p]", source_string);
+
+       if (!source_string)
+               return NULL;
+       int i;
+
+       for (i = 0; source_string[i] != NULL_CHAR ; i++) {
+               if (source_string[i] != SPACE) /*  || source_string[i] != TAB || source_string[i] != CR || source_string[i] || LF) */
+                       break;
+       }
+
+       EM_DEBUG_FUNC_END("i[%d]", i);
+       return source_string + i;
+}
+
+/*refactoring required*/
+INTERNAL_FUNC char* em_replace_all_string(char *source_string, char *old_string, char *new_string)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       char *result_buffer = NULL;
+       char *p = NULL;
+       int i = 0, count = 0;
+       int old_str_length = 0;
+       int new_str_length = 0;
+
+       EM_IF_NULL_RETURN_VALUE(source_string, NULL);
+       EM_IF_NULL_RETURN_VALUE(old_string, NULL);
+       EM_IF_NULL_RETURN_VALUE(new_string, NULL);
+
+       old_str_length = EM_SAFE_STRLEN(old_string);
+       new_str_length = EM_SAFE_STRLEN(new_string);
+
+       if (old_str_length != new_str_length) {
+               for (i = 0; source_string[i] != '\0';) {
+                       if (memcmp(&source_string[i], old_string, old_str_length) == 0) {
+                               count++;
+                               i += old_str_length;
+                       } else {
+                               i++;
+                       }
+               }
+       } else {
+               i = EM_SAFE_STRLEN(source_string);
+       }
+
+       result_buffer = (char *)malloc(i + 1 + count*(new_str_length-old_str_length));
+       if (result_buffer == NULL)
+               return NULL;
+
+       p = result_buffer;
+       while (*source_string) {
+               if (memcmp(source_string, old_string, old_str_length) == 0) {
+                       memcpy(p, new_string, new_str_length);
+                       p += new_str_length;
+                       source_string += old_str_length;
+               } else {
+                       *p++ = *source_string++;
+               }
+       }
+       *p = '\0';
+
+       EM_DEBUG_FUNC_END("result_buffer : %s", result_buffer);
+       return result_buffer;
+}
+
+INTERNAL_FUNC char* em_replace_string(char *source_string, char *old_string, char *new_string)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       char *result_buffer = NULL;
+       char *p = NULL;
+       int   buffer_length = 0;
+
+       EM_IF_NULL_RETURN_VALUE(source_string, NULL);
+       EM_IF_NULL_RETURN_VALUE(old_string, NULL);
+       EM_IF_NULL_RETURN_VALUE(new_string, NULL);
+
+       p = strstr(source_string, old_string);
+
+       if (p == NULL) {
+               EM_DEBUG_EXCEPTION("old_string not found in source_string");
+               EM_DEBUG_FUNC_END("return NULL");
+               return NULL;
+       }
+
+       buffer_length   = EM_SAFE_STRLEN(source_string) + 1024;
+       result_buffer  = (char *)em_malloc(buffer_length);
+
+       if (!result_buffer) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               return NULL;
+       }
+
+       strncpy(result_buffer, source_string, p - source_string);
+       snprintf(result_buffer + strlen(result_buffer), buffer_length - strlen(result_buffer), "%s%s", new_string, p + strlen(old_string)); /*prevent 34351*/
+
+       EM_DEBUG_FUNC_END("result_buffer[%p]", result_buffer);
+       return result_buffer;
+}
+
+/* Memory clean up */
+#include <sys/mman.h>
+
+/* #define GETSP()                             ({ unsigned int sp; asm volatile ("mov %0, sp " : "=r"(sp)); sp;}) */
+#define BUF_SIZE                               256
+#define PAGE_SIZE                          (1 << 12)
+#define _ALIGN_UP(addr, size)   (((addr)+((size)-1))&(~((size)-1)))
+#define _ALIGN_DOWN(addr, size) ((addr)&(~((size)-1)))
+#define PAGE_ALIGN(addr)        _ALIGN_DOWN(addr, PAGE_SIZE)
+
+int stack_trim(void)
+{
+       /*
+       char buf[BUF_SIZE];
+       FILE *file;
+       unsigned int stacktop;
+       int found = 0;
+       unsigned int sp;
+
+       asm volatile ("mov %0, sp " : "=r"(sp));
+
+       sprintf(buf, "/proc/%d/maps", getpid());
+       file = fopen(buf, "r");
+       while (fgets(buf, BUF_SIZE, file) != NULL) {
+               if (strstr(buf, "[stack]")) {
+                       found = 1;
+                       break;
+               }
+       }
+
+       fclose(file);
+
+       if (found) {
+               sscanf(buf, "%x-", &stacktop);
+               if (madvise((void *)PAGE_ALIGN(stacktop), PAGE_ALIGN(sp)-stacktop, MADV_DONTNEED) < 0)
+                       perror("stack madvise fail");
+       }
+       */
+       return 1;
+}
+
+INTERNAL_FUNC void em_flush_memory()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       /*  flush memory in heap */
+       malloc_trim(0);
+
+       /*  flush memory in stack */
+       stack_trim();
+
+       /*  flush memory for sqlite */
+       emstorage_flush_db_cache();
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC int em_get_file_name_from_file_path(char *input_source_file_path, char **output_file_name)
+{
+       EM_DEBUG_FUNC_BEGIN("input_source_file_path[%s], output_file_name [%p]", input_source_file_path, output_file_name);
+       int   err = EMAIL_ERROR_NONE;
+       int   pos_on_string = 0;
+       int   file_name_length = 0;
+       char *start_pos_of_file_name = NULL;
+       char *end_pos_of_file_name = NULL;
+       char *end_pos_of_file_path = NULL;
+       char  file_name_string[MAX_PATH] = { 0, };
+
+       if (!input_source_file_path || !output_file_name) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err  = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       pos_on_string        = EM_SAFE_STRLEN(input_source_file_path) - 1;
+       end_pos_of_file_path = input_source_file_path + pos_on_string;
+       end_pos_of_file_name = end_pos_of_file_path;
+
+       while(pos_on_string >= 0 && input_source_file_path[pos_on_string] != '/') {
+               pos_on_string--;
+       }
+
+       pos_on_string++;
+
+       if(pos_on_string >= 0) {
+               start_pos_of_file_name = input_source_file_path + pos_on_string;
+               file_name_length       = end_pos_of_file_name - start_pos_of_file_name + 1;
+               memcpy(file_name_string, start_pos_of_file_name, file_name_length);
+       }
+
+       EM_DEBUG_LOG("file_name_string [%s] pos_on_string [%d] file_name_length [%d]", file_name_string, pos_on_string, file_name_length);
+
+       *output_file_name = EM_SAFE_STRDUP(file_name_string);
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err = [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int em_get_file_name_and_extension_from_file_path(char *input_source_file_path, char **output_file_name, char **output_extension)
+{
+       EM_DEBUG_FUNC_BEGIN("input_source_file_path[%s], output_file_name [%p], output_extension [%p]", input_source_file_path, output_file_name, output_extension);
+       int   err = EMAIL_ERROR_NONE;
+       int   pos_on_string = 0;
+       int   file_name_length = 0;
+       int   extention_length = 0;
+       char *start_pos_of_file_name = NULL;
+       char *end_pos_of_file_name = NULL;
+       char *dot_pos_of_file_path = NULL;
+       char *end_pos_of_file_path = NULL;
+       char  file_name_string[MAX_PATH] = { 0, };
+       char  extension_string[MAX_PATH] = { 0, };
+
+       if (!input_source_file_path || !output_file_name || !output_extension) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err  = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       pos_on_string        = EM_SAFE_STRLEN(input_source_file_path) - 1;
+       end_pos_of_file_path = input_source_file_path + pos_on_string;
+       end_pos_of_file_name = end_pos_of_file_path;
+
+       while(pos_on_string >= 0 && input_source_file_path[pos_on_string] != '/') {
+               if(input_source_file_path[pos_on_string] == '.') {
+                       if(dot_pos_of_file_path == NULL) {
+                               end_pos_of_file_name = input_source_file_path + pos_on_string;
+                               dot_pos_of_file_path = end_pos_of_file_name;
+                       }
+               }
+               pos_on_string--;
+       }
+
+       pos_on_string++;
+
+       if(pos_on_string >= 0) {
+               start_pos_of_file_name = input_source_file_path + pos_on_string;
+               file_name_length       = end_pos_of_file_name - start_pos_of_file_name;
+               memcpy(file_name_string, start_pos_of_file_name, file_name_length);
+       }
+
+       if(dot_pos_of_file_path != NULL) {
+               extention_length       = (end_pos_of_file_path + 1) - (dot_pos_of_file_path + 1);
+               memcpy(extension_string, dot_pos_of_file_path + 1, extention_length);
+       }
+
+       EM_DEBUG_LOG("*file_name_string [%s] pos_on_string [%d]", file_name_string, pos_on_string);
+
+       *output_file_name = EM_SAFE_STRDUP(file_name_string);
+       *output_extension = EM_SAFE_STRDUP(extension_string);
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err = [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC char *em_get_extension_from_file_path(char *source_file_path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("source_file_path[%s]", source_file_path);
+       int err = EMAIL_ERROR_NONE, pos_on_string = 0;
+       char *extension = NULL;
+
+       if (!source_file_path) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err  = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       pos_on_string = EM_SAFE_STRLEN(source_file_path) - 1;
+
+       while(pos_on_string > 0 && source_file_path[pos_on_string--] != '.') ;
+
+       if(pos_on_string > 0)
+               extension = source_file_path + pos_on_string + 2;
+
+       EM_DEBUG_LOG("*extension [%s] pos_on_string [%d]", extension, pos_on_string);
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return extension;
+}
+
+INTERNAL_FUNC int em_get_encoding_type_from_file_path(const char *input_file_path, char **output_encoding_type)
+{
+       EM_DEBUG_FUNC_BEGIN("input_file_path[%d], output_encoding_type[%p]", input_file_path, output_encoding_type);
+       int   err = EMAIL_ERROR_NONE;
+       int   pos_of_filename = 0;
+       int   pos_of_dot = 0;
+       int   enf_of_string = 0;
+       int   result_string_length = 0;
+       char *filename = NULL;
+       char *result_encoding_type = NULL;
+
+       if (!input_file_path || !output_encoding_type) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err  = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       enf_of_string = pos_of_filename = EM_SAFE_STRLEN(input_file_path);
+
+       while(pos_of_filename >= 0 && input_file_path[pos_of_filename--] != '/') {
+               if(input_file_path[pos_of_filename] == '.')
+                       pos_of_dot = pos_of_filename;
+       }
+
+       if(pos_of_filename != 0)
+               pos_of_filename += 2;
+
+       filename = (char*)input_file_path + pos_of_filename;
+
+       if(pos_of_dot != 0 && pos_of_dot > pos_of_filename)
+               result_string_length = pos_of_dot - pos_of_filename;
+       else
+               result_string_length = enf_of_string - pos_of_filename;
+
+       EM_DEBUG_LOG("pos_of_dot [%d], pos_of_filename [%d], enf_of_string[%d],result_string_length [%d]", pos_of_dot, pos_of_filename, enf_of_string, result_string_length);
+
+       if( !(result_encoding_type =    em_malloc(sizeof(char) * (result_string_length + 1))) ) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               err  = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memcpy(result_encoding_type, input_file_path + pos_of_filename, result_string_length);
+
+       EM_DEBUG_LOG("*result_encoding_type [%s]", result_encoding_type);
+
+       *output_encoding_type = result_encoding_type;
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int em_get_content_type_from_extension_string(const char *extension_string, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("extension_string[%s]", extension_string);
+       int i = 0, err = EMAIL_ERROR_NONE, result_content_type = TYPEAPPLICATION;
+       char *image_extension[] = { "jpeg", "jpg", "png", "gif", "bmp", "pic", "agif", "tif", "wbmp" , "p7s", "p7m", NULL};
+
+       if (!extension_string) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err  = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       while(image_extension[i]) {
+               EM_DEBUG_LOG("image_extension[%d] [%s]", i, image_extension[i]);
+               if(strcasecmp(image_extension[i], extension_string) == 0) {
+                       break;
+               }
+               i++;
+       }
+
+       switch (i) {
+       case EXTENSION_JPEG:
+       case EXTENSION_JPG:
+       case EXTENSION_PNG:
+       case EXTENSION_GIF:
+       case EXTENSION_BMP:
+       case EXTENSION_PIC:
+       case EXTENSION_AGIF:
+       case EXTENSION_TIF:
+       case EXTENSION_WBMP:
+               result_content_type = TYPEIMAGE;
+               break;
+       case EXTENSION_P7S:
+               result_content_type = TYPEPKCS7_SIGN;
+               break;
+       case EXTENSION_P7M:
+               result_content_type = TYPEPKCS7_MIME;
+               break;
+       default:
+               break;
+       }
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return result_content_type;
+}
+
+#define EMAIL_ACCOUNT_RGEX                     "([a-z0-9!#$%&'*+/=?^_`{|}~-]+.)*[a-z0-9!#$%&'*+/=?^_`{|}~-]+"
+#define EMAIL_DOMAIN_RGEX                      "([a-z0-9!#$%&'*+/=?^_`{|}~-]+.)+[a-z0-9!#$%&'*+/=?^_`{|}~-]+"
+
+#define EMAIL_ADDR_RGEX                        "[[:space:]]*<"EMAIL_ACCOUNT_RGEX"@"EMAIL_DOMAIN_RGEX">[[:space:]]*"
+#define EMAIL_ALIAS_RGEX                       "([[:space:]]*\"[^\"]*\")?"EMAIL_ADDR_RGEX
+#define EMAIL_ALIAS_LIST_RGEX                  "^("EMAIL_ALIAS_RGEX"[;,])*"EMAIL_ALIAS_RGEX"[;,]?[[:space:]]*$"
+
+#define EMAIL_ADDR_WITHOUT_BRACKET_RGEX        "[[:space:]]*"EMAIL_ACCOUNT_RGEX"@"EMAIL_DOMAIN_RGEX"[[:space:]]*"
+#define EMAIL_ALIAS_WITHOUT_BRACKET_RGEX       "([[:space:]]*\"[^\"]*\")?"EMAIL_ADDR_WITHOUT_BRACKET_RGEX
+#define EMAIL_ALIAS_LIST_WITHOUT_BRACKET_RGEX  "("EMAIL_ALIAS_WITHOUT_BRACKET_RGEX"[;,])*"EMAIL_ADDR_WITHOUT_BRACKET_RGEX"[;,]?[[:space:]]*$"
+
+INTERNAL_FUNC int em_verify_email_address(char *address, int without_bracket, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("address[%s] without_bracket[%d]", address, without_bracket);
+
+       /*  this following code verfies the email alias string using reg. exp. */
+       regex_t alias_list_regex = {0};
+       int ret = false, error = EMAIL_ERROR_NONE;
+       char *reg_rule = NULL;
+
+       if(!address || EM_SAFE_STRLEN(address) == 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       if(without_bracket)
+               reg_rule = EMAIL_ALIAS_LIST_WITHOUT_BRACKET_RGEX;
+       else
+               reg_rule = EMAIL_ALIAS_LIST_RGEX;
+
+       if (regcomp(&alias_list_regex, reg_rule, REG_ICASE | REG_EXTENDED)) {
+               EM_DEBUG_EXCEPTION("email alias regex unrecognized");
+               if (err_code)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return false;
+       }
+
+       int alias_len = EM_SAFE_STRLEN(address) + 1;
+       regmatch_t pmatch[alias_len];
+
+       bzero(pmatch, alias_len);
+
+       if (regexec(&alias_list_regex, address, alias_len, pmatch, 0) == REG_NOMATCH)
+               EM_DEBUG_LOG("failed :[%s]", address);
+       else {
+               EM_DEBUG_LOG("success :[%s]", address);
+               ret = true;
+       }
+
+       regfree(&alias_list_regex);
+
+       if (err_code)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int em_verify_email_address_of_mail_data(email_mail_data_t *mail_data, int without_bracket, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_data[%p] without_bracket[%d]", mail_data, without_bracket);
+       char *address_array[4] = { mail_data->full_address_from, mail_data->full_address_to, mail_data->full_address_cc, mail_data->full_address_bcc};
+       int  ret = false, err = EMAIL_ERROR_NONE, i;
+
+       /* check for email_address validation */
+       for (i = 0; i < 4; i++) {
+               if (address_array[i] && address_array[i][0] != 0) {
+                       if (!em_verify_email_address(address_array[i] , without_bracket, &err)) {
+                               err = EMAIL_ERROR_INVALID_ADDRESS;
+                               EM_DEBUG_EXCEPTION("Invalid Email Address [%d][%s]", i, address_array[i]);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+       ret = true;
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int em_verify_email_address_of_mail_tbl(emstorage_mail_tbl_t *input_mail_tbl, int input_without_bracket)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_tbl[%p] input_without_bracket[%d]", input_mail_tbl, input_without_bracket);
+       char *address_array[4] = { input_mail_tbl->full_address_to, input_mail_tbl->full_address_cc, input_mail_tbl->full_address_bcc, input_mail_tbl->full_address_from};
+       int  err = EMAIL_ERROR_NONE, i;
+
+       /* check for email_address validation */
+       for (i = 0; i < 4; i++) {
+               if (address_array[i] && address_array[i][0] != 0) {
+                       if (!em_verify_email_address(address_array[i] , input_without_bracket, &err)) {
+                               err = EMAIL_ERROR_INVALID_ADDRESS;
+                               EM_DEBUG_EXCEPTION("Invalid Email Address [%d][%s]", i, address_array[i]);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int em_find_tag_for_thread_view(char *subject, int *result)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error_code = EMAIL_ERROR_NONE;
+       char *copy_of_subject = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(subject, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(result, EMAIL_ERROR_INVALID_PARAM);
+
+       *result = FALSE;
+
+       copy_of_subject = EM_SAFE_STRDUP(subject);
+
+       if (copy_of_subject == NULL) {
+               EM_DEBUG_EXCEPTION("strdup is failed.");
+               goto FINISH_OFF;
+       }
+
+       em_upper_string(copy_of_subject);
+       EM_DEBUG_LOG("em_upper_string result : %s\n", copy_of_subject);
+
+       if (strstr(copy_of_subject, "RE:") == NULL) {
+               if (strstr(copy_of_subject, "FWD:") == NULL) {
+                       if (strstr(copy_of_subject, "FW:") != NULL)
+                               *result = TRUE;
+               }
+               else
+                       *result = TRUE;
+       }
+       else
+               *result = TRUE;
+
+FINISH_OFF:
+       EM_SAFE_FREE(copy_of_subject);
+
+       EM_DEBUG_FUNC_END("result : %d", *result);
+
+       return error_code;
+}
+
+INTERNAL_FUNC int em_find_pos_stripped_subject_for_thread_view(char *subject, char *stripped_subject, int stripped_subject_buffer_size)
+{
+       EM_DEBUG_FUNC_BEGIN("subject [%p] stripped_subject [%p] stripped_subject_buffer_size[%d]", subject, stripped_subject, stripped_subject_buffer_size);
+       int error_code = EMAIL_ERROR_NONE;
+       int gap;
+       char *copy_of_subject = NULL, *curpos = NULL, *result;
+
+       EM_IF_NULL_RETURN_VALUE(subject, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(stripped_subject, EMAIL_ERROR_INVALID_PARAM);
+
+       copy_of_subject = EM_SAFE_STRDUP(subject);
+
+       if (copy_of_subject == NULL) {
+               EM_DEBUG_EXCEPTION("strdup is failed");
+               goto FINISH_OFF;
+       }
+
+       em_upper_string(copy_of_subject);
+       curpos = copy_of_subject;
+
+       EM_DEBUG_LOG("em_upper_string result : %s", copy_of_subject);
+
+       while ((result = strstr(curpos, "RE:")) != NULL) {
+               curpos = result + 3;
+               EM_DEBUG_LOG("RE result : %s", curpos);
+       }
+
+       while ((result = strstr(curpos, "FWD:")) != NULL) {
+               curpos = result + 4;
+               EM_DEBUG_LOG("FWD result : %s", curpos);
+       }
+
+       while ((result = strstr(curpos, "FW:")) != NULL) {
+               curpos = result + 3;
+               EM_DEBUG_LOG("FW result : %s", curpos);
+       }
+
+       while (curpos != NULL && *curpos == ' ') {
+               curpos++;
+       }
+
+       gap = curpos - copy_of_subject;
+
+       EM_SAFE_STRNCPY(stripped_subject, subject + gap, stripped_subject_buffer_size);
+
+FINISH_OFF:
+       EM_SAFE_FREE(copy_of_subject);
+
+       if (error_code == EMAIL_ERROR_NONE && stripped_subject)
+               EM_DEBUG_LOG("result[%s]", stripped_subject);
+
+       EM_DEBUG_FUNC_END("error_code[%d]", error_code);
+       return error_code;
+}
+
+
+/*
+ * encoding base64
+ */
+INTERNAL_FUNC int em_encode_base64(char *src, unsigned long src_len, char **enc, unsigned long* enc_len, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+    unsigned char *content;
+    int ret = true, err = EMAIL_ERROR_NONE;
+
+       if (err_code != NULL) {
+               *err_code = EMAIL_ERROR_NONE;
+       }
+
+    content = rfc822_binary(src, src_len, enc_len);
+
+    if (content)
+        *enc = (char *)content;
+    else {
+        err = EMAIL_ERROR_UNKNOWN;
+        ret = false;
+    }
+
+    if (err_code)
+        *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+    return ret;
+}
+
+/*
+ * decoding base64
+ */
+INTERNAL_FUNC int em_decode_base64(unsigned char *enc_text, unsigned long enc_len, char **dec_text, unsigned long* dec_len, int *err_code)
+{
+    unsigned char *text = enc_text;
+    unsigned long size = enc_len;
+    unsigned char *content;
+    int ret = true, err = EMAIL_ERROR_NONE;
+
+       if (err_code != NULL) {
+               *err_code = EMAIL_ERROR_NONE;
+       }
+
+    EM_DEBUG_FUNC_BEGIN();
+
+    content = rfc822_base64(text, size, dec_len);
+    if (content)
+        *dec_text = (char *)content;
+    else
+    {
+        err = EMAIL_ERROR_UNKNOWN;
+        ret = false;
+    }
+
+    if (err_code)
+        *err_code = err;
+
+    return ret;
+}
+
+INTERNAL_FUNC int em_get_account_server_type_by_account_id(int account_id, email_account_server_t* account_server_type, int flag, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       emstorage_account_tbl_t *account_tbl_data = NULL;
+       int ret = false;
+       int err= EMAIL_ERROR_NONE;
+
+       if (account_server_type == NULL ) {
+               EM_DEBUG_EXCEPTION("account_server_type is NULL");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               ret = false;
+               goto FINISH_OFF;
+       }
+
+       if( !emstorage_get_account_by_id(account_id, WITHOUT_OPTION, &account_tbl_data, false, &err)) {
+               EM_DEBUG_EXCEPTION ("emstorage_get_account_by_id failed [%d] ", err);
+               ret = false;
+               goto FINISH_OFF;
+       }
+
+       if ( flag == false )  { /*  sending server */
+               *account_server_type = account_tbl_data->outgoing_server_type;
+       } else if ( flag == true ) {    /*  receiving server */
+               *account_server_type = account_tbl_data->incoming_server_type;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if ( account_tbl_data != NULL ) {
+               emstorage_free_account(&account_tbl_data, 1, NULL);
+       }
+       if ( error != NULL ) {
+               *error = err;
+       }
+
+       return ret;
+}
+
+#include <vconf.h>
+#include <dbus/dbus.h>
+
+#define ACTIVE_SYNC_HANDLE_INIT_VALUE          (-1)
+#define ACTIVE_SYNC_HANDLE_BOUNDARY                    (-100000000)
+
+
+INTERNAL_FUNC int em_get_handle_for_activesync(int *handle, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       static int next_handle = 0;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if ( handle == NULL ) {
+               EM_DEBUG_EXCEPTION("em_get_handle_for_activesync failed : handle is NULL");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ( vconf_get_int(VCONFKEY_EMAIL_SERVICE_ACTIVE_SYNC_HANDLE, &next_handle)  != 0 ) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+               if ( next_handle != 0 ) {
+                       err = EMAIL_ERROR_GCONF_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       EM_DEBUG_LOG(">>>>>> VCONFKEY_EMAIL_SERVICE_ACTIVE_SYNC_HANDLE : get lastest handle[%d]", next_handle);
+
+       /*  set the value of the handle for active sync */
+       next_handle--;
+       if ( next_handle < ACTIVE_SYNC_HANDLE_BOUNDARY ) {
+               next_handle = ACTIVE_SYNC_HANDLE_INIT_VALUE;
+       }
+       if ( vconf_set_int(VCONFKEY_EMAIL_SERVICE_ACTIVE_SYNC_HANDLE, next_handle) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_set_int failed");
+               err = EMAIL_ERROR_GCONF_FAILURE;
+               goto FINISH_OFF;
+       }
+       ret = true;
+       *handle = next_handle;
+       EM_DEBUG_LOG(">>>>>> return next handle[%d]", *handle);
+
+FINISH_OFF:
+       if ( error != NULL ) {
+               *error = err;
+       }
+
+       return ret;
+}
+
+INTERNAL_FUNC int em_send_notification_to_active_sync_engine(int subType, ASNotiData *data)
+{
+       EM_DEBUG_FUNC_BEGIN("subType [%d], data [%p]", subType, data);
+
+       DBusConnection     *connection;
+       DBusMessage        *signal = NULL;
+       DBusError           error;
+       int                 i = 0;
+
+       dbus_error_init (&error);
+       connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
+
+       if(connection == NULL)
+               goto FINISH_OFF;
+
+       signal = dbus_message_new_signal("/User/Email/ActiveSync", EMAIL_ACTIVE_SYNC_NOTI, "email");
+
+       dbus_message_append_args(signal, DBUS_TYPE_INT32, &subType, DBUS_TYPE_INVALID);
+       switch ( subType ) {
+               case ACTIVE_SYNC_NOTI_SEND_MAIL:
+                       EM_DEBUG_LOG("handle:[%d]", data->send_mail.handle);
+                       EM_DEBUG_LOG("account_id:[%d]", data->send_mail.account_id);
+                       EM_DEBUG_LOG("mail_id:[%d]", data->send_mail.mail_id);
+
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.handle), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.account_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail.mail_id), DBUS_TYPE_INVALID);
+                       break;
+               case ACTIVE_SYNC_NOTI_SEND_SAVED:                               /*  publish a send notification to ASE (active sync engine) */
+                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_SEND_SAVED]", subType);
+                       break;
+               case ACTIVE_SYNC_NOTI_SEND_REPORT:
+                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_SEND_REPORT]", subType);
+                       break;
+               case ACTIVE_SYNC_NOTI_SYNC_HEADER:
+                       EM_DEBUG_LOG("handle:[%d]", data->sync_header.handle);
+                       EM_DEBUG_LOG("account_id:[%d]", data->sync_header.account_id);
+                       EM_DEBUG_LOG("mailbox_id:[%d]", data->sync_header.mailbox_id);
+
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.handle ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.account_id ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->sync_header.mailbox_id ), DBUS_TYPE_INVALID);
+                       break;
+               case ACTIVE_SYNC_NOTI_DOWNLOAD_BODY:                    /*  publish a download body notification to ASE */
+                       EM_DEBUG_LOG("handle:[%d]", data->download_body.handle);
+                       EM_DEBUG_LOG("account_id:[%d]", data->download_body.account_id);
+                       EM_DEBUG_LOG("mail_id:[%d]", data->download_body.mail_id);
+                       EM_DEBUG_LOG("with_attachment:[%d]", data->download_body.with_attachment);
+
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.handle  ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.account_id  ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.mail_id ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_body.with_attachment  ), DBUS_TYPE_INVALID);
+                       break;
+               case ACTIVE_SYNC_NOTI_DOWNLOAD_ATTACHMENT:
+                       EM_DEBUG_LOG("handle:[%d]", data->download_attachment.handle);
+                       EM_DEBUG_LOG("account_id:[%d]", data->download_attachment.account_id );
+                       EM_DEBUG_LOG("mail_id:[%d]", data->download_attachment.mail_id);
+                       EM_DEBUG_LOG("with_attachment:[%d]", data->download_attachment.attachment_order );
+
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.handle  ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.account_id  ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.mail_id ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->download_attachment.attachment_order), DBUS_TYPE_INVALID);
+                       break;
+               case ACTIVE_SYNC_NOTI_VALIDATE_ACCOUNT:
+                       EM_DEBUG_EXCEPTION("Not support yet : subType[ACTIVE_SYNC_NOTI_VALIDATE_ACCOUNT]", subType);
+                       break;
+               case ACTIVE_SYNC_NOTI_CANCEL_JOB:
+                       EM_DEBUG_LOG("account_id:[%d]",       data->cancel_job.account_id );
+                       EM_DEBUG_LOG("handle to cancel:[%d]", data->cancel_job.handle);
+                       EM_DEBUG_LOG("cancel_type:[%d]",      data->cancel_job.cancel_type);
+
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.account_id  ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.handle  ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->cancel_job.cancel_type  ), DBUS_TYPE_INVALID);
+                       break;
+               case ACTIVE_SYNC_NOTI_SEARCH_ON_SERVER:
+                       EM_DEBUG_LOG("account_id:[%d]",          data->search_mail_on_server.account_id );
+                       EM_DEBUG_LOG("mailbox_id:[%d]",        data->search_mail_on_server.mailbox_id );
+                       EM_DEBUG_LOG("search_filter_count:[%d]", data->search_mail_on_server.search_filter_count );
+                       EM_DEBUG_LOG("handle to cancel:[%d]",    data->search_mail_on_server.handle);
+
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.account_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.mailbox_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.search_filter_count), DBUS_TYPE_INVALID);
+                       for(i = 0; i < data->search_mail_on_server.search_filter_count; i++) {
+                               dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.search_filter_list[i].search_filter_type), DBUS_TYPE_INVALID);
+                               switch(data->search_mail_on_server.search_filter_list[i].search_filter_type) {
+                                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO       :
+                                       case EMAIL_SEARCH_FILTER_TYPE_UID              :
+                                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER      :
+                                       case EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER     :
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED   :
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED    :
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT      :
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED     :
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT     :
+                                       case EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN       :
+                                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.integer_type_key_value), DBUS_TYPE_INVALID);
+                                               break;
+
+                                       case EMAIL_SEARCH_FILTER_TYPE_BCC              :
+                                       case EMAIL_SEARCH_FILTER_TYPE_CC               :
+                                       case EMAIL_SEARCH_FILTER_TYPE_FROM             :
+                                       case EMAIL_SEARCH_FILTER_TYPE_KEYWORD          :
+                                       case EMAIL_SEARCH_FILTER_TYPE_SUBJECT          :
+                                       case EMAIL_SEARCH_FILTER_TYPE_TO               :
+                                       case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       :
+                                               dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.string_type_key_value), DBUS_TYPE_INVALID);
+                                               break;
+
+                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE :
+                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON     :
+                                       case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE  :
+                                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->search_mail_on_server.search_filter_list[i].search_filter_key_value.time_type_key_value), DBUS_TYPE_INVALID);
+                                               break;
+                                       default :
+                                               EM_DEBUG_EXCEPTION("Invalid filter type [%d]", data->search_mail_on_server.search_filter_list[i].search_filter_type);
+                                               break;
+                               }
+                       }
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.handle), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_CLEAR_RESULT_OF_SEARCH_ON_SERVER :
+                       EM_DEBUG_LOG("account_id:[%d]",          data->clear_result_of_search_mail_on_server.account_id );
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->search_mail_on_server.account_id), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_EXPUNGE_MAILS_DELETED_FLAGGED :
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.mailbox_id  ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.on_server  ), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->expunge_mails_deleted_flagged.handle  ), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_RESOLVE_RECIPIENT :
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->get_resolve_recipients.account_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->get_resolve_recipients.email_address), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->get_resolve_recipients.handle), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_VALIDATE_CERTIFICATE :
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->validate_certificate.account_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->validate_certificate.email_address), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->validate_certificate.handle), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_ADD_MAILBOX :
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->add_mailbox.account_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->add_mailbox.mailbox_path), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->add_mailbox.mailbox_alias), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->add_mailbox.handle), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_RENAME_MAILBOX :
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.account_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.mailbox_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->rename_mailbox.mailbox_name), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &(data->rename_mailbox.mailbox_alias), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->rename_mailbox.handle), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_DELETE_MAILBOX :
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.account_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.mailbox_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox.handle), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_DELETE_MAILBOX_EX :
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.account_id), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.mailbox_id_count), DBUS_TYPE_INVALID);
+                       for(i = 0; i <data->delete_mailbox_ex.mailbox_id_count; i++)
+                               dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->delete_mailbox_ex.mailbox_id_array[i]), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32,  &(data->delete_mailbox_ex.handle), DBUS_TYPE_INVALID);
+                       break;
+
+               case ACTIVE_SYNC_NOTI_SEND_MAIL_WITH_DOWNLOADING_OF_ORIGINAL_MAIL:
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail_with_downloading_attachment_of_original_mail.handle), DBUS_TYPE_INVALID);
+                       dbus_message_append_args(signal, DBUS_TYPE_INT32, &(data->send_mail_with_downloading_attachment_of_original_mail.mail_id), DBUS_TYPE_INVALID);
+                       break;
+
+               default:
+                       EM_DEBUG_EXCEPTION("Invalid Notification type of Active Sync : subType[%d]", subType);
+                       return FAILURE;
+       }
+
+       if(!dbus_connection_send (connection, signal, NULL)) {
+               EM_DEBUG_EXCEPTION("dbus_connection_send is failed");
+               return FAILURE;
+       } else
+               EM_DEBUG_LOG("dbus_connection_send is successful");
+
+       dbus_connection_flush(connection);
+
+FINISH_OFF:
+
+       if(signal)
+               dbus_message_unref(signal);
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
diff --git a/email-common-use/include/email-convert.h b/email-common-use/include/email-convert.h
new file mode 100755 (executable)
index 0000000..cb345fd
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 __EMAIL_CONVERT_H__
+#define __EMAIL_CONVERT_H__
+
+#include <time.h>
+#include "email-internal-types.h"
+#include "email-debug-log.h"
+#include "email-storage.h"
+
+/* Account */
+INTERNAL_FUNC char* em_convert_account_to_byte_stream(email_account_t* account, int* stream_len);
+INTERNAL_FUNC void  em_convert_byte_stream_to_account(char* stream,  int stream_len, email_account_t* account);
+INTERNAL_FUNC int   em_convert_account_to_account_tbl(email_account_t *account, emstorage_account_tbl_t *account_tbl);
+INTERNAL_FUNC int   em_convert_account_tbl_to_account(emstorage_account_tbl_t *account_tbl, email_account_t *account);
+
+
+/* Mail */
+INTERNAL_FUNC char* em_convert_mail_data_to_byte_stream(email_mail_data_t *mail_data, int *stream_size);
+INTERNAL_FUNC void  em_convert_byte_stream_to_mail_data(char *stream, int stream_len, email_mail_data_t *mail_data);
+
+INTERNAL_FUNC int   em_convert_mail_tbl_to_mail_data(emstorage_mail_tbl_t *mail_table_data, int item_count, email_mail_data_t **mail_data, int *error);
+INTERNAL_FUNC int   em_convert_mail_data_to_mail_tbl(email_mail_data_t *mail_data, int item_count, emstorage_mail_tbl_t **mail_table_data, int *error);
+
+/* Attachment */
+INTERNAL_FUNC char* em_convert_attachment_data_to_byte_stream(email_attachment_data_t *attachment_data, int attachment_count, int* stream_len);
+INTERNAL_FUNC void  em_convert_byte_stream_to_attachment_data(char *stream, int stream_len, email_attachment_data_t **attachment_data, int *attachment_count);
+
+/* Mailbox */
+INTERNAL_FUNC int   em_convert_mailbox_to_mailbox_tbl(email_mailbox_t *mailbox, emstorage_mailbox_tbl_t *mailbox_tbl);
+INTERNAL_FUNC int   em_convert_mailbox_tbl_to_mailbox(emstorage_mailbox_tbl_t *mailbox_tbl, email_mailbox_t *mailbox);
+
+
+INTERNAL_FUNC char* em_convert_mailbox_to_byte_stream(email_mailbox_t* mailbox, int* stream_len);
+INTERNAL_FUNC void  em_convert_byte_stream_to_mailbox(char* stream, int stream_len, email_mailbox_t* mailbox);
+
+/* Rule */
+INTERNAL_FUNC char* em_convert_rule_to_byte_stream(email_rule_t* rule, int* stream_len);
+INTERNAL_FUNC void  em_convert_byte_stream_to_rule(char *stream, int stream_len, email_rule_t *rule);
+
+/* Sending options */
+INTERNAL_FUNC char* em_convert_option_to_byte_stream(email_option_t* option, int* stream_len);
+INTERNAL_FUNC void em_convert_byte_stream_to_option(char *stream, int stream_len, email_option_t *option);
+
+/* time_t */
+INTERNAL_FUNC int   em_convert_string_to_time_t(char *input_datetime_string, time_t *output_time);
+INTERNAL_FUNC int   em_convert_time_t_to_string(time_t *input_time, char **output_datetime_string);
+
+/* email_meeting_request_t */
+INTERNAL_FUNC char* em_convert_meeting_req_to_byte_stream(email_meeting_request_t* meeting_req, int* nStreamSize);
+INTERNAL_FUNC void  em_convert_byte_stream_to_meeting_req(char* stream, int stream_len, email_meeting_request_t* meeting_req);
+
+INTERNAL_FUNC int   em_convert_mail_status_to_mail_tbl(int mail_status, emstorage_mail_tbl_t *result_mail_tbl_data, int* err_code);
+INTERNAL_FUNC int   em_convert_mail_tbl_to_mail_status(emstorage_mail_tbl_t *mail_tbl_data, int *result_mail_status, int* err_code);
+
+/* Search filter options */
+INTERNAL_FUNC char* em_convert_search_filter_to_byte_stream(email_search_filter_t *input_search_filter_list, int input_search_filter_count, int *output_stream_size);
+INTERNAL_FUNC void  em_convert_byte_stream_to_search_filter(char *input_stream, email_search_filter_t **output_search_filter_list, int *output_search_filter_count);
+
+/* convert certificate */
+INTERNAL_FUNC int em_convert_certificate_tbl_to_certificate(emstorage_certificate_tbl_t *certificate_tbl, email_certificate_t **certificate, int *error);
+
+INTERNAL_FUNC int em_convert_certificate_to_certificate_tbl(email_certificate_t *certificate, emstorage_certificate_tbl_t *certificate_tbl);
+
+#endif /* __EMAIL_CONVERT_H__ */
diff --git a/email-common-use/include/email-debug-log.h b/email-common-use/include/email-debug-log.h
new file mode 100755 (executable)
index 0000000..b568293
--- /dev/null
@@ -0,0 +1,244 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File: email-debug-log.h
+ * Desc: email-common-use debug header
+ *
+ * Auth:
+ *
+ * History:
+ *    2006.08.01 : created
+ *****************************************************************************/
+#ifndef __EMAIL_DEBUG_LOG_H__
+#define __EMAIL_DEBUG_LOG_H__
+
+#ifdef  __cplusplus
+extern "C"
+{
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <dlog.h>
+#include <errno.h>
+
+#define __FEATURE_DEBUG_LOG__
+
+#ifdef  __FEATURE_DEBUG_LOG__
+
+/* definition of LOG_TAG */
+#ifdef LOG_TAG
+#undef LOG_TAG
+#endif
+
+#define LOG_TAG "EMAIL_SERVICE"
+
+#define        EM_DEBUG_LOG(format, arg...)        SLOGD(format, ##arg)
+#define        EM_DEBUG_EXCEPTION(format, arg...)  SLOGE("[EXCEPTION!] " format "\n", ##arg)
+#ifdef  _DEBUG_MIME_PARSE_
+#define EM_DEBUG_LOG_MIME(format, arg...)   EM_DEBUG_LOG(format, ##arg)
+#else   /*  _DEBUG_MIME_PARSE */
+#define EM_DEBUG_LOG_MIME(format, arg...)
+#endif /*  _DEBUG_MIME_PARSE */
+
+#define        EM_DEBUG_FUNC_BEGIN(format, arg...) EM_DEBUG_LOG("BEGIN - "format, ##arg)
+#define        EM_DEBUG_FUNC_END(format, arg...)   EM_DEBUG_LOG("END - "format, ##arg)
+#define        EM_DEBUG_LINE                       EM_DEBUG_LOG("FUNC[%s : %d]", __FUNCTION__, __LINE__)
+#define EM_DEBUG_DB_EXEC(eval, expr, X)     if (eval) { EM_DEBUG_LOG X; expr;} else {;}
+
+#define EM_DEBUG_ERROR_FILE_PATH            "/opt/usr/data/email/.email_data/.critical_error.log"
+#define EM_DEBUG_CRITICAL_EXCEPTION(format, arg...)   \
+                       {\
+                               FILE *fp_error = NULL;\
+                               fp_error = fopen(EM_DEBUG_ERROR_FILE_PATH, "a");\
+                               if(fp_error) {\
+                                       fprintf(fp_error, "[%s() :%s:%d] " format "\n", \
+                                               __FUNCTION__, (rindex(__FILE__, '/')? rindex(__FILE__,'/')+1 : __FILE__ ),\
+                                               __LINE__, ##arg); \
+                                       fclose(fp_error);\
+                               }\
+                       }
+#define EM_DEBUG_PERROR(str)   ({\
+               char buf[128] = {0};\
+               strerror_r(errno, buf, sizeof(buf));\
+               EM_DEBUG_EXCEPTION("%s: %s(%d)", str, buf, errno);\
+       })
+
+#define EM_VALIDATION_SYSTEM_LOG(CLASSIFICATION, MAIL_ID, FORMAT, ARG...) {char now_time_string[30] = {0,}; \
+               time_t now = time(NULL); \
+               strftime(now_time_string, 20, "%Y.%m.%d %H:%M:%S", localtime(&now)); \
+               LOG(LOG_VERBOSE, "VLD_EMAIL", "[Email " CLASSIFICATION "]%s, %d," FORMAT "\n", now_time_string, MAIL_ID, ##ARG);}
+
+#ifdef _USE_PROFILE_DEBUG_
+#define EM_PROFILE_BEGIN(pfid) \
+       unsigned int __prf_l1_##pfid = __LINE__;\
+       struct timeval __prf_1_##pfid;\
+       struct timeval __prf_2_##pfid;\
+       do {\
+               gettimeofday(&__prf_1_##pfid, 0);\
+               EM_DEBUG_LOG("**PROFILE BEGIN** [EMAILFW: %s() :%s %u ~ ] " #pfid \
+               " ->  Start Time: %u.%06u seconds\n",\
+                       __FUNCTION__,\
+               rindex(__FILE__,'/')+1, \
+               __prf_l1_##pfid,\
+               (unsigned int)__prf_1_##pfid.tv_sec,\
+               (unsigned int)__prf_1_##pfid.tv_usec );\
+       } while (0)
+
+#define EM_PROFILE_END(pfid) \
+       unsigned int __prf_l2_##pfid = __LINE__;\
+       do { \
+               gettimeofday(&__prf_2_##pfid, 0);\
+               long __ds = __prf_2_##pfid.tv_sec - __prf_1_##pfid.tv_sec;\
+               long __dm = __prf_2_##pfid.tv_usec - __prf_1_##pfid.tv_usec;\
+               if ( __dm < 0 ) { __ds--; __dm = 1000000 + __dm; } \
+               EM_DEBUG_LOG("**PROFILE END** [EMAILFW: %s() :%s %u ~ %u] " #pfid                            \
+               " -> Elapsed Time: %u.%06u seconds\n",\
+                       __FUNCTION__,\
+               rindex(__FILE__, '/')+1,\
+               __prf_l1_##pfid,\
+               __prf_l2_##pfid,\
+               (unsigned int)(__ds),\
+               (unsigned int)(__dm));\
+       } while (0)
+#else
+
+#define EM_PROFILE_BEGIN(pfid)
+#define EM_PROFILE_END(pfid)
+
+#endif
+
+
+#else /* __FEATURE_DEBUG_LOG__ */
+
+       #define EM_DEBUG_LINE
+       #define EM_DEBUG_LOG(format, arg...)
+       #define EM_DEBUG_ASSERT(format, arg...)
+       #define EM_DEBUG_EXCEPTION(format, arg...)
+
+
+       #define EM_DEBUG_DB_EXEC(eval, expr, X)  if (eval) { EM_DEBUG_DB X; expr;} else {;}
+       #define EM_PROFILE_BEGIN(pfid)
+       #define EM_PROFILE_END(pfid)
+
+#endif /* __FEATURE_DEBUG_LOG__ */
+
+
+#define EM_NULL_CHECK_FOR_VOID(expr)   \
+       {\
+               if (!expr) {\
+                       EM_DEBUG_EXCEPTION ("INVALID PARAM: "#expr" NULL ");\
+                       return;\
+               }\
+       }
+
+#define EM_IF_NULL_RETURN_VALUE(expr, val) \
+       {\
+               if (!expr ) {\
+                       EM_DEBUG_EXCEPTION ("INVALID PARAM: "#expr" NULL ");\
+                       return val;     \
+               }\
+       }
+
+#define EM_RETURN_ERR_CODE(err_ptr, err_code, ret) \
+       {\
+               if(err_ptr) *err_ptr = err_code;\
+               return ret;\
+       }
+
+#define EM_EXIT_ERR_CODE(err_ptr, err_code) \
+       {\
+               if(err_ptr) *err_ptr = err_code;\
+               return;\
+       }
+
+
+#define EM_SAFE_FREE(expr)      \
+       ({\
+               if (expr ) {\
+                       free(expr);\
+                       expr = NULL;\
+               }\
+       })
+
+#define EM_SAFE_STRDUP(s) \
+       ({\
+               char* _s = (char*)s;\
+               (_s)? strdup(_s) : NULL;\
+       })
+
+#define EM_SAFE_STRCMP(dest, src) \
+       ({\
+               char* _dest = dest;\
+               char* _src = src;\
+               ((_src) && (_dest))? strcmp(_dest, _src) : -1;\
+       })
+
+#define EM_SAFE_STRCPY(dest, src) \
+       ({\
+               char* _dest = dest;\
+               char* _src = src;\
+               ((_src) && (_dest))? strcpy(_dest, _src) : NULL;\
+       })
+
+#define EM_SAFE_STRNCPY(dest, src, size) \
+       ({\
+               char* _dest = dest;\
+               char* _src = src;\
+               int _size = size;\
+               ((_src) && (_dest))? strncpy(_dest, _src, _size) : NULL;\
+       })
+
+#define EM_SAFE_STRCAT(dest, src) \
+       ({\
+               char* _dest = dest;\
+               char* _src = src;\
+               ((_src) && (_dest))? strcat(_dest, _src) : NULL;\
+       })
+
+#define EM_SAFE_STRLEN(s) \
+       ({\
+               char* _s = (char*)s;\
+               (_s)? strlen(_s) : 0;\
+       })
+
+
+#define EM_IF_ACCOUNT_ID_NULL(expr, ret) {\
+               if (expr <= 0) {\
+                       EM_DEBUG_EXCEPTION ("EM_IF_ACCOUNT_ID_NULL: Account ID [ %d ]  ", expr);\
+                       return ret;\
+               }\
+       }
+
+
+#define EM_STRERROR(err) ({ char buf[128]; strerror_r(err, buf, sizeof(buf));})
+
+
+#ifdef  __cplusplus
+}
+#endif /* __cplusplu */
+
+#endif /* __EMAIL_DEBUG_LOG_H__ */
diff --git a/email-common-use/include/email-errors.h b/email-common-use/include/email-errors.h
new file mode 100755 (executable)
index 0000000..4499c09
--- /dev/null
@@ -0,0 +1,195 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_ERRORS_H__
+#define __EMAIL_ERRORS_H__
+
+/*****************************************************************************/
+/*  Errors                                                                   */
+/*****************************************************************************/
+#define EMAIL_ERROR_NONE                                 1       /*  There is no error */
+
+/* Error codes for invalid input */
+#define EMAIL_ERROR_INVALID_PARAM                       -1001    /*  invalid parameter was given. - Invalid input parameter */
+#define EMAIL_ERROR_INVALID_ACCOUNT                     -1002    /*  invalid account information was given. - Unsupported account */
+#define EMAIL_ERROR_INVALID_SERVER                      -1005    /*  invalid server information was given. - Server unavailable */
+#define EMAIL_ERROR_INVALID_MAIL                        -1006    /*  invalid mail information was given */
+#define EMAIL_ERROR_INVALID_ADDRESS                     -1007    /*  invalid address information was given. - Incorrect address */
+#define EMAIL_ERROR_INVALID_ATTACHMENT                  -1008    /*  invalid attachment information was given */
+#define EMAIL_ERROR_INVALID_MAILBOX                     -1009    /*  invalid mailbox information was given */
+#define EMAIL_ERROR_INVALID_FILTER                      -1010    /*  invalid filter information was given */
+#define EMAIL_ERROR_INVALID_DATA                        -1012    /*  invalid data */
+#define EMAIL_ERROR_INVALID_RESPONSE                    -1013    /*  unexpected network response was given. - Invalid server response */
+#define EMAIL_ERROR_NO_RECIPIENT                        -1062    /*  no recipients information was found */
+#define EMAIL_ERROR_INVALID_FILE_PATH                   -4101    /*  invalid file path was given */
+#define EMAIL_ERROR_INVALID_REFERENCE_MAIL              -4102    /*  invalid reference mail was given */
+
+/* Error codes for missing data */
+#define EMAIL_ERROR_ACCOUNT_NOT_FOUND                   -1014    /*  no matched account was found */
+#define EMAIL_ERROR_MAIL_NOT_FOUND                      -1015    /*  no matched mail was found */
+#define EMAIL_ERROR_MAILBOX_NOT_FOUND                   -1016    /*  no matched mailbox was found */
+#define EMAIL_ERROR_ATTACHMENT_NOT_FOUND                -1017    /*  no matched attachment was found */
+#define EMAIL_ERROR_FILTER_NOT_FOUND                    -1018    /*  no matched filter was found */
+#define EMAIL_ERROR_CONTACT_NOT_FOUND                   -1019    /*  no matched contact was found */
+#define EMAIL_ERROR_FILE_NOT_FOUND                      -1020    /*  no matched file was found */
+#define EMAIL_ERROR_DATA_NOT_FOUND                      -1021    /*  no matched data was found */
+#define EMAIL_ERROR_TASK_BINDER_NOT_FOUND               -1023    /*  no matched task binder was found */
+#define EMAIL_ERROR_TASK_NOT_FOUND                      -1168    /*  no matched task was found */
+#define EMAIL_ERROR_HANDLE_NOT_FOUND                    -1301
+
+/* Error codes for specification for maximum data */
+#define EMAIL_ERROR_NO_MORE_DATA                        -1022    /*  No more data available */
+#define EMAIL_ERROR_MAX_EXCEEDED                        -1024    /*  Can't handle more data */
+#define EMAIL_ERROR_OUT_OF_MEMORY                       -1028    /*  There is not enough memory */
+#define EMAIL_ERROR_ACCOUNT_MAX_COUNT                   -1053    /*  There is too many account */
+#define EMAIL_ERROR_MAIL_MEMORY_FULL                    -1054    /*  There is no more storage */
+#define EMAIL_ERROR_DATA_TOO_LONG                       -1025    /*  Data is too long */
+#define EMAIL_ERROR_MAXIMUM_DEVICES_LIMIT_REACHED       -1530    /*  EAS - Maximum devices limit reached */
+
+/* Error codes for storage */
+#define EMAIL_ERROR_DB_FAILURE                          -1029    /*  database operation failed */
+#define EMAIL_ERROR_SECURED_STORAGE_FAILURE             -2100    /*  Error from secured storage */
+#define EMAIL_ERROR_GCONF_FAILURE                       -1058    /*  The error occurred on accessing Gconf */
+
+/* Error codes for network */
+#define EMAIL_ERROR_SOCKET_FAILURE                      -1031    /*  socket operation failed */
+#define EMAIL_ERROR_CONNECTION_FAILURE                  -1032    /*  network connection failed */
+#define EMAIL_ERROR_CONNECTION_BROKEN                   -1033    /*  network connection was broken */
+#define EMAIL_ERROR_NO_SUCH_HOST                        -1059    /*  no such host was found */
+#define EMAIL_ERROR_NETWORK_NOT_AVAILABLE               -1800    /*  WIFI not available*/
+#define EMAIL_ERROR_INVALID_STREAM                      -1068
+
+/* Error codes for SSL/TLS */
+#define EMAIL_ERROR_STARTLS                             -1401    /*  "STARTLS" */
+#define EMAIL_ERROR_TLS_NOT_SUPPORTED                   -1040    /*  The server doesn't support TLS */
+#define EMAIL_ERROR_TLS_SSL_FAILURE                     -1041    /*  The agent failed TLS/SSL */
+#define EMAIL_ERROR_CANNOT_NEGOTIATE_TLS                -1400    /*  "Cannot negotiate TLS" */
+
+#define EMAIL_ERROR_NO_RESPONSE                         -1036    /*  There is no server response */
+
+/* Error codes for authentication */
+#define EMAIL_ERROR_AUTH_NOT_SUPPORTED                  -1038    /*  The server doesn't support authentication */
+#define EMAIL_ERROR_AUTHENTICATE                        -1039    /*  The server failed to authenticate user */
+#define EMAIL_ERROR_AUTH_REQUIRED                       -1069    /*  SMTP Authentication needed */
+#define EMAIL_ERROR_LOGIN_FAILURE                       -1035    /*  login failed */
+#define EMAIL_ERROR_LOGIN_ALLOWED_EVERY_15_MINS         -1600    /*  "login allowed only every 15 minutes" */
+#define EMAIL_ERROR_TOO_MANY_LOGIN_FAILURE              -1601    /*  "Too many login failure" */
+
+/* Error codes for functionality */
+#define EMAIL_ERROR_NOT_IMPLEMENTED                     -1047    /*  The function is not implemented yet*/
+#define EMAIL_ERROR_NOT_SUPPORTED                       -1048    /*  The function is not supported */
+
+/* Error codes for from system */
+#define EMAIL_ERROR_NO_SIM_INSERTED                     -1205
+#define EMAIL_ERROR_BADGE_API_FAILED                    -3004
+
+/* Error codes for event handling */
+#define EMAIL_ERROR_EVENT_QUEUE_FULL                    -1060    /*  event queue is full */
+#define EMAIL_ERROR_EVENT_QUEUE_EMPTY                   -1061    /*  event queue is empty */
+#define EMAIL_ERROR_SESSION_NOT_FOUND                   -1067    /*  no matched session was found */
+#define EMAIL_ERROR_CANNOT_STOP_THREAD                  -2000
+#define EMAIL_ERROR_CANCELLED                           -1046    /*  The job was canceled by user */
+#define EMAIL_NO_AVAILABLE_TASK_SLOT                    -2656    /*  There is no available task slot */
+
+/* Error codes for IPC*/
+#define EMAIL_ERROR_IPC_CRASH                           -1500
+#define EMAIL_ERROR_IPC_CONNECTION_FAILURE              -1501
+#define EMAIL_ERROR_IPC_SOCKET_FAILURE                  -1502
+#define EMAIL_ERROR_IPC_PROTOCOL_FAILURE                -1503
+#define EMAIL_ERROR_IPC_ALREADY_INITIALIZED             -1504
+#define EMAIL_ERROR_ACTIVE_SYNC_NOTI_FAILURE            -1300
+
+/* Error codes for error from server */
+#define EMAIL_ERROR_COMMAND_NOT_SUPPORTED               -1043    /* The server doesn't support this command */
+#define EMAIL_ERROR_ANNONYM_NOT_SUPPORTED               -1044    /* The server doesn't support anonymous user */
+#define EMAIL_ERROR_SCAN_NOT_SUPPORTED                  -1037    /* The server doesn't support 'scan mailbox' */
+
+#define EMAIL_ERROR_SMTP_SEND_FAILURE                   -1063    /* SMTP send failed */
+
+#define EMAIL_ERROR_POP3_DELE_FAILURE                   -1100    /* Failed to run the command 'Dele' on POP server */
+#define EMAIL_ERROR_POP3_UIDL_FAILURE                   -1101    /* Failed to run the command 'Uidl' on POP server */
+#define EMAIL_ERROR_POP3_LIST_FAILURE                   -1102    /* Failed to run the command 'List' on POP server */
+
+#define EMAIL_ERROR_IMAP4_APPEND_FAILURE                -1042    /* Failed to run the command 'Append' on IMAP server */
+#define EMAIL_ERROR_IMAP4_STORE_FAILURE                 -1200    /* Failed to run the command 'Store' on IMAP server */
+#define EMAIL_ERROR_IMAP4_EXPUNGE_FAILURE               -1201    /* Failed to run the command 'Expunge' on IMAP server */
+#define EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE             -1202    /* Failed to run the command 'Fetch UID' on IMAP server */
+#define EMAIL_ERROR_IMAP4_FETCH_SIZE_FAILURE            -1203    /* Failed to run the command 'Fetch SIZE' on IMAP server */
+#define EMAIL_ERROR_IMAP4_IDLE_FAILURE                  -1204    /* Failed to run the command 'Idle' on IMAP server */
+#define EMAIL_ERROR_IMAP4_CREATE_FAILURE                -1210    /* Failed to run the command 'Create' on IMAP server */
+#define EMAIL_ERROR_IMAP4_DELETE_FAILURE                -1211    /* Failed to run the command 'Delete' on IMAP server */
+#define EMAIL_ERROR_IMAP4_RENAME_FAILURE                -1212    /* Failed to run the command 'Rename' on IMAP server */
+
+#define EMAIL_ERROR_INVALID_ATTACHMENT_SAVE_NAME        -1301
+
+/* Error codes for certificate */
+#define EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE            -3001    /*  Cannot load the certificate */
+#define EMAIL_ERROR_INVALID_CERTIFICATE                 -3002    /*  invalid certificate */
+#define EMAIL_ERROR_DECRYPT_FAILED                      -3003    /*  Cannot decipher the encrypt mail */
+#define EMAIL_ERROR_CERTIFICATE_FAILURE                 -1045    /*  certificate failure - Invalid server certificate */
+
+/* Error codes for account */
+#define EMAIL_ERROR_ACCOUNT_IS_QUARANTINED              -5001
+#define EMAIL_ERROR_ACCOUNT_IS_BLOCKED                  -5002
+
+/* Error codes for mails */
+#define EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER            -1055    /*  The expected mail is not found in server */
+#define EMAIL_ERROR_MAIL_IS_NOT_DOWNLOADED              -1095    /*  The mail is not downloaded */
+
+/* Error codes for attachment */
+#define EMAIL_ERROR_ATTACHMENT_SIZE_EXCEED_POLICY_LIMIT -7001
+
+/* Etc */
+#define EMAIL_ERROR_ALREADY_INITIALIZED                 -7321
+#define EMAIL_ERROR_NOT_INITIALIZED                     -7322
+#define EMAIL_ERROR_UNKNOWN                             -8000    /*  unknown error */
+
+/* Should be replaced with proper name */
+#define EMAIL_ERROR_LOAD_ENGINE_FAILURE                 -1056    /*  loading engine failed */
+#define EMAIL_ERROR_CLOSE_FAILURE                       -1057    /*  engine is still used */
+#define EMAIL_ERROR_NULL_VALUE                          -1302
+#define EMAIL_ERROR_EMPTY_FILE                          -1304
+
+/* Should be classified */
+#define EMAIL_ERROR_SYSTEM_FAILURE                      -1050    /*  There is a system error */
+#define EMAIL_ERROR_ON_PARSING                          -1700
+#define EMAIL_ERROR_ALREADY_EXISTS                      -1023    /*  data duplicated */
+
+/* Not used */
+#define EMAIL_ERROR_INVALID_USER                        -1003    /*  invalid user ID was given. - Invalid user or password */
+#define EMAIL_ERROR_INVALID_PASSWORD                    -1004    /*  invalid password was given. - Invalid user or password */
+#define EMAIL_ERROR_INVALID_PATH                        -1011    /*  invalid flle path was given */
+#define EMAIL_ERROR_MAIL_MAX_COUNT                      -1052    /*  The mailbox is full */
+#define EMAIL_ERROR_DATA_TOO_SMALL                      -1026    /*  Data is too small */
+#define EMAIL_ERROR_PROFILE_FAILURE                     -1030    /*  no proper profile was found */
+#define EMAIL_ERROR_NO_MMC_INSERTED                     -1209
+#define EMAIL_ERROR_VALIDATE_ACCOUNT                    -1208
+#define EMAIL_ERROR_NETWORK_TOO_BUSY                    -1027    /*  Network is busy */
+#define EMAIL_ERROR_DISCONNECTED                        -1034    /*  connection was disconnected */
+#define EMAIL_ERROR_MAIL_LOCKED                         -1049    /*  The mail was locked */
+#define EMAIL_ERROR_RETRIEVE_HEADER_DATA_FAILURE        -1065    /*  retrieving header failed */
+#define EMAIL_ERROR_MAILBOX_OPEN_FAILURE                -1064    /*  accessing mailbox failed */
+#define EMAIL_ERROR_XML_PARSER_FAILURE                  -1066    /*  XML parsing failed */
+#define EMAIL_ERROR_FAILED_BY_SECURITY_POLICY           -1303
+#define EMAIL_ERROR_FLIGHT_MODE                         -1206
+
+#endif /* __EMAIL_ERRORS_H__ */
diff --git a/email-common-use/include/email-internal-types.h b/email-common-use/include/email-internal-types.h
new file mode 100755 (executable)
index 0000000..8ab5945
--- /dev/null
@@ -0,0 +1,399 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-internal-types.h
+ * Desc :  defines data structures and macros
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2011.04.05  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_INTERNAL_TYPES_H__
+#define __EMAIL_INTERNAL_TYPES_H__
+
+#include "email-types.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /*  __cplusplus */
+
+#ifndef INTERNAL_FUNC
+#define INTERNAL_FUNC __attribute__((visibility("default")))
+#endif
+
+/* ----------------------------------------------------------------------------- */
+/*  Feature definitions */
+#define __FEATURE_USING_ACCOUNT_SVC__
+#define __FEATURE_BACKUP_ACCOUNT__
+#define __FEATURE_MOVE_TO_OUTBOX_FIRST__
+/*  #define __FEATURE_PARTIAL_BODY_FOR_POP3__ */
+/*  #define __FEATURE_KEEP_CONNECTION__  */
+/*  #define __FEATURE_DRM__ */
+#define __FEATURE_PARTIAL_BODY_DOWNLOAD__
+#define __FEATURE_HEADER_OPTIMIZATION__
+#define __FEATURE_SEND_OPTMIZATION__
+#define __FEATURE_DOWNLOAD_BODY_ATTACHMENT_OPTIMIZATION__
+#define __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+#define __FEATURE_SYNC_CLIENT_TO_SERVER__
+#define __FEATURE_AUTO_POLLING__
+#define __FEATURE_DEBUG_LOG__
+#define __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__
+#define __FEATURE_XLIST_SUPPORT__
+#define __FEATURE_SUPPORT_REPORT_MAIL__
+#define __FEATURE_SUPPORT_IMAP_ID__
+#define __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__
+#define __FEATURE_SUPPORT_VALIDATION_SYSTEM__
+#define __FEATURE_PROGRESS_IN_OUTBOX__
+/*  #define __FEATURE_USE_SHARED_MUTEX_FOR_PROTECTED_FUNC_CALL__ */
+/*  #define __FEATURE_IMAP_IDLE__ */
+
+
+/* ----------------------------------------------------------------------------- */
+/*  Macro */
+#ifndef NULL
+#define NULL (char *)0
+#endif
+
+#define SESSION_MAX                            5
+#define        IMAP_2004_LOG                       1
+#define TEXT_SIZE                           161 
+#define MAILBOX_COUNT                       6
+#define PARTIAL_DOWNLOAD_SIZE               1024
+#define PARTIAL_BODY_SIZE_IN_BYTES          15360     /*  Partial Body download - 15K */
+#define NO_LIMITATION                       0
+#define MAX_MAILBOX_TYPE                    100
+#define EMAIL_SYNC_ALL_MAILBOX              1
+#define EMAIL_ATTACHMENT_MAX_COUNT          512
+#define DOWNLOAD_MAX_BUFFER_SIZE            8000
+#define LOCAL_MAX_BUFFER_SIZE               1000000
+#define IMAP_MAX_COMMAND_LENGTH             1000
+#define DOWNLOAD_NOTI_INTERVAL_PERCENT      5         /*  notify every 5% */
+#define DOWNLOAD_NOTI_INTERVAL_SIZE         51200     /*  notify every 50k */
+#define MAX_PATH                            4096      /* /usr/src/linux-2.4.20-8/include/linux/limits.h */
+#define DATETIME_LENGTH                     16
+#define MAIL_ID_STRING_LENGTH               10
+#define MAILBOX_ID_STRING_LENGTH            10
+#define        EMAIL_LIMITATION_FREE_SPACE         (5) /*  This value is 5MB */
+#define EMAIL_MAIL_MAX_COUNT                5000
+#define HTML_EXTENSION_STRING               ".htm"
+#define MAX_PATH_HTML                       256
+#define MAX_ACTIVE_TASK                     10
+
+#define DIR_SEPERATOR                       "/"
+
+#define USERDATA_PATH                       "/opt/usr"
+#define DATA_PATH                           "/opt/usr/data"
+#define DB_PATH                             "/opt/usr/dbspace"
+#define EMAIL_SERVICE_DB_FILE_PATH          "/opt/usr/dbspace/.email-service.db"
+
+#define EMAILPATH                                              DATA_PATH"/email"
+#define MAILHOME                                               DATA_PATH"/email/.email_data"
+#define MAILTEMP                            MAILHOME"/tmp"
+#define DIRECTORY_PERMISSION                0755
+
+#define MIME_SUBTYPE_DRM_OBJECT             "vnd.oma.drm.message"
+#define MIME_SUBTYPE_DRM_RIGHTS             "vnd.oma.drm.rights+xml"
+#define MIME_SUBTYPE_DRM_DCF                "vnd.oma.drm.dcf"
+
+#define SHM_FILE_FOR_DB_LOCK                "/.email_shm_db_lock"
+
+#define NATIVE_EMAIL_APPLICATION_PKG        "com.samsung.email"
+
+#define IMAP_ID_OS                          "TIZEN"
+#define IMAP_ID_OS_VERSION                  "2.0b"
+#define IMAP_ID_VENDOR                      "Samsung Mobile"
+#define IMAP_ID_DEVICE_NAME                 "GT-I8800_EUR_XX"
+#define IMAP_ID_AGUID                       "1"
+#define IMAP_ID_ACLID                       "Samsung"
+
+#ifdef __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__
+#define SHM_FILE_FOR_MAIL_ID_LOCK           "/.email_shm_mail_id_lock"
+#endif /* __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__ */
+
+#define CR                                  '\r'
+#define LF                                  '\n'
+#define SPACE                               ' '
+#define TAB                                 '\t'
+#define NULL_CHAR                           '\0'
+#define TAB_STRING                          "\t"
+#define CR_STRING                           "\r"
+#define LF_STRING                           "\n"
+#define CRLF_STRING                         "\r\n"
+
+#define GRAB_TYPE_TEXT                      1        /*  retrieve text and attachment list */
+#define GRAB_TYPE_ATTACHMENT                2        /*  retrieve attachment */
+
+#define SAVE_TYPE_SIZE                      1        /*  only get content size */
+#define SAVE_TYPE_BUFFER                    2        /*  save content to buffer */
+#define SAVE_TYPE_FILE                      3        /*  save content to temporary file */
+
+#define FINISH_OFF_IF_CANCELED              if (!emcore_check_thread_status()) { err = EMAIL_ERROR_CANCELLED; goto FINISH_OFF; }
+#define CHECK_JOB_CANCELED()                {if (!emcore_check_thread_status()) goto JOB_CANCEL; }
+
+#define SNPRINTF(buff, size, format, args...)  snprintf(buff, size, format, ##args)
+#define SNPRINTF_OFFSET(base_buf, offset, base_size, format, args...) \
+                       ({\
+                               int _offset = offset;\
+                               snprintf(base_buf + _offset, base_size - _offset - 1, format, ##args);\
+                       })
+
+#define THREAD_CREATE(tv, func, param, err)       { EM_DEBUG_LOG("THREAD_CREATE "#tv); err = pthread_create(&tv, NULL, func, param); }
+#define THREAD_CREATE_JOINABLE(tv, func, err)     { pthread_attr_t attr; EM_DEBUG_LOG("THREAD_CREATE_JOINABLE "#tv); \
+                                                   pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\
+                                                   err = pthread_create(&tv, &attr, func, NULL); pthread_attr_destroy(&attr); }
+#define THREAD_JOIN(tv)                           {EM_DEBUG_LOG("THREAD_JOIN "#tv); pthread_join(tv, NULL); }
+#define THREAD_SELF()                             pthread_self()
+#define THREAD_DETACH(tv)                         pthread_detach(tv)
+#define INITIALIZE_CRITICAL_SECTION(cs)           {EM_DEBUG_LOG("INITIALIZE_CRITICAL_SECTION "#cs); pthread_mutex_init(&cs, NULL); }
+#define ENTER_CRITICAL_SECTION(cs)                {EM_DEBUG_LOG("ENTER_CRITICAL_SECTION "#cs); pthread_mutex_lock(&cs); }
+#define TRY_ENTER_CRITICAL_SECTION(cs)            {EM_DEBUG_LOG("TRY_ENTER_CRITICAL_SECTION "#cs); pthread_mutex_trylock(&cs); }
+#define LEAVE_CRITICAL_SECTION(cs)                {EM_DEBUG_LOG("LEAVE_CRITICAL_SECTION "#cs); pthread_mutex_unlock(&cs); }
+#define DELETE_CRITICAL_SECTION(cs)               {EM_DEBUG_LOG("DELETE_CRITICAL_SECTION "#cs); pthread_mutex_destroy(&cs); }
+
+#define INITIALIZE_CONDITION_VARIABLE(cv)         {EM_DEBUG_LOG("INITIALIZE_CONDITION_VARIABLE "#cv); pthread_cond_init(&cv, NULL); } 
+#define SLEEP_CONDITION_VARIABLE(cv, cs)          {EM_DEBUG_LOG("SLEEP_CONDITION_VARIABLE "#cv); pthread_cond_wait(&cv, &cs); } 
+#define WAKE_CONDITION_VARIABLE(cv)               {EM_DEBUG_LOG("WAKE_CONDITION_VARIABLE "#cv); pthread_cond_signal(&cv); } 
+#define DELETE_CONDITION_VARIABLE(cv)             {EM_DEBUG_LOG("DELETE_CONDITION_VARIABLE "#cv); pthread_cond_destroy(&cv); } 
+
+#define INITIALIZE_RECURSIVE_CRITICAL_SECTION(cs) { EM_DEBUG_LOG("INITIALIZE_RECURSIVE_CRITICAL_SECTION "#cs);  \
+                                                   if (cs == NULL) {pthread_mutex_lock(&_send_event_available_lock); pthread_mutexattr_t attr; cs = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));\
+                                                   pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);\
+                                                   pthread_mutex_init(cs, &attr);pthread_mutexattr_destroy(&attr); pthread_mutex_unlock(&_send_event_available_lock);}}
+#define ENTER_RECURSIVE_CRITICAL_SECTION(cs)      {EM_DEBUG_LOG("ENTER_RECURSIVE_CRITICAL_SECTION "#cs); if(cs) pthread_mutex_lock(cs);}
+#define TRY_ENTER_RECURSIVE_CRITICAL_SECTION(cs)  {EM_DEBUG_LOG("TRY_ENTER_RECURSIVE_CRITICAL_SECTION "#cs); if(cs)  pthread_mutex_trylock(cs);}
+#define LEAVE_RECURSIVE_CRITICAL_SECTION(cs)      {EM_DEBUG_LOG("LEAVE_RECURSIVE_CRITICAL_SECTION "#cs); if(cs) pthread_mutex_unlock(cs);}
+#define DELETE_RECURSIVE_CRITICAL_SECTION(cs)     {EM_DEBUG_LOG("DELETE_RECURSIVE_CRITICAL_SECTION "#cs); if(cs) pthread_mutex_destroy(cs);}
+typedef pthread_t thread_t;
+
+#define SMTP_RESPONSE_OK                       250
+#define SMTP_RESPONSE_READY                    354
+#define SMTP_RESPONSE_CONNECTION_BROKEN 421
+#define SMTP_RESPONSE_WANT_AUTH                    505
+#define SMTP_RESPONSE_WANT_AUTH2           530
+#define SMTP_RESPONSE_UNAVAIL              550
+
+#define VCONF_KEY_LATEST_MAIL_ID        "db/private/email-service/latest_mail_id"
+#define VCONF_KEY_DEFAULT_ACCOUNT_ID    "db/private/email-service/default_account_id"
+#define VCONF_KEY_NOTI_PRIVATE_ID       "db/private/email-service/noti_private_id"
+
+#define OUTMODE "wb"
+#define INMODE "rb"
+#define READMODE "r"
+
+#define TYPEPKCS7_SIGN 10      
+#define TYPEPKCS7_MIME 11
+
+#define INLINE_ATTACHMENT    1
+#define ATTACHMENT           2
+
+/* __FEATURE_LOCAL_ACTIVITY__ supported
+#define BULK_OPERATION_COUNT              50
+#define ALL_ACTIVITIES                    0
+*/
+
+/* ----------------------------------------------------------------------------- */
+/*  Type */
+typedef enum
+{
+       _SERVICE_THREAD_TYPE_NONE      = 0,  
+       _SERVICE_THREAD_TYPE_RECEIVING = 1, 
+       _SERVICE_THREAD_TYPE_SENDING   = 2, 
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__ 
+       _SERVICE_THREAD_TYPE_PBD       = 3, 
+#endif /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
+} email_service_thread_type;
+
+
+typedef enum
+{
+       EMAIL_PROTOCOL_NONE                        = 0,
+       EMAIL_PROTOCOL_POP3                        = 1,
+       EMAIL_PROTOCOL_IMAP                        = 2,
+       EMAIL_PROTOCOL_SMTP                        = 3,
+} email_protocol_type_t;
+
+typedef enum
+{
+       ACCOUNT_SVC_SYNC_STATUS_RUNNING            = 0,
+       ACCOUNT_SVC_SYNC_STATUS_IDLE               = 1,
+       ACCOUNT_SVC_SYNC_STATUS_OFF                = 2,
+} email_account_svc_sync_status;
+
+typedef enum {
+       SET_TYPE_SET        = 1,
+       SET_TYPE_UNION      = 2,
+       SET_TYPE_MINUS      = 3,
+       SET_TYPE_INTERSECT  = 4 /* Not supported */
+} email_set_type_t;
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+enum
+{
+       EMAIL_STREAM_STATUS_DISCONNECTED = 0,
+       EMAIL_STREAM_STATUS_CONNECTED = 1
+} ;
+#endif /* __FEATURE_KEEP_CONNECTION__ */
+
+enum 
+{
+       EXTENSION_JPEG   = 0,
+       EXTENSION_JPG    = 1,
+       EXTENSION_PNG    = 2,
+       EXTENSION_GIF    = 3,
+       EXTENSION_BMP    = 4,
+       EXTENSION_PIC    = 5,
+       EXTENSION_AGIF   = 6,
+       EXTENSION_TIF    = 7,
+       EXTENSION_WBMP   = 8,
+       EXTENSION_P7S    = 9,
+       EXTENSION_P7M    = 10
+};
+
+/*  event information */
+typedef struct
+{
+       int                      account_id;         /*  in general, account id */
+       email_event_type_t         type;
+       email_event_status_type_t  status;
+       char                    *event_param_data_1; /*  in general, mailbox name (exception in emcore_send_mail, emcore_send_saved_mail it is email_option_t **/
+       char                    *event_param_data_2;
+       char                    *event_param_data_3;
+       int                      event_param_data_4;
+       int                      event_param_data_5;
+       int                      event_param_data_6; /* in general, notification parameter #1 */
+       int                      event_param_data_7; /* in general, notification parameter #2 */
+       int                      event_param_data_8;
+} email_event_t;
+
+
+typedef struct
+{
+       int   num;
+       void *data;
+} email_callback_holder_t;
+
+
+typedef struct email_search_key_t email_search_key_t;
+struct email_search_key_t
+{
+       int               type;
+       char             *value;
+       email_search_key_t *next;
+};
+
+typedef struct
+{
+       int                  tid;
+       email_protocol_type_t  protocol;
+       void                *stream;
+       int                  auth;
+       int                  network;
+       int                  error;
+       int                  status;
+} email_session_t;
+
+typedef struct
+{
+       int                    mailbox_id;                 /**< Unique id on mailbox table.*/
+       char                  *mailbox_name;               /**< Specifies the path of mailbox.*/
+       email_mailbox_type_e   mailbox_type;               /**< Specifies the type of mailbox */
+       char                  *alias;                      /**< Specifies the display name of mailbox.*/
+       int                    unread_count;               /**< Specifies the Unread Mail count in the mailbox.*/
+       int                    total_mail_count_on_local;  /**< Specifies the total number of mails in the mailbox in the local DB.*/
+       int                    total_mail_count_on_server; /**< Specifies the total number of mails in the mailbox in the mail server.*/
+       int                    local;                      /**< Specifies the local mailbox.*/
+       int                    synchronous;                /**< Specifies the mailbox with synchronized the server.*/
+       int                    account_id;                 /**< Specifies the account ID for mailbox.*/
+       int                    has_archived_mails;         /**< Specifies the archived mails.*/
+       int                    mail_slot_size;             /**< Specifies how many mails can be stored in local mailbox.*/
+       int                    no_select;                  /**< Specifies the 'no_select' attribute from xlist.*/
+       void                  *user_data;                  /**< Specifies the internal data.*/
+       void                  *mail_stream;                /**< Specifies the internal data.*/
+} email_internal_mailbox_t;
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+typedef struct email_connection_info
+{
+       int                    account_id;
+       int                    sending_server_stream_status;
+       void                  *sending_server_stream;
+       int                    receiving_server_stream_status;
+       void                  *receiving_server_stream;
+       struct email_connection_info *next;
+} email_connection_info_t;
+#endif /* __FEATURE_KEEP_CONNECTION__ */
+
+typedef struct
+{
+       char *contact_name;
+       char *email_address;
+       char *alias;
+       int   storage_type;
+       int   contact_id;
+} email_mail_contact_info_t;
+
+/*  global account list */
+typedef struct email_account_list {
+    email_account_t *account;
+    struct email_account_list *next;
+} email_account_list_t;
+
+typedef struct {
+       int                task_id;
+       email_task_type_t  task_type;
+       thread_t           thread_id;
+} email_active_task_t;
+
+typedef void (*email_event_callback)(int total, int done, int status, int account_id, int mail_id, int handle, void *user_data, int error);
+
+/* ----------------------------------------------------------------------------- */
+/*  Please contact Himanshu [h.gahlaut@samsung.com] for any explanation in code here under __FEATURE_PARTIAL_BODY_DOWNLOAD__ MACRO */
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+typedef enum
+{
+       ACTIVITY_PARTIAL_BODY_DOWNLOAD_IMAP4 = 1,
+       ACTIVITY_PARTIAL_BODY_DOWNLOAD_POP3_WAIT,
+       ACTIVITY_PARTIAL_BODY_DOWNLOAD_POP3_ACTIVE
+}      email_pdb_activity_type_e;
+
+typedef struct 
+{
+    int account_id;
+    int mail_id;
+    unsigned long server_mail_id;
+    int activity_id;
+    int mailbox_id;
+    char *mailbox_name;
+    email_event_type_t event_type;   /*  Event Type Null means event is created from local activitys    */
+    int activity_type;             /*  Activity Type Null means event is created from event queue */
+
+} email_event_partial_body_thd;
+#endif /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
+
+#ifdef __cplusplus
+}
+#endif /*  __cplusplus */
+
+#endif /*  __EMAIL_INTERNAL_TYPES_H__ */
diff --git a/email-common-use/include/email-types.h b/email-common-use/include/email-types.h
new file mode 100755 (executable)
index 0000000..efe62ba
--- /dev/null
@@ -0,0 +1,1857 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 __EMAIL_TYPES_H__
+#define __EMAIL_TYPES_H__
+
+/**
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_TYPES Email Types
+* @{
+*/
+/**
+ * This file defines structures and enums of Email Framework.
+ * @file       email-types.h
+ * @author     Kyu-ho Jo(kyuho.jo@samsung.com)
+ * @author     Choongho Lee(ch715.lee@samsung.com)
+ * @version    0.1
+ * @brief      This file is the header file of Email Framework library.
+ */
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include <glib.h>
+#include <stdbool.h>
+#include "email-errors.h"
+
+
+/*****************************************************************************/
+/*  Macros                                                                   */
+/*****************************************************************************/
+
+#define MAILBOX_NAME_LENGTH               256
+#define MAX_EMAIL_ADDRESS_LENGTH          254                                    /* RFC5322, RFC3696 */
+#define MAX_USER_NAME_LENGTH              64
+#define MAX_DATETIME_STRING_LENGTH        20
+#define MAX_PREVIEW_TEXT_LENGTH           512
+#define STRING_LENGTH_FOR_DISPLAY         100
+#define MEETING_REQ_OBJECT_ID_LENGTH      256
+
+#define ALL_ACCOUNT                       0
+#define NEW_ACCOUNT_ID                    0xFFFFFFFE
+#define ALL_MAIL                          -1
+
+#define EMAIL_SEARCH_FILTER_NONE          0x00
+#define EMAIL_SEARCH_FILTER_SUBJECT       0x01
+#define EMAIL_SEARCH_FILTER_SENDER        0x02
+#define EMAIL_SEARCH_FILTER_RECIPIENT     0x04
+#define EMAIL_SEARCH_FILTER_ALL           0x07                                   /*  EMAIL_SEARCH_FILTER_SUBJECT + EMAIL_SEARCH_FILTER_SENDER + EMAIL_SEARCH_FILTER_RECIPIEN */
+
+#define EMAIL_SUCCESS                     0                                      /*  we need to modify the success return value */
+
+#define EMAIL_ACC_GET_OPT_DEFAULT         0x01                                   /**< Default values without account name */
+#define EMAIL_ACC_GET_OPT_ACCOUNT_NAME    0x02                                   /**< Account name */
+#define EMAIL_ACC_GET_OPT_PASSWORD        0x04                                   /**< With password */
+#define EMAIL_ACC_GET_OPT_OPTIONS         0x08                                   /**< Account options : email_option_t */
+#define EMAIL_ACC_GET_OPT_FULL_DATA       0xFF                                   /**< With all data of account */
+
+#define GET_FULL_DATA                     (EMAIL_ACC_GET_OPT_FULL_DATA)
+#define GET_FULL_DATA_WITHOUT_PASSWORD    (EMAIL_ACC_GET_OPT_DEFAULT | EMAIL_ACC_GET_OPT_ACCOUNT_NAME | EMAIL_ACC_GET_OPT_OPTIONS )
+#define WITHOUT_OPTION                    (EMAIL_ACC_GET_OPT_DEFAULT | EMAIL_ACC_GET_OPT_ACCOUNT_NAME )
+#define ONLY_OPTION                       (EMAIL_ACC_GET_OPT_OPTIONS)
+
+#define THREAD_TYPE_RECEIVING             0                                      /**< for function 'email_activate_pdp' */
+#define THREAD_TYPE_SENDING               1                                      /**< for function 'email_activate_pdp' */
+
+#define EMAIL_IMAP_PORT                   143                                    /**< Specifies the default IMAP port.*/
+#define EMAIL_POP3_PORT                   110                                    /**< Specifies the default POP3 port.*/
+#define EMAIL_SMTP_PORT                   25                                     /**< Specifies the default SMTP port.*/
+#define EMAIL_IMAPS_PORT                  993                                    /**< Specifies the default IMAP SSL port.*/
+#define EMAIL_POP3S_PORT                  995                                    /**< Specifies the default POP3 SSL port.*/
+#define EMAIL_SMTPS_PORT                  465                                    /**< Specifies the default SMTP SSL port.*/
+#define EMAIL_ACCOUNT_MAX                 10                                     /**< Specifies the MAX account.*/
+
+#define EMAIL_INBOX_NAME                  "INBOX"                                /**< Specifies the name of inbox.*/
+#define EMAIL_DRAFTBOX_NAME               "DRAFTBOX"                             /**< Specifies the name of draftbox.*/
+#define EMAIL_OUTBOX_NAME                 "OUTBOX"                               /**< Specifies the name of outbox.*/
+#define EMAIL_SENTBOX_NAME                "SENTBOX"                              /**< Specifies the name of sentbox.*/
+#define EMAIL_TRASH_NAME                  "TRASH"                                /**< Specifies the name of trash.*/
+#define EMAIL_SPAMBOX_NAME                "SPAMBOX"                              /**< Specifies the name of spambox.*/
+
+#define EMAIL_INBOX_DISPLAY_NAME          "Inbox"                                /**< Specifies the display name of inbox.*/
+#define EMAIL_DRAFTBOX_DISPLAY_NAME       "Draftbox"                             /**< Specifies the display name of draftbox.*/
+#define EMAIL_OUTBOX_DISPLAY_NAME         "Outbox"                               /**< Specifies the display name of outbox.*/
+#define EMAIL_SENTBOX_DISPLAY_NAME        "Sentbox"                              /**< Specifies the display name of sentbox.*/
+#define EMAIL_TRASH_DISPLAY_NAME          "Trash"                                /**< Specifies the display name of sentbox.*/
+#define EMAIL_SPAMBOX_DISPLAY_NAME        "Spambox"                              /**< Specifies the display name of spambox.*/
+
+#define EMAIL_SEARCH_RESULT_MAILBOX_NAME  "_`S1!E2@A3#R4$C5^H6&R7*E8(S9)U0-L=T_" /**< Specifies the name of search result mailbox.*/
+
+#define SYNC_STATUS_FINISHED              0                                      /* BIN 00000000 */
+#define SYNC_STATUS_SYNCING               1                                      /* BIN 00000001 */
+#define SYNC_STATUS_HAVE_NEW_MAILS        2                                      /* BIN 00000010 */
+
+#define UNKNOWN_CHARSET_PLAIN_TEXT_FILE   "unknown"
+#define UNKNOWN_CHARSET_HTML_TEXT_FILE    "unknown.htm"
+
+#define FAILURE                           -1
+#define SUCCESS                           0
+
+#define DAEMON_EXECUTABLE_PATH            "/usr/bin/email-service"
+
+#ifndef EXPORT_API
+#define EXPORT_API                        __attribute__((visibility("default")))
+#endif
+
+#ifndef DEPRECATED
+#define DEPRECATED                        __attribute__((deprecated))
+#endif
+
+#define VCONF_VIP_NOTI_RINGTONE_PATH          "db/private/email-service/noti_ringtone_path"            
+#define VCONF_VIP_NOTI_REP_TYPE               "db/private/email-service/noti_rep_type"                 
+#define VCONF_VIP_NOTI_NOTIFICATION_TICKER    "db/private/email-service/noti_notification_ticker"      
+#define VCONF_VIP_NOTI_DISPLAY_CONTENT_TICKER "db/private/email-service/noti_display_content_ticker"   
+#define VCONF_VIP_NOTI_BADGE_TICKER           "db/private/email-service/noti_badge_ticker"             
+
+/*****************************************************************************/
+/*  Enumerations                                                             */
+/*****************************************************************************/
+
+enum {
+       /* Account */
+       _EMAIL_API_ADD_ACCOUNT                               = 0x01000000,
+       _EMAIL_API_DELETE_ACCOUNT                            = 0x01000001,
+       _EMAIL_API_UPDATE_ACCOUNT                            = 0x01000002,
+       _EMAIL_API_GET_ACCOUNT                               = 0x01000003,
+       _EMAIL_API_GET_ACCOUNT_LIST                          = 0x01000005,
+       _EMAIL_API_GET_MAILBOX_COUNT                         = 0x01000007,
+       _EMAIL_API_VALIDATE_ACCOUNT                          = 0x01000008,
+       _EMAIL_API_ADD_ACCOUNT_WITH_VALIDATION               = 0x01000009,
+       _EMAIL_API_BACKUP_ACCOUNTS                           = 0x0100000A,
+       _EMAIL_API_RESTORE_ACCOUNTS                          = 0x0100000B,
+       _EMAIL_API_GET_PASSWORD_LENGTH_OF_ACCOUNT            = 0x0100000C,
+
+       /* Mail */
+       _EMAIL_API_DELETE_MAIL                               = 0x01100002,
+       _EMAIL_API_DELETE_ALL_MAIL                           = 0x01100004,
+       _EMAIL_API_GET_MAILBOX_LIST                          = 0x01100006,
+       _EMAIL_API_GET_SUBMAILBOX_LIST                       = 0x01100007,
+       _EMAIL_API_CLEAR_DATA                                = 0x01100009,
+       _EMAIL_API_MOVE_MAIL                                 = 0x0110000A,
+       _EMAIL_API_MOVE_ALL_MAIL                             = 0x0110000B,
+       _EMAIL_API_ADD_ATTACHMENT                            = 0x0110000C,
+       _EMAIL_API_GET_ATTACHMENT                            = 0x0110000D,
+       _EMAIL_API_DELETE_ATTACHMENT                         = 0x0110000E,
+       _EMAIL_API_MODIFY_MAIL_FLAG                          = 0x0110000F,
+       _EMAIL_API_MODIFY_MAIL_EXTRA_FLAG                    = 0x01100011,
+       _EMAIL_API_SET_FLAGS_FIELD                           = 0x01100016,
+       _EMAIL_API_ADD_MAIL                                  = 0x01100017,
+       _EMAIL_API_UPDATE_MAIL                               = 0x01100018,
+       _EMAIL_API_ADD_READ_RECEIPT                          = 0x01100019,
+       _EMAIL_API_EXPUNGE_MAILS_DELETED_FLAGGED             = 0x0110001A,
+       _EMAIL_API_UPDATE_MAIL_ATTRIBUTE                     = 0x0110001B,
+
+       /* Thread */
+       _EMAIL_API_MOVE_THREAD_TO_MAILBOX                    = 0x01110000,
+       _EMAIL_API_DELETE_THREAD                             = 0x01110001,
+       _EMAIL_API_MODIFY_SEEN_FLAG_OF_THREAD                = 0x01110002,
+
+       /* Mailbox */
+       _EMAIL_API_ADD_MAILBOX                               = 0x01200000,
+       _EMAIL_API_DELETE_MAILBOX                            = 0x01200001,
+       _EMAIL_API_SET_MAIL_SLOT_SIZE                        = 0x01200007,
+       _EMAIL_API_RENAME_MAILBOX                            = 0x01200008,
+       _EMAIL_API_SET_MAILBOX_TYPE                          = 0x01200009,
+       _EMAIL_API_SET_LOCAL_MAILBOX                         = 0x0120000A,
+
+       /* Network */
+       _EMAIL_API_SEND_MAIL                                 = 0x01300000,
+       _EMAIL_API_SYNC_HEADER                               = 0x01300001,
+       _EMAIL_API_DOWNLOAD_BODY                             = 0x01300002,
+       _EMAIL_API_DOWNLOAD_ATTACHMENT                       = 0x01300003,
+       _EMAIL_API_NETWORK_GET_STATUS                        = 0x01300004,
+       _EMAIL_API_SEND_SAVED                                = 0x01300005,
+       _EMAIL_API_DELETE_EMAIL                              = 0x01300007,
+       _EMAIL_API_DELETE_EMAIL_ALL                          = 0x01300008,
+       _EMAIL_API_GET_IMAP_MAILBOX_LIST                     = 0x01300015,
+       _EMAIL_API_SEND_MAIL_CANCEL_JOB                       = 0x01300017,
+       _EMAIL_API_SEARCH_MAIL_ON_SERVER                     = 0x01300019,
+       _EMAIL_API_CLEAR_RESULT_OF_SEARCH_MAIL_ON_SERVER     = 0x0130001A,
+
+       /* Rule */
+       _EMAIL_API_ADD_RULE                                  = 0x01400000,
+       _EMAIL_API_GET_RULE                                  = 0x01400001,
+       _EMAIL_API_GET_RULE_LIST                             = 0x01400002,
+       _EMAIL_API_FIND_RULE                                 = 0x01400003,
+       _EMAIL_API_DELETE_RULE                               = 0x01400004,
+       _EMAIL_API_UPDATE_RULE                               = 0x01400005,
+       _EMAIL_API_CANCEL_JOB                                = 0x01400006,
+       _EMAIL_API_GET_PENDING_JOB                           = 0x01400007,
+       _EMAIL_API_SEND_RETRY                                = 0x01400008,
+       _EMAIL_API_UPDATE_ACTIVITY                           = 0x01400009,
+       _EMAIL_API_SYNC_LOCAL_ACTIVITY                       = 0x0140000A,
+       _EMAIL_API_PRINT_RECEIVING_EVENT_QUEUE               = 0x0140000B,
+
+       /* Etc */
+       _EMAIL_API_PING_SERVICE                              = 0x01500000,
+       _EMAIL_API_UPDATE_NOTIFICATION_BAR_FOR_UNREAD_MAIL   = 0x01500001,
+       _EMAIL_API_SHOW_USER_MESSAGE                         = 0x01500002,
+       _EMAIL_API_WRITE_MIME_FILE                           = 0x01500003,
+
+       /* Smime */
+       _EMAIL_API_ADD_CERTIFICATE                           = 0x01600000,
+       _EMAIL_API_DELETE_CERTIFICATE                        = 0x01600001,
+       _EMAIL_API_VERIFY_SIGNATURE                          = 0x01600002,
+       _EMAIL_API_VERIFY_CERTIFICATE                        = 0x01600003,
+};
+
+typedef enum
+{
+       EMAIL_DELETE_LOCALLY                     = 0,  /**< Specifies Mail Delete local only */
+       EMAIL_DELETE_LOCAL_AND_SERVER,                 /**< Specifies Mail Delete local & server */
+       EMAIL_DELETE_FOR_SEND_THREAD,                  /**< Created to check which activity to delete in send thread */
+       EMAIL_DELETE_FROM_SERVER,
+       EMAIL_DELETE_MAIL_AND_MEETING_FOR_EAS,         /**< Delete mails and meetings on an EAS account. */
+} email_delete_option_t;
+
+typedef enum
+{
+       NOTI_MAIL_ADD                            = 10000,
+       NOTI_MAIL_DELETE                         = 10001,
+       NOTI_MAIL_DELETE_ALL                     = 10002,
+       NOTI_MAIL_DELETE_WITH_ACCOUNT            = 10003,
+       NOTI_MAIL_DELETE_FAIL                    = 10007,
+       NOTI_MAIL_DELETE_FINISH                  = 10008,
+
+       NOTI_MAIL_UPDATE                         = 10004,
+       NOTI_MAIL_FIELD_UPDATE                   = 10020,
+
+       NOTI_MAIL_MOVE                           = 10005,
+       NOTI_MAIL_MOVE_FAIL                      = 10010,
+       NOTI_MAIL_MOVE_FINISH                    = 10006,
+
+       NOTI_THREAD_MOVE                         = 11000,
+       NOTI_THREAD_DELETE                       = 11001,
+       NOTI_THREAD_MODIFY_SEEN_FLAG             = 11002,
+
+       NOTI_ACCOUNT_ADD                         = 20000,
+       NOTI_ACCOUNT_DELETE                      = 20001,
+       NOTI_ACCOUNT_DELETE_FAIL                 = 20003,
+       NOTI_ACCOUNT_UPDATE                      = 20002,
+       NOTI_ACCOUNT_UPDATE_SYNC_STATUS          = 20010,
+
+       NOTI_MAILBOX_ADD                         = 40000,
+       NOTI_MAILBOX_DELETE                      = 40001,
+       NOTI_MAILBOX_UPDATE                      = 40002,
+       NOTI_MAILBOX_FIELD_UPDATE                = 40003,
+
+       NOTI_MAILBOX_RENAME                      = 40010,
+       NOTI_MAILBOX_RENAME_FAIL                 = 40011,
+
+       NOTI_CERTIFICATE_ADD                     = 50000,
+       NOTI_CERTIFICATE_DELETE                  = 50001,
+       NOTI_CERTIFICATE_UPDATE                  = 50002,
+       /* To be added more */
+} email_noti_on_storage_event;
+
+typedef enum
+{
+       NOTI_SEND_START                          = 1002,
+       NOTI_SEND_FINISH                         = 1004,
+       NOTI_SEND_FAIL                           = 1005,
+       NOTI_SEND_CANCEL                         = 1003,
+
+       NOTI_DOWNLOAD_START                      = 2000,
+       NOTI_DOWNLOAD_FINISH,
+       NOTI_DOWNLOAD_FAIL,
+       NOTI_DOWNLOAD_CANCEL                     = 2004,
+       NOTI_DOWNLOAD_NEW_MAIL                   = 2003,
+
+       NOTI_DOWNLOAD_BODY_START                 = 3000,
+       NOTI_DOWNLOAD_BODY_FINISH                = 3002,
+       NOTI_DOWNLOAD_BODY_FAIL                  = 3004,
+       NOTI_DOWNLOAD_BODY_CANCEL                = 3003,
+       NOTI_DOWNLOAD_MULTIPART_BODY             = 3001,
+
+       NOTI_DOWNLOAD_ATTACH_START               = 4000,
+       NOTI_DOWNLOAD_ATTACH_FINISH,
+       NOTI_DOWNLOAD_ATTACH_FAIL,
+       NOTI_DOWNLOAD_ATTACH_CANCEL,
+
+       NOTI_MAIL_DELETE_ON_SERVER_FAIL          = 5000,
+       NOTI_MAIL_MOVE_ON_SERVER_FAIL,
+
+       NOTI_SEARCH_ON_SERVER_START              = 6000,
+       NOTI_SEARCH_ON_SERVER_FINISH             = 6001,
+       NOTI_SEARCH_ON_SERVER_FAIL               = 6002,
+       NOTI_SEARCH_ON_SERVER_CANCEL             = 6003,
+
+       NOTI_VALIDATE_ACCOUNT_FINISH             = 7000,
+       NOTI_VALIDATE_ACCOUNT_FAIL,
+       NOTI_VALIDATE_ACCOUNT_CANCEL,
+
+       NOTI_VALIDATE_AND_CREATE_ACCOUNT_FINISH  = 8000,
+       NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL,
+       NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL,
+
+       NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FINISH  = 9000,
+       NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FAIL,
+       NOTI_VALIDATE_AND_UPDATE_ACCOUNT_CANCEL,
+
+       NOTI_VALIDATE_CERTIFICATE_FINISH         = 10000,
+       NOTI_VALIDATE_CERTIFICATE_FAIL           = 10001,
+       NOTI_VALIDATE_CERTIFICATE_CANCEL         = 10002,
+
+       NOTI_RESOLVE_RECIPIENT_START             = 11000,
+       NOTI_RESOLVE_RECIPIENT_FINISH,
+       NOTI_RESOLVE_RECIPIENT_FAIL,
+       NOTI_RESOLVE_RECIPIENT_CANCEL,
+
+       NOTI_RENAME_MAILBOX_START                = 12000,
+       NOTI_RENAME_MAILBOX_FINISH,
+       NOTI_RENAME_MAILBOX_FAIL,
+       NOTI_RENAME_MAILBOX_CANCEL,
+
+       NOTI_ADD_MAILBOX_START                   = 12100,
+       NOTI_ADD_MAILBOX_FINISH,
+       NOTI_ADD_MAILBOX_FAIL,
+       NOTI_ADD_MAILBOX_CANCEL,
+
+       NOTI_DELETE_MAILBOX_START                = 12200,
+       NOTI_DELETE_MAILBOX_FINISH,
+       NOTI_DELETE_MAILBOX_FAIL,
+       NOTI_DELETE_MAILBOX_CANCEL,
+
+       NOTI_SYNC_IMAP_MAILBOX_LIST_START        = 12300,
+       NOTI_SYNC_IMAP_MAILBOX_LIST_FINISH,
+       NOTI_SYNC_IMAP_MAILBOX_LIST_FAIL,
+       NOTI_SYNC_IMAP_MAILBOX_LIST_CANCEL,
+
+       /* To be added more */
+} email_noti_on_network_event;
+
+typedef enum
+{
+       RESPONSE_SUCCEEDED                       = 0,
+       RESPONSE_FAILED                          = 1,
+       RESPONSE_CANCELED                        = 2
+       /* To be added more */
+} email_response_to_request;
+
+/**
+ * This enumeration specifies the mail type of account.
+ */
+typedef enum
+{
+       EMAIL_BIND_TYPE_DISABLE          = 0,          /**< Specifies the bind type for Disabled account.*/
+       EMAIL_BIND_TYPE_EM_CORE          = 1,          /**< Specifies the bind type for email-service .*/
+} email_account_bind_t DEPRECATED;
+
+/**
+ * This enumeration specifies the server type of account.
+ */
+typedef enum
+{
+       EMAIL_SERVER_TYPE_POP3           = 1,          /**< Specifies the POP3 Server.*/
+       EMAIL_SERVER_TYPE_IMAP4,                       /**< Specifies the IMAP4 Server.*/
+       EMAIL_SERVER_TYPE_SMTP,                        /**< Specifies the SMTP Server.*/
+       EMAIL_SERVER_TYPE_NONE,                        /**< Specifies the Local.*/
+       EMAIL_SERVER_TYPE_ACTIVE_SYNC,                 /** < Specifies the Active Sync.  */
+} email_account_server_t;
+
+/**
+ * This enumeration specifies the mode of retrieval.
+ */
+typedef enum
+{
+       EMAIL_IMAP4_RETRIEVAL_MODE_NEW   = 0,          /**< Specifies the retrieval mode for new email.*/
+       EMAIL_IMAP4_RETRIEVAL_MODE_ALL,                /**< Specifies the retrieval mode for all email.*/
+} email_imap4_retrieval_mode_t;
+
+/**
+ * This enumeration specifies the filtering type.
+ */
+typedef enum
+{
+       EMAIL_FILTER_FROM                = 1,          /**< Specifies the filtering of sender.*/
+       EMAIL_FILTER_SUBJECT,                          /**< Specifies the filtering of email subject.*/
+       EMAIL_FILTER_BODY,                             /**< Specifies the filterinf of email body.*/
+       EMAIL_PRIORITY_SENDER,                         /**< Specifies the priority sender of email. */
+} email_rule_type_t;
+
+
+/**
+ * This enumeration specifies the rules for filtering type.
+ */
+typedef enum
+{
+       RULE_TYPE_INCLUDES             = 1,          /**< Specifies the filtering rule for includes.*/
+       RULE_TYPE_EXACTLY,                           /**< Specifies the filtering rule for Exactly same as.*/
+} email_filtering_type_t;
+
+
+/**
+ * This enumeration specifies the action for filtering type.
+ */
+typedef enum
+{
+       EMAIL_FILTER_MOVE                = 1,          /**< Specifies the move of email.*/
+       EMAIL_FILTER_BLOCK               = 2,          /**< Specifies the block of email.*/
+       EMAIL_FILTER_DELETE              = 3,          /**< Specifies delete email.*/
+} email_rule_action_t;
+
+/**
+ * This enumeration specifies the email status.
+ */
+typedef enum
+{
+       EMAIL_MAIL_STATUS_NONE           = 0,          /**< The Mail is in No Operation state */
+       EMAIL_MAIL_STATUS_RECEIVED,                    /**< The mail is a received mail.*/
+       EMAIL_MAIL_STATUS_SENT,                        /**< The mail is a sent mail.*/
+       EMAIL_MAIL_STATUS_SAVED,                       /**< The mail is a saved mail.*/
+       EMAIL_MAIL_STATUS_SAVED_OFFLINE,               /**< The mail is a saved mail in off-line mode.*/
+       EMAIL_MAIL_STATUS_SENDING,                     /**< The mail is being sent.*/
+       EMAIL_MAIL_STATUS_SEND_FAILURE,                /**< The mail is a mail to been failed to send.*/
+       EMAIL_MAIL_STATUS_SEND_CANCELED,               /**< The mail is a canceled mail.*/
+       EMAIL_MAIL_STATUS_SEND_WAIT,                   /**< The mail is a mail to be send .*/
+} email_mail_status_t;
+
+/**
+ * This enumeration specifies the email priority.
+ */
+typedef enum
+{
+       EMAIL_MAIL_PRIORITY_HIGH         = 1,          /**< The priority is high.*/
+       EMAIL_MAIL_PRIORITY_NORMAL       = 3,          /**< The priority is normal.*/
+       EMAIL_MAIL_PRIORITY_LOW          = 5,          /**< The priority is low.*/
+} email_mail_priority_t;
+
+/**
+ * This enumeration specifies the email status.
+ */
+typedef enum
+{
+       EMAIL_MAIL_REPORT_NONE           = 0x00,       /**< The mail isn't report mail.*/
+       EMAIL_MAIL_REPORT_REQUEST        = 0x03,       /* Deprecated */
+       EMAIL_MAIL_REPORT_DSN            = 0x04,       /**< The mail is a Delivery Status Notifications mail.*/
+       EMAIL_MAIL_REPORT_MDN            = 0x08,       /**< The mail is a Message Disposition Notifications mail.*/
+       EMAIL_MAIL_REQUEST_DSN           = 0x10,       /**< The mail requires Delivery Status Notifications.*/
+       EMAIL_MAIL_REQUEST_MDN           = 0x20,       /**< The mail requires Message Disposition Notifications.*/
+} email_mail_report_t;
+
+/**
+ * This enumeration specifies the DRM type
+ */
+typedef enum
+{
+       EMAIL_ATTACHMENT_DRM_NONE        = 0,          /**< The mail isn't DRM file.*/
+       EMAIL_ATTACHMENT_DRM_OBJECT,                   /**< The mail is a DRM object.*/
+       EMAIL_ATTACHMENT_DRM_RIGHTS,                   /**< The mail is a DRM rights as xml format.*/
+       EMAIL_ATTACHMENT_DRM_DCF,                      /**< The mail is a DRM dcf.*/
+} email_attachment_drm_t;
+
+/**
+ * This enumeration specifies the mail type
+ */
+typedef enum
+{
+       EMAIL_MAIL_TYPE_NORMAL                     = 0, /**< NOT a meeting request mail. A Normal mail */
+       EMAIL_MAIL_TYPE_MEETING_REQUEST            = 1, /**< a meeting request mail from a serve */
+       EMAIL_MAIL_TYPE_MEETING_RESPONSE           = 2, /**< a response mail about meeting reques */
+       EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST = 3  /**< a originating mail about meeting reques */
+} email_mail_type_t;
+
+/**
+ * This enumeration specifies the meeting response type
+ */
+typedef enum
+{
+       EMAIL_MEETING_RESPONSE_NONE                = 0, /**< NOT response */
+       EMAIL_MEETING_RESPONSE_ACCEPT              = 1, /**< The response is acceptance */
+       EMAIL_MEETING_RESPONSE_TENTATIVE           = 2, /**< The response is tentative */
+       EMAIL_MEETING_RESPONSE_DECLINE             = 3, /**< The response is decline */
+       EMAIL_MEETING_RESPONSE_REQUEST             = 4, /**< The response is request */
+       EMAIL_MEETING_RESPONSE_CANCEL              = 5, /**< The response is cancelation */
+} email_meeting_response_t;
+
+typedef enum
+{
+       EMAIL_ACTION_SEND_MAIL                     =  0,
+       EMAIL_ACTION_SYNC_HEADER                   =  1,
+       EMAIL_ACTION_DOWNLOAD_BODY                 =  2,
+       EMAIL_ACTION_DOWNLOAD_ATTACHMENT           =  3,
+       EMAIL_ACTION_DELETE_MAIL                   =  4,
+       EMAIL_ACTION_SEARCH_MAIL                   =  5,
+       EMAIL_ACTION_SAVE_MAIL                     =  6,
+       EMAIL_ACTION_SYNC_MAIL_FLAG_TO_SERVER      =  7,
+       EMAIL_ACTION_SYNC_FLAGS_FIELD_TO_SERVER    =  8,
+       EMAIL_ACTION_MOVE_MAIL                     =  9,
+       EMAIL_ACTION_CREATE_MAILBOX                = 10,
+       EMAIL_ACTION_DELETE_MAILBOX                = 11,
+       EMAIL_ACTION_SYNC_HEADER_OMA               = 12,
+       EMAIL_ACTION_VALIDATE_ACCOUNT              = 13,
+       EMAIL_ACTION_VALIDATE_AND_CREATE_ACCOUNT   = 14,
+       EMAIL_ACTION_VALIDATE_AND_UPDATE_ACCOUNT   = 15,
+       EMAIL_ACTION_UPDATE_MAIL                   = 30,
+       EMAIL_ACTION_SET_MAIL_SLOT_SIZE            = 31,
+       EMAIL_ACTION_EXPUNGE_MAILS_DELETED_FLAGGED = 32,
+       EMAIL_ACTION_SEARCH_ON_SERVER              = 33,
+       EMAIL_ACTION_MOVE_MAILBOX                  = 34,
+       EMAIL_ACTION_NUM,
+} email_action_t;
+
+/**
+ * This enumeration specifies the status of getting envelope list.
+ */
+typedef enum
+{
+       EMAIL_LIST_NONE                  = 0,
+       EMAIL_LIST_WAITING,
+       EMAIL_LIST_PREPARE,                            /**< Specifies the preparation.*/
+       EMAIL_LIST_CONNECTION_START,                   /**< Specifies the connection start.*/
+       EMAIL_LIST_CONNECTION_SUCCEED,                 /**< Specifies the success of connection.*/
+       EMAIL_LIST_CONNECTION_FINISH,                  /**< Specifies the connection finish.*/
+       EMAIL_LIST_CONNECTION_FAIL,                    /**< Specifies the connection failure.*/
+       EMAIL_LIST_START,                              /**< Specifies the getting start.*/
+       EMAIL_LIST_PROGRESS,                           /**< Specifies the status of getting.*/
+       EMAIL_LIST_FINISH,                             /**< Specifies the getting complete.*/
+       EMAIL_LIST_FAIL,                               /**< Specifies the download failure.*/
+} email_envelope_list_status_t;
+
+/**
+ * This enumeration specifies the downloaded status of email.
+ */
+typedef enum
+{
+       EMAIL_DOWNLOAD_NONE              = 0,
+       EMAIL_DOWNLOAD_WAITING,
+       EMAIL_DOWNLOAD_PREPARE,                        /**< Specifies the preparation.*/
+       EMAIL_DOWNLOAD_CONNECTION_START,               /**< Specifies the connection start.*/
+       EMAIL_DOWNLOAD_CONNECTION_SUCCEED,             /**< Specifies the success of connection.*/
+       EMAIL_DOWNLOAD_CONNECTION_FINISH,              /**< Specifies the connection finish.*/
+       EMAIL_DOWNLOAD_CONNECTION_FAIL,                /**< Specifies the connection failure.*/
+       EMAIL_DOWNLOAD_START,                          /**< Specifies the download start.*/
+       EMAIL_DOWNLOAD_PROGRESS,                       /**< Specifies the status of download.*/
+       EMAIL_DOWNLOAD_FINISH,                         /**< Specifies the download complete.*/
+       EMAIL_DOWNLOAD_FAIL,                           /**< Specifies the download failure.*/
+} email_download_status_t;
+
+/**
+ * This enumeration specifies the status of sending email.
+ */
+typedef enum
+{
+       EMAIL_SEND_NONE                  = 0,
+       EMAIL_SEND_WAITING,
+       EMAIL_SEND_PREPARE,                            /**< Specifies the preparation.*/
+       EMAIL_SEND_CONNECTION_START,                   /**< Specifies the connection start.*/
+       EMAIL_SEND_CONNECTION_SUCCEED,                 /**< Specifies the success of connection.*/
+       EMAIL_SEND_CONNECTION_FINISH,                  /**< Specifies the connection finish.*/
+       EMAIL_SEND_CONNECTION_FAIL,                    /**< Specifies the connection failure.*/
+       EMAIL_SEND_START,                              /**< Specifies the sending start.*/
+       EMAIL_SEND_PROGRESS,                           /**< Specifies the status of sending.*/
+       EMAIL_SEND_FINISH,                             /**< Specifies the sending complete.*/
+       EMAIL_SEND_FAIL,                               /**< Specifies the sending failure.*/
+       EMAIL_SAVE_WAITING,                            /**< Specfies the Waiting of Sync */
+} email_send_status_t;
+
+typedef enum
+{
+       EMAIL_SYNC_NONE                  = 0,
+       EMAIL_SYNC_WAITING,
+       EMAIL_SYNC_PREPARE,
+       EMAIL_SYNC_CONNECTION_START,
+       EMAIL_SYNC_CONNECTION_SUCCEED,
+       EMAIL_SYNC_CONNECTION_FINISH,
+       EMAIL_SYNC_CONNECTION_FAIL,
+       EMAIL_SYNC_START,
+       EMAIL_SYNC_PROGRESS,
+       EMAIL_SYNC_FINISH,
+       EMAIL_SYNC_FAIL,
+} email_sync_status_t;
+
+/**
+* This enumeration specifies the deleting status of email.
+*/
+typedef enum
+{
+       EMAIL_DELETE_NONE                = 0,
+       EMAIL_DELETE_WAITING,
+       EMAIL_DELETE_PREPARE,                          /**< Specifies the preparation.*/
+       EMAIL_DELETE_CONNECTION_START,                 /**< Specifies the connection start.*/
+       EMAIL_DELETE_CONNECTION_SUCCEED,               /**< Specifies the success of connection.*/
+       EMAIL_DELETE_CONNECTION_FINISH,                /**< Specifies the connection finish.*/
+       EMAIL_DELETE_CONNECTION_FAIL,                  /**< Specifies the connection failure.*/
+       EMAIL_DELETE_START,                            /**< Specifies the deletion start.*/
+       EMAIL_DELETE_PROGRESS,                         /**< Specifies the status of deleting.*/
+       EMAIL_DELETE_SERVER_PROGRESS,                  /**< Specifies the status of server deleting.*/
+       EMAIL_DELETE_LOCAL_PROGRESS,                   /**< Specifies the status of local deleting.*/
+       EMAIL_DELETE_FINISH,                           /**< Specifies the deletion complete.*/
+       EMAIL_DELETE_FAIL,                             /**< Specifies the deletion failure.*/
+} email_delete_status_t;
+
+/**
+* This enumeration specifies the status of validating account
+*/
+typedef enum
+{
+       EMAIL_VALIDATE_ACCOUNT_NONE = 0,
+       EMAIL_VALIDATE_ACCOUNT_WAITING,
+       EMAIL_VALIDATE_ACCOUNT_PREPARE,                /**< Specifies the preparation.*/
+       EMAIL_VALIDATE_ACCOUNT_CONNECTION_START,       /**< Specifies the connection start.*/
+       EMAIL_VALIDATE_ACCOUNT_CONNECTION_SUCCEED,     /**< Specifies the success of connection.*/
+       EMAIL_VALIDATE_ACCOUNT_CONNECTION_FINISH,      /**< Specifies the connection finish.*/
+       EMAIL_VALIDATE_ACCOUNT_CONNECTION_FAIL,        /**< Specifies the connection failure.*/
+       EMAIL_VALIDATE_ACCOUNT_START,                  /**< Specifies the getting start.*/
+       EMAIL_VALIDATE_ACCOUNT_PROGRESS,               /**< Specifies the status of getting.*/
+       EMAIL_VALIDATE_ACCOUNT_FINISH,                 /**< Specifies the getting complete.*/
+       EMAIL_VALIDATE_ACCOUNT_FAIL,                   /**< Specifies the validation failure.*/
+} email_validate_account_status_t;
+
+typedef enum
+{
+       EMAIL_SET_SLOT_SIZE_NONE         = 0,
+       EMAIL_SET_SLOT_SIZE_WAITING,
+       EMAIL_SET_SLOT_SIZE_START,
+       EMAIL_SET_SLOT_SIZE_FINISH,
+       EMAIL_SET_SLOT_SIZE_FAIL,
+}email_set_slot_size_status_e;
+
+typedef enum
+{
+       EMAIL_EXPUNGE_MAILS_DELETED_FLAGGED_NONE         = 0,
+       EMAIL_EXPUNGE_MAILS_DELETED_FLAGGED_WAITING,
+       EMAIL_EXPUNGE_MAILS_DELETED_FLAGGED_START,
+       EMAIL_EXPUNGE_MAILS_DELETED_FLAGGED_FINISH,
+       EMAIL_EXPUNGE_MAILS_DELETED_FLAGGED_FAIL,
+}email_expunge_mails_deleted_flagged_status_e;
+
+typedef enum
+{
+       EMAIL_SEARCH_ON_SERVER_NONE         = 0,
+       EMAIL_SEARCH_ON_SERVER_WAITING,
+       EMAIL_SEARCH_ON_SERVER_START,
+       EMAIL_SEARCH_ON_SERVER_FINISH,
+       EMAIL_SEARCH_ON_SERVER_FAIL,
+}email_search_on_server_status_e;
+
+typedef enum
+{
+       EMAIL_MOVE_MAILBOX_ON_IMAP_SERVER_NONE         = 0,
+       EMAIL_MOVE_MAILBOX_ON_IMAP_SERVER_WAITING,
+       EMAIL_MOVE_MAILBOX_ON_IMAP_SERVER_START,
+       EMAIL_MOVE_MAILBOX_ON_IMAP_SERVER_FINISH,
+       EMAIL_MOVE_MAILBOX_ON_IMAP_SERVER_FAIL,
+}email_move_mailbox_status_e;
+
+typedef enum
+{
+       EMAIL_UPDATE_MAIL_NONE         = 0,
+       EMAIL_UPDATE_MAIL_WAITING,
+       EMAIL_UPDATE_MAIL_START,
+       EMAIL_UPDATE_MAIL_FINISH,
+       EMAIL_UPDATE_MAIL_FAIL,
+}email_update_mail_status_e;
+
+/**
+* This enumeration specifies the type of mailbox
+*/
+typedef enum
+{
+       EMAIL_MAILBOX_TYPE_NONE          = 0,         /**< Unspecified mailbox type*/
+       EMAIL_MAILBOX_TYPE_INBOX         = 1,         /**< Specified inbox type*/
+       EMAIL_MAILBOX_TYPE_SENTBOX       = 2,         /**< Specified sent box type*/
+       EMAIL_MAILBOX_TYPE_TRASH         = 3,         /**< Specified trash type*/
+       EMAIL_MAILBOX_TYPE_DRAFT         = 4,         /**< Specified draft box type*/
+       EMAIL_MAILBOX_TYPE_SPAMBOX       = 5,         /**< Specified spam box type*/
+       EMAIL_MAILBOX_TYPE_OUTBOX        = 6,         /**< Specified outbox type*/
+       EMAIL_MAILBOX_TYPE_ALL_EMAILS    = 7,         /**< Specified all emails type of gmail*/
+       EMAIL_MAILBOX_TYPE_SEARCH_RESULT = 8,         /**< Specified mailbox type for result of search on server */
+       EMAIL_MAILBOX_TYPE_FLAGGED       = 9,         /**< Specified flagged mailbox type on gmail */
+       EMAIL_MAILBOX_TYPE_USER_DEFINED  = 0xFF,      /**< Specified mailbox type for all other mailboxes */
+}email_mailbox_type_e;
+
+typedef enum
+{
+       EMAIL_SYNC_LATEST_MAILS_FIRST    = 0,
+       EMAIL_SYNC_OLDEST_MAILS_FIRST,
+       EMAIL_SYNC_ALL_MAILBOX_50_MAILS,
+} EMAIL_RETRIEVE_MODE;
+
+/*  event type */
+typedef enum
+{
+       EMAIL_EVENT_NONE                            =  0,
+       EMAIL_EVENT_SYNC_HEADER                     =  1,          /*  synchronize mail headers with server (network used) */
+       EMAIL_EVENT_DOWNLOAD_BODY                   =  2,          /*  download mail body from server (network used)*/
+       EMAIL_EVENT_DOWNLOAD_ATTACHMENT             =  3,          /*  download mail attachment from server (network used) */
+       EMAIL_EVENT_SEND_MAIL                       =  4,          /*  send a mail (network used) */
+       EMAIL_EVENT_SEND_MAIL_SAVED                 =  5,          /*  send all mails in 'outbox' box (network used) */
+       EMAIL_EVENT_SYNC_IMAP_MAILBOX               =  6,          /*  download imap mailboxes from server (network used) */
+       EMAIL_EVENT_DELETE_MAIL                     =  7,          /*  delete mails (network unused) */
+       EMAIL_EVENT_DELETE_MAIL_ALL                 =  8,          /*  delete all mails (network unused) */
+       EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER        =  9,          /*  sync mail flag to server */
+       EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER      = 10,          /*  sync a field of flags to server */
+       EMAIL_EVENT_SAVE_MAIL                       = 11,          /*  add mail on server */
+       EMAIL_EVENT_MOVE_MAIL                       = 12,          /*  move mails to specific mailbox on server */
+       EMAIL_EVENT_CREATE_MAILBOX                  = 13,
+       EMAIL_EVENT_UPDATE_MAILBOX                  = 14,
+       EMAIL_EVENT_DELETE_MAILBOX                  = 15,
+       EMAIL_EVENT_ISSUE_IDLE                      = 16,
+       EMAIL_EVENT_SYNC_HEADER_OMA                 = 17,
+       EMAIL_EVENT_VALIDATE_ACCOUNT                = 18,
+       EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT     = 19,
+       EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT     = 20,
+       EMAIL_EVENT_SEARCH_ON_SERVER                = 21,
+       EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER                    = 22,
+
+       EMAIL_EVENT_ADD_MAIL                        = 10001,       /*  Deprecated */
+       EMAIL_EVENT_UPDATE_MAIL_OLD                 = 10002,       /*  Deprecated */
+       EMAIL_EVENT_UPDATE_MAIL                     = 10003,
+       EMAIL_EVENT_SET_MAIL_SLOT_SIZE              = 20000,
+       EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED   = 20001,
+
+/*     EMAIL_EVENT_LOCAL_ACTIVITY,                     __LOCAL_ACTIVITY_ */
+
+       EMAIL_EVENT_BULK_PARTIAL_BODY_DOWNLOAD      = 20002,       /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ supported */
+       EMAIL_EVENT_LOCAL_ACTIVITY_SYNC_BULK_PBD    = 20003,       /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ supported */
+       EMAIL_EVENT_GET_PASSWORD_LENGTH             = 20004,       /*  get password length of an account */
+} email_event_type_t;
+
+/*  event status */
+typedef enum
+{
+       EMAIL_EVENT_STATUS_UNUSED        = 0,
+       EMAIL_EVENT_STATUS_WAIT,
+       EMAIL_EVENT_STATUS_STARTED,
+       EMAIL_EVENT_STATUS_CANCELED,
+} email_event_status_type_t;
+
+
+/* sorting_orde */
+typedef enum
+{
+       EMAIL_SORT_DATETIME_HIGH         = 0,
+       EMAIL_SORT_DATETIME_LOW,
+       EMAIL_SORT_SENDER_HIGH,
+       EMAIL_SORT_SENDER_LOW,
+       EMAIL_SORT_RCPT_HIGH,
+       EMAIL_SORT_RCPT_LOW,
+       EMAIL_SORT_SUBJECT_HIGH,
+       EMAIL_SORT_SUBJECT_LOW,
+       EMAIL_SORT_PRIORITY_HIGH,
+       EMAIL_SORT_PRIORITY_LOW,
+       EMAIL_SORT_ATTACHMENT_HIGH,
+       EMAIL_SORT_ATTACHMENT_LOW,
+       EMAIL_SORT_FAVORITE_HIGH,
+       EMAIL_SORT_FAVORITE_LOW,
+       EMAIL_SORT_MAILBOX_NAME_HIGH,
+       EMAIL_SORT_MAILBOX_NAME_LOW,
+       EMAIL_SORT_FLAGGED_FLAG_HIGH,
+       EMAIL_SORT_FLAGGED_FLAG_LOW,
+       EMAIL_SORT_SEEN_FLAG_HIGH,
+       EMAIL_SORT_SEEN_FLAG_LOW,
+       EMAIL_SORT_END,
+}email_sort_type_t;
+
+typedef enum
+{
+       EMAIL_MAILBOX_SORT_BY_NAME_ASC  = 0,
+       EMAIL_MAILBOX_SORT_BY_NAME_DSC,
+       EMAIL_MAILBOX_SORT_BY_TYPE_ASC,
+       EMAIL_MAILBOX_SORT_BY_TYPE_DSC,
+} email_mailbox_sort_type_t;
+
+
+/**
+* This enumeration specifies the priority.
+*/
+enum
+{
+       EMAIL_OPTION_PRIORITY_HIGH       = 1,          /**< Specifies the high priority.*/
+       EMAIL_OPTION_PRIORITY_NORMAL     = 3,          /**< Specifies the normal priority*/
+       EMAIL_OPTION_PRIORITY_LOW        = 5,          /**< Specifies the low priority.*/
+};
+
+/**
+* This enumeration specifies the saving save a copy after sending.
+*/
+enum
+{
+       EMAIL_OPTION_KEEP_LOCAL_COPY_OFF = 0,          /**< Specifies off the keeping local copy.*/
+       EMAIL_OPTION_KEEP_LOCAL_COPY_ON  = 1,          /**< Specifies on the keeping local copy.*/
+};
+
+/**
+* This enumeration specifies the request of delivery report.
+*/
+enum
+{
+       EMAIL_OPTION_REQ_DELIVERY_RECEIPT_OFF = 0,     /**< Specifies off the requesting delivery receipt.*/
+       EMAIL_OPTION_REQ_DELIVERY_RECEIPT_ON  = 1,     /**< Specifies on the requesting delivery receipt.*/
+};
+
+/**
+* This enumeration specifies the request of read receipt.
+*/
+enum
+{
+       EMAIL_OPTION_REQ_READ_RECEIPT_OFF = 0,         /**< Specifies off the requesting read receipt.*/
+       EMAIL_OPTION_REQ_READ_RECEIPT_ON  = 1,         /**< Specifies on the requesting read receipt.*/
+};
+
+/**
+* This enumeration specifies the blocking of address.
+*/
+enum
+{
+       EMAIL_OPTION_BLOCK_ADDRESS_OFF   = 0,          /**< Specifies off the blocking by address.*/
+       EMAIL_OPTION_BLOCK_ADDRESS_ON    = 1,          /**< Specifies on the blocking by address.*/
+};
+
+/**
+* This enumeration specifies the blocking of subject.
+*/
+enum
+{
+       EMAIL_OPTION_BLOCK_SUBJECT_OFF   = 0,          /**< Specifies off the blocking by subject.*/
+       EMAIL_OPTION_BLOCK_SUBJECT_ON    = 1,          /**< Specifies on the blocking by subject.*/
+};
+
+enum
+{
+       EMAIL_LIST_TYPE_UNREAD           = -3,
+       EMAIL_LIST_TYPE_LOCAL            = -2,
+       EMAIL_LIST_TYPE_THREAD           = -1,
+       EMAIL_LIST_TYPE_NORMAL           = 0
+};
+
+/**
+* This enumeration specifies the mailbox sync type.
+*/
+enum
+{
+       EMAIL_MAILBOX_ALL                = -1,         /**< All mailboxes.*/
+       EMAIL_MAILBOX_FROM_SERVER        = 0,          /**< Mailboxes from server. */
+       EMAIL_MAILBOX_FROM_LOCAL         = 1,          /**< Mailboxes from local. */
+};
+
+typedef enum
+{
+       APPEND_BODY                    = 1,
+       UPDATE_MAILBOX,
+       UPDATE_ATTACHMENT_INFO,
+       UPDATE_FLAG,
+       UPDATE_SAVENAME,
+       UPDATE_EXTRA_FLAG,
+       UPDATE_MAIL,
+       UPDATE_DATETIME,
+       UPDATE_FROM_CONTACT_INFO,
+       UPDATE_TO_CONTACT_INFO,
+       UPDATE_ALL_CONTACT_NAME,
+       UPDATE_ALL_CONTACT_INFO,
+       UPDATE_STICKY_EXTRA_FLAG,
+       UPDATE_PARTIAL_BODY_DOWNLOAD,
+       UPDATE_MEETING,
+       UPDATE_SEEN_FLAG_OF_THREAD,
+       UPDATE_FILE_PATH,
+} email_mail_change_type_t; // Should be moved intenal types */
+
+
+/**
+* This enumeration specifies the address type.
+*/
+typedef enum
+{
+       EMAIL_ADDRESS_TYPE_FROM          = 1,          /**< Specifies the from address.*/
+       EMAIL_ADDRESS_TYPE_TO,                         /**< Specifies the to recipient address.*/
+       EMAIL_ADDRESS_TYPE_CC,                         /**< Specifies the cc recipient address.*/
+       EMAIL_ADDRESS_TYPE_BCC,                        /**< Specifies the bcc recipient address.*/
+       EMAIL_ADDRESS_TYPE_REPLY,                      /**< Specifies the reply recipient address.*/
+       EMAIL_ADDRESS_TYPE_RETURN,                     /**< Specifies the return recipient address.*/
+} email_address_type_t;
+
+/**
+ * This enumeration specifies the search type for searching mailbox.
+ */
+typedef enum
+{
+       EMAIL_MAILBOX_SEARCH_KEY_TYPE_SUBJECT,         /**< The search key is for searching subject.*/
+       EMAIL_MAILBOX_SEARCH_KEY_TYPE_FROM,            /**< The search key is for searching sender address.*/
+       EMAIL_MAILBOX_SEARCH_KEY_TYPE_BODY,            /**< The search key is for searching body.*/
+       EMAIL_MAILBOX_SEARCH_KEY_TYPE_TO,              /**< The search key is for searching recipient address.*/
+} email_mailbox_search_key_t;
+
+/**
+ * This enumeration specifies the download status of mail body.
+ */
+
+typedef enum
+{
+       EMAIL_BODY_DOWNLOAD_STATUS_NONE = 0,
+       EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED = 1,
+       EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED = 2,
+} email_body_download_status_t;
+
+/**
+ * This enumeration specifies the moving type.
+ */
+typedef enum
+{
+       EMAIL_MOVED_BY_COMMAND = 0,
+       EMAIL_MOVED_BY_MOVING_THREAD,
+       EMAIL_MOVED_AFTER_SENDING,
+       EMAIL_MOVED_CANCELATION_MAIL
+} email_move_type;
+
+/**
+ * This enumeration specifies the deletion type.
+ */
+typedef enum
+{
+       EMAIL_DELETED_BY_COMMAND = 0,
+       EMAIL_DELETED_BY_OVERFLOW,
+       EMAIL_DELETED_BY_DELETING_THREAD,
+       EMAIL_DELETED_BY_MOVING_TO_OTHER_ACCOUNT,
+       EMAIL_DELETED_AFTER_SENDING,
+       EMAIL_DELETED_FROM_SERVER,
+} email_delete_type;
+
+/**
+ * This enumeration specifies the status field type.
+ */
+typedef enum
+{
+       EMAIL_FLAGS_SEEN_FIELD = 0,
+       EMAIL_FLAGS_DELETED_FIELD,
+       EMAIL_FLAGS_FLAGGED_FIELD,
+       EMAIL_FLAGS_ANSWERED_FIELD,
+       EMAIL_FLAGS_RECENT_FIELD,
+       EMAIL_FLAGS_DRAFT_FIELD,
+       EMAIL_FLAGS_FORWARDED_FIELD,
+       EMAIL_FLAGS_FIELD_COUNT,
+} email_flags_field_type;
+
+typedef enum {
+       EMAIL_FLAG_NONE                  = 0,
+       EMAIL_FLAG_FLAGED                = 1,
+       EMAIL_FLAG_TASK_STATUS_CLEAR     = 2,
+       EMAIL_FLAG_TASK_STATUS_COMPLETE  = 3,
+       EMAIL_FLAG_TASK_STATUS_ACTIVE    = 4,
+} email_flagged_type;
+
+typedef enum {
+       EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO       =  1,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_UID              =  2,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_BCC              =  7,  /* string type */
+       EMAIL_SEARCH_FILTER_TYPE_CC               =  9,  /* string type */
+       EMAIL_SEARCH_FILTER_TYPE_FROM             = 10,  /* string type */
+       EMAIL_SEARCH_FILTER_TYPE_KEYWORD          = 11,  /* string type */
+       EMAIL_SEARCH_FILTER_TYPE_SUBJECT          = 13,  /* string type */
+       EMAIL_SEARCH_FILTER_TYPE_TO               = 15,  /* string type */
+       EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER      = 16,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER     = 17,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE = 20,  /* time type */
+       EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON     = 21,  /* time type */
+       EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE  = 22,  /* time type */
+       EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED   = 26,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED    = 28,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT      = 30,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED     = 32,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT     = 34,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN       = 36,  /* integer type */
+       EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       = 43,  /* string type */
+} email_search_filter_type;
+
+typedef enum {
+       EMAIL_DRM_TYPE_NONE                       = 0,
+       EMAIL_DRM_TYPE_OBJECT                     = 1,
+       EMAIL_DRM_TYPE_RIGHT                      = 2,
+       EMAIL_DRM_TYPE_DCF                        = 3
+} email_drm_type;
+
+typedef enum {
+       EMAIL_DRM_METHOD_NONE                     = 0,
+       EMAIL_DRM_METHOD_FL                       = 1,
+       EMAIL_DRM_METHOD_CD                       = 2,
+       EMAIL_DRM_METHOD_SSD                      = 3,
+       EMAIL_DRM_METHOD_SD                       = 4
+} email_drm_method;
+
+typedef enum {
+       EMAIL_CANCELED_BY_USER                    = 0,
+       EMAIL_CANCELED_BY_MDM                     = 1,
+} email_cancelation_type;
+
+typedef enum {
+       EMAIL_MAIL_ATTRIBUTE_MAIL_ID                 =  0,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID              =  1,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_MAILBOX_ID              =  2,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_MAILBOX_NAME            =  3,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_MAILBOX_TYPE            =  4,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_SUBJECT                 =  5,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_DATE_TIME               =  6,  /* datetime type */
+       EMAIL_MAIL_ATTRIBUTE_SERVER_MAIL_STATUS      =  7,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_SERVER_MAILBOX_NAME     =  8,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_SERVER_MAIL_ID          =  9,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_MESSAGE_ID              = 10,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_REFERENCE_MAIL_ID       = 11,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FROM                    = 12,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_TO                      = 13,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_CC                      = 14,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_BCC                     = 15,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS    = 16,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FILE_PATH_PLAIN         = 17,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_FILE_PATH_HTML          = 18,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_FILE_SIZE               = 19,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_SEEN_FIELD        = 20,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_DELETED_FIELD     = 21,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_FLAGGED_FIELD     = 22,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_ANSWERED_FIELD    = 23,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_RECENT_FIELD      = 24,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_DRAFT_FIELD       = 25,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_FLAGS_FORWARDED_FIELD   = 26,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_DRM_STATUS              = 27,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_PRIORITY                = 28,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS             = 29,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_LOCK_STATUS             = 30,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_REPORT_STATUS           = 31,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_ATTACHMENT_COUNT        = 32,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_INLINE_CONTENT_COUNT    = 33,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_THREAD_ID               = 34,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_THREAD_ITEM_COUNT       = 35,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_PREVIEW_TEXT            = 36,  /* string type */
+       EMAIL_MAIL_ATTRIBUTE_MEETING_REQUEST_STATUS  = 37,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_MESSAGE_CLASS           = 38,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_DIGEST_TYPE             = 39,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_SMIME_TYPE              = 40,  /* integer type */
+       EMAIL_MAIL_ATTRIBUTE_END                         
+} email_mail_attribute_type;
+
+typedef enum {
+       EMAIL_ADD_MY_ADDRESS_OPTION_DO_NOT_ADD            = 0,
+       EMAIL_ADD_MY_ADDRESS_OPTION_ALWAYS_ADD_TO_CC      = 1,
+       EMAIL_ADD_MY_ADDRESS_OPTION_ALWAYS_ADD_TO_BCC     = 2,
+} email_add_my_address_option_type;
+
+typedef enum {
+       EMAIL_MESSAGE_CLASS_UNSPECIFIED,
+       EMAIL_MESSAGE_CLASS_UNKNOWN,
+       EMAIL_MESSAGE_CLASS_NOTE,
+       EMAIL_MESSAGE_CLASS_NOTE_RULES_OF_TEMPLATE_MICROSOFT,
+       EMAIL_MESSAGE_CLASS_NOTE_SMIME,
+       EMAIL_MESSAGE_CLASS_NOTE_SMIME_MULTIPART_SIGNED,
+       EMAIL_MESSAGE_CLASS_NOTIFICATION_MEETING,
+       EMAIL_MESSAGE_CLASS_OCTEL_VOICE,
+       EMAIL_MESSAGE_CLASS_SCHEDULE_MEETING_REQUEST,
+       EMAIL_MESSAGE_CLASS_SCHEDULE_MEETING_CANCELED,
+       EMAIL_MESSAGE_CLASS_SCHEDULE_MEETING_RESP_POS,
+       EMAIL_MESSAGE_CLASS_SCHEDULE_MEETING_RESP_TENT,
+       EMAIL_MESSAGE_CLASS_SCHEDULE_MEETING_RESP_NEG,
+       EMAIL_MESSAGE_CLASS_POST,
+       EMAIL_MESSAGE_CLASS_INFO_PATH_FORM,
+       EMAIL_MESSAGE_CLASS_VOICE_NOTES,
+       EMAIL_MESSAGE_CLASS_SHARING,
+       EMAIL_MESSAGE_CLASS_NOTE_EXCHANGE_ACTIVE_SYNC_REMOTE_WIPE_CONFIRMATION,
+       EMAIL_MESSAGE_CLASS_VOICE_MAIL,
+       EMAIL_MESSAGE_CLASS_SMS,
+       EMAIL_MESSAGE_CLASS_IRM_MESSAGE                                         = 0x00100000,
+       EMAIL_MESSAGE_CLASS_SMART_REPLY                                         = 0x01000000,
+       EMAIL_MESSAGE_CLASS_SMART_FORWARD                                       = 0x02000000,
+       EMAIL_MESSAGE_CLASS_REPORT_NOT_READ_REPORT                              = 0x10000000,
+       EMAIL_MESSAGE_CLASS_REPORT_READ_REPORT                                  = 0x20000000,
+       EMAIL_MESSAGE_CLASS_REPORT_NON_DELIVERY_RECEIPT                         = 0x40000000,
+       EMAIL_MESSAGE_CLASS_REPORT_DELIVERY_RECEIPT                             = 0x80000000,
+} email_message_class; 
+
+typedef enum{
+       EMAIL_SMIME_NONE                          = 0,   /* Not use smime */
+       EMAIL_SMIME_SIGNED,                               
+       EMAIL_SMIME_ENCRYPTED,
+       EMAIL_SMIME_SIGNED_AND_ENCRYPTED,
+} email_smime_type;
+
+typedef enum {
+       CIPHER_TYPE_DES3                          = 0,
+       CIPHER_TYPE_DES,
+       CIPHER_TYPE_RC2_128,
+       CIPHER_TYPE_RC2_64,
+       CIPHER_TYPE_RC2_40,                       
+} email_cipher_type;
+
+typedef enum {
+       DIGEST_TYPE_SHA1                          = 0,
+       DIGEST_TYPE_MD5,
+} email_digest_type;
+
+/*****************************************************************************/
+/*  Data Structures                                                          */
+/*****************************************************************************/
+
+/**
+ * This structure is used to save mail time.
+ */
+typedef struct
+{
+       unsigned short year;                         /**< Specifies the Year.*/
+       unsigned short month;                        /**< Specifies the Month.*/
+       unsigned short day;                          /**< Specifies the Day.*/
+       unsigned short hour;                         /**< Specifies the Hour.*/
+       unsigned short minute;                       /**< Specifies the Minute.*/
+       unsigned short second;                       /**< Specifies the Second.*/
+} email_datetime_t DEPRECATED;
+
+/**
+ * This structure is used to save the options.
+ */
+typedef struct
+{
+       email_mail_priority_t              priority;               /**< Specifies the prority. 1=high 3=normal 5=low.*/
+       int                                keep_local_copy;        /**< Specifies the saving save a copy after sending.*/
+       int                                req_delivery_receipt;   /**< Specifies the request of delivery report. 0=off 1=on*/
+       int                                req_read_receipt;       /**< Specifies the request of read receipt. 0=off 1=on*/
+       int                                download_limit;         /**< Specifies the limit of size for downloading.*/
+       int                                block_address;          /**< Specifies the blocking of address. 0=off 1=on*/
+       int                                block_subject;          /**< Specifies the blocking of subject. 0=off 1=on*/
+       char                              *display_name_from;      /**< Specifies the display name of from.*/
+       int                                reply_with_body;        /**< Specifies the replying with body 0=off 1=on*/
+       int                                forward_with_files;     /**< Specifies the fowarding with files 0=off 1=on*/
+       int                                add_myname_card;        /**< Specifies the adding name card 0=off 1=on*/
+       int                                add_signature;          /**< Specifies the adding signature 0=off 1=on*/
+       char                              *signature;              /**< Specifies the signature*/
+       email_add_my_address_option_type   add_my_address_to_bcc;  /**< Specifies whether cc or bcc field should be always filled with my address. */
+} email_option_t;
+
+/**
+ * This structure is used to save the information of email account.
+ */
+typedef struct
+{
+       /* General account information */
+       int                          account_id;                               /**< Account id  */
+       char                        *account_name;                             /**< Account name */
+       int                          account_svc_id;                           /**< AccountSvc priv data: Specifies id from account-svc */
+       int                          sync_status;                              /**< Sync Status. SYNC_STATUS_FINISHED, SYNC_STATUS_SYNCING, SYNC_STATUS_HAVE_NEW_MAILS */
+       int                          sync_disabled;                            /**< If this attriube is set as true, email-service will not synchronize this account. */
+       int                          default_mail_slot_size;
+       char                        *logo_icon_path;                           /**< account logo icon (used by account svc and email app) */
+       void                        *user_data;                                /**< binary user data */
+       int                                          user_data_length;                         /**< user data length */
+
+       /* User information */
+       char                            *user_display_name;                        /**< User's display */
+       char                            *user_email_address;                       /**< User's email address */
+       char                        *reply_to_address;                         /**< Email address for reply */
+       char                        *return_address;                           /**< Email address for error from server*/
+
+       /* Configuration for incoming server */
+       email_account_server_t       incoming_server_type;                     /**< Incoming server type */
+       char                        *incoming_server_address;                  /**< Incoming server address */
+       int                          incoming_server_port_number;              /**< Incoming server port number */
+       char                        *incoming_server_user_name;                /**< Incoming server user name */
+       char                        *incoming_server_password;                 /**< Incoming server password */
+       int                          incoming_server_secure_connection;        /**< Does incoming server requires secured connection? */
+
+       /* Options for incoming server */
+       email_imap4_retrieval_mode_t retrieval_mode;                           /**< Retrieval mode : EMAIL_IMAP4_RETRIEVAL_MODE_NEW or EMAIL_IMAP4_RETRIEVAL_MODE_ALL */
+       int                          keep_mails_on_pop_server_after_download;  /**< Keep mails on POP server after download */
+       int                          check_interval;                           /**< Specifies the interval for checking new mail periodically */
+       int                          auto_download_size;                       /**< Specifies the size for auto download in bytes. -1 means entire mails body */
+
+       /* Configuration for outgoing server */
+       email_account_server_t       outgoing_server_type;                     /**< Outgoing server type */
+       char                                    *outgoing_server_address;                  /**< Outgoing server address */
+       int                                              outgoing_server_port_number;              /**< Outgoing server port number */
+       char                                    *outgoing_server_user_name;                /**< Outgoing server user name */
+       char                                    *outgoing_server_password;                 /**< Outgoing server password */
+       int                                      outgoing_server_secure_connection;        /**< Does outgoing server requires secured connection? */
+       int                                      outgoing_server_need_authentication;      /**< Does outgoing server requires authentication? */
+       int                                      outgoing_server_use_same_authenticator;   /**< Use same authenticator for outgoing server */
+
+
+       /* Options for outgoing server */
+       email_option_t                   options;
+
+       /* Authentication Options */
+       int                              pop_before_smtp;                          /**< POP before SMTP Authentication */
+       int                          incoming_server_requires_apop;            /**< APOP authentication */
+
+       /* S/MIME Options */
+       email_smime_type             smime_type;                               /**< Specifies the smime type 0=Normal 1=Clear signed 2=encrypted 3=Signed + encrypted */
+       char                        *certificate_path;                         /**< Specifies the certificate path of private*/
+       email_cipher_type            cipher_type;                              /**< Specifies the encryption algorithm*/
+       email_digest_type            digest_type;                              /**< Specifies the digest algorithm*/
+} email_account_t;
+
+/**
+ * This structure is used to save the information of certificate
+ */
+
+typedef struct 
+{
+       int certificate_id;
+       int issue_year;
+       int issue_month;
+       int issue_day;
+       int expiration_year;
+       int expiration_month;
+       int expiration_day;
+       char *issue_organization_name;
+       char *email_address;
+       char *subject_str;
+       char *filepath;
+} email_certificate_t;
+
+/**
+ * This structure is used to save the information of email server.
+ */
+
+typedef struct
+{
+       int                         configuration_id;      /**< Specifies the id of configuration.*/
+       email_account_server_t      protocol_type;         /**< Specifies the type of configuration.*/
+       char                       *server_addr;           /**< Specifies the address of configuration.*/
+       int                         port_number;           /**< Specifies the port number of configuration.*/
+       int                         security_type;         /**< Specifies the security such as SSL.*/
+       int                         auth_type;             /**< Specifies the authentication type of configuration.*/
+} email_protocol_config_t;
+
+typedef struct
+{
+       char                       *service_name;           /**< Specifies the name of service.*/
+       int                         authname_format;        /**< Specifies the type of user name for authentication.*/
+       int                         protocol_conf_count;    /**< Specifies count of protocol configurations.*/
+       email_protocol_config_t    *protocol_config_array;  /**< Specifies array of protocol configurations.*/
+} email_server_info_t;
+
+typedef struct
+{
+       int   mailbox_type;
+       char  mailbox_name[MAILBOX_NAME_LENGTH];
+} email_mailbox_type_item_t;
+
+/**
+ * This structure is contains the Mail information.
+ */
+
+typedef struct
+{
+       int                   mail_id;                 /**< Specifies the Mail ID.*/
+       int                   account_id;              /**< Specifies the Account ID.*/
+       int                   mailbox_id;              /**< Specifies the Mailbox ID.*/
+       email_mailbox_type_e  mailbox_type;            /**< Specifies the mailbox type of the mail. */
+       char                 *subject;                 /**< Specifies the subject.*/
+       time_t                date_time;               /**< Specifies the Date time.*/
+       int                   server_mail_status;      /**< Specifies the Whether sever mail or not.*/
+       char                 *server_mailbox_name;     /**< Specifies the server mailbox.*/
+       char                 *server_mail_id;          /**< Specifies the Server Mail ID.*/
+       char                 *message_id;              /**< Specifies the message id */
+       int                   reference_mail_id;       /**< Specifies the reference mail id */
+       char                 *full_address_from;       /**< Specifies the From address.*/
+       char                 *full_address_reply;      /**< Specifies the Reply to address */
+       char                 *full_address_to;         /**< Specifies the To address.*/
+       char                 *full_address_cc;         /**< Specifies the CC address.*/
+       char                 *full_address_bcc;        /**< Specifies the BCC address*/
+       char                 *full_address_return;     /**< Specifies the return Path*/
+       char                 *email_address_sender;    /**< Specifies the email address of sender.*/
+       char                 *email_address_recipient; /**< Specifies the email address of recipients.*/
+       char                 *alias_sender;            /**< Specifies the alias of sender. */
+       char                 *alias_recipient;         /**< Specifies the alias of recipients. */
+       int                   body_download_status;    /**< Specifies the Text downloaded or not.*/
+       char                 *file_path_plain;         /**< Specifies the path of text mail body.*/
+       char                 *file_path_html;          /**< Specifies the path of HTML mail body.*/
+       char                 *file_path_mime_entity;   /**< Specifies the path of MIME entity. */
+       int                   mail_size;               /**< Specifies the Mail Size.*/
+       char                  flags_seen_field;        /**< Specifies the seen flags*/
+       char                  flags_deleted_field;     /**< Specifies the deleted flags*/
+       char                  flags_flagged_field;     /**< Specifies the flagged flags*/
+       char                  flags_answered_field;    /**< Specifies the answered flags*/
+       char                  flags_recent_field;      /**< Specifies the recent flags*/
+       char                  flags_draft_field;       /**< Specifies the draft flags*/
+       char                  flags_forwarded_field;   /**< Specifies the forwarded flags*/
+       int                   DRM_status;              /**< Has the mail DRM content? (1 : true, 0 : false) */
+       email_mail_priority_t priority;                /**< Specifies the priority of the mail.*/
+       email_mail_status_t   save_status;             /**< Specifies the save status*/
+       int                   lock_status;             /**< Specifies the mail is locked*/
+       email_mail_report_t   report_status;           /**< Specifies the Mail Report.*/
+       int                   attachment_count;        /**< Specifies the attachment count. */
+       int                   inline_content_count;    /**< Specifies the inline content count. */
+       int                   thread_id;               /**< Specifies the thread id for thread view. */
+       int                   thread_item_count;       /**< Specifies the item count of specific thread. */
+       char                 *preview_text;            /**< Specifies the preview body. */
+       email_mail_type_t     meeting_request_status;  /**< Specifies the status of meeting request. */
+       int                   message_class;           /**< Specifies the class of message for EAS. */ /* email_message_class */
+       email_digest_type     digest_type;             /**< Specifies the digest algorithm*/
+       email_smime_type      smime_type;              /**< Specifies the SMIME type. */
+} email_mail_data_t;
+
+/**
+ * This structure is contains information for displaying mail list.
+ */
+typedef struct
+{
+       int                   mail_id;                                            /**< Specifies the mail id.*/
+       int                   account_id;                                         /**< Specifies the account id.*/
+       int                   mailbox_id;                                         /**< Specifies the mailbox id.*/
+       char                  full_address_from[STRING_LENGTH_FOR_DISPLAY];       /**< Specifies the full from email address.*/
+       char                  email_address_sender[MAX_EMAIL_ADDRESS_LENGTH];     /**< Specifies the sender email address.*/
+       char                  email_address_recipient[STRING_LENGTH_FOR_DISPLAY]; /**< Specifies the recipients email address.*/
+       char                  subject[STRING_LENGTH_FOR_DISPLAY];                 /**< Specifies the subject.*/
+       int                   body_download_status;                               /**< Specifies the text donwloaded or not.*/
+       time_t                date_time;                                          /**< Specifies the date time.*/
+       char                  flags_seen_field;                                   /**< Specifies the seen flags*/
+       char                  flags_deleted_field;                                /**< Specifies the deleted flags*/
+       char                  flags_flagged_field;                                /**< Specifies the flagged flags*/
+       char                  flags_answered_field;                               /**< Specifies the answered flags*/
+       char                  flags_recent_field;                                 /**< Specifies the recent flags*/
+       char                  flags_draft_field;                                  /**< Specifies the draft flags*/
+       char                  flags_forwarded_field;                              /**< Specifies the forwarded flags*/
+       int                   DRM_status;                                         /**< Has the mail DRM content? (1 : true, 0 : false) */
+       email_mail_priority_t priority;                                           /**< Specifies the priority of Mails.*/ /* email_mail_priority_t*/
+       email_mail_status_t   save_status;                                        /**< Specifies the save status*/ /* email_mail_status_t */
+       int                   lock_status;                                        /**< Specifies the locked*/
+       email_mail_report_t   report_status;                                      /**< Specifies the mail report.*/ /* email_mail_report_t */
+       int                   attachment_count;                                   /**< Specifies the attachment count. */
+       int                   inline_content_count;                               /**< Specifies the inline content count. */
+       char                  preview_text[MAX_PREVIEW_TEXT_LENGTH];              /**< text for preview body*/
+       int                   thread_id;                                          /**< thread id for thread view*/
+       int                   thread_item_count;                                  /**< item count of specific thread */
+       email_mail_type_t     meeting_request_status;                             /**< Whether the mail is a meeting request or not */ /* email_mail_type_t */
+       int                   message_class;                                      /**< Specifies the message class */ /* email_message_class */
+       email_smime_type      smime_type;                                         /**< Specifies the smime type */ /* email_smime_type */
+} email_mail_list_item_t;
+
+/**
+ * This structure is used to save the filtering structure.
+ */
+typedef struct
+{
+       int                  account_id;          /**< Specifies the account ID.*/
+       int                  filter_id;           /**< Specifies the filtering ID.*/
+       email_rule_type_t    type;                /**< Specifies the filtering type.*/
+       char                *value;               /**< Specifies the filtering value.*/
+       email_rule_action_t  faction;             /**< Specifies the action type for filtering.*/
+       int                  target_mailbox_id;   /**< Specifies the mail box if action type means move.*/
+       int                  flag1;               /**< Specifies the activation.*/
+       int                  flag2;               /**< Reserved.*/
+} email_rule_t;
+
+/**
+ * This structure is used to save the information of mail flag.
+ */
+typedef struct
+{
+       unsigned int  seen           : 1; /**< Specifies the read email.*/
+       unsigned int  deleted        : 1; /**< Reserved.*/
+       unsigned int  flagged        : 1; /**< Specifies the flagged email.*/
+       unsigned int  answered       : 1; /**< Reserved.*/
+       unsigned int  recent         : 1; /**< Reserved.*/
+       unsigned int  draft          : 1; /**< Specifies the draft email.*/
+       unsigned int  attachment_count : 1; /**< Reserved.*/
+       unsigned int  forwarded      : 1; /**< Reserved.*/
+       unsigned int  sticky         : 1; /**< Sticky flagged mails cannot be deleted */
+} email_mail_flag_t /* DEPRECATED */;
+
+
+/**
+ * This structure is used to save the information of mail extra flag.
+ */
+typedef struct
+{
+       unsigned int  priority         : 3; /**< Specifies the mail priority.
+                                           The value is greater than or equal to EMAIL_MAIL_PRIORITY_HIGH.
+                                           The value is less than or equal to EMAIL_MAIL_PRIORITY_LOW.*/
+       unsigned int  status           : 4; /**< Specifies the mail status.
+                                              The value is a value of enumeration email_mail_status_t.*/
+       unsigned int  noti             : 1; /**< Specifies the notified mail.*/
+       unsigned int  lock             : 1; /**< Specifies the locked mail.*/
+       unsigned int  report           : 2; /**< Specifies the MDN/DSN mail. The value is a value of enumeration email_mail_report_t.*/
+       unsigned int  drm              : 1; /**< Specifies the drm mail.*/
+       unsigned int  text_download_yn : 2; /**< body download y/n*/
+} email_extra_flag_t DEPRECATED;
+
+/**
+ * This structure is used to save the information of attachment.
+ */
+typedef struct
+{
+       int   attachment_id;
+       char *attachment_name;
+       char *attachment_path;
+       int   attachment_size;
+       int   mail_id;
+       int   account_id;
+       char  mailbox_id;
+       int   save_status;
+       int   drm_status;
+       int   inline_content_status;
+       char *attachment_mime_type; /**< Specifies the context mime type.*/
+} email_attachment_data_t;
+
+typedef struct
+{
+       int        offset_from_GMT;
+       char       standard_name[32];
+       struct tm  standard_time_start_date;
+       int        standard_bias;
+       char       daylight_name[32];
+       struct tm  daylight_time_start_date;
+       int        daylight_bias;
+} email_time_zone_t;
+
+typedef struct
+{
+       int                        mail_id;                                        /**< Specifies the mail id of meeting request on DB. This is the primary key. */
+       email_meeting_response_t   meeting_response;                               /**< Specifies the meeting response. */
+       struct tm                  start_time;
+       struct tm                  end_time;
+       char                      *location;                                       /**< Specifies the location of meeting. Maximum length of this string is 32768 */
+       char                      *global_object_id;                               /**< Specifies the object id. */
+       email_time_zone_t          time_zone;
+} email_meeting_request_t;
+
+/**
+ * This structure is used to save the information of sender list with unread/total mail counts
+ */
+typedef struct
+{
+       char *address;         /**< Specifies the address of a sender.*/
+       char *display_name;    /**< Specifies a display name. This may be one of contact name, alias in original mail and email address of sender. (Priority order : contact name, alias, email address) */
+       int   unread_count;    /**< Specifies the number of unread mails received from sender address*/
+       int   total_count;     /**< Specifies the total number of  mails which are received from sender address*/
+} email_sender_list_t /* DEPRECATED */;
+
+
+/**
+ * This structure is used to save the information of mailbox.
+ */
+typedef struct
+{
+       int                   mailbox_id;                 /**< Unique id on mailbox table.*/
+       char                 *mailbox_name;               /**< Specifies the path of mailbox.*/
+       email_mailbox_type_e  mailbox_type;               /**< Specifies the type of mailbox */
+       char                 *alias;                      /**< Specifies the display name of mailbox.*/
+       int                   unread_count;               /**< Specifies the unread mail count in the mailbox.*/
+       int                   total_mail_count_on_local;  /**< Specifies the total number of mails in the mailbox in the local DB.*/
+       int                   total_mail_count_on_server; /**< Specifies the total number of mails in the mailbox in the mail server.*/
+       int                   local;                      /**< Specifies the local mailbox.*/
+       int                   account_id;                 /**< Specifies the account ID for mailbox.*/
+       int                   mail_slot_size;             /**< Specifies how many mails can be stored in local mailbox.*/
+       int                   no_select;                  /**< Specifies the 'no_select' attribute from xlist.*/
+       time_t                last_sync_time;
+       int                   deleted_flag;               /**< Specifies whether mailbox is deleted.*/
+} email_mailbox_t;
+
+typedef struct
+{
+       email_address_type_t  address_type;
+       char                 *address;
+       char                 *display_name;
+       int                   storage_type;
+       int                   contact_id;
+} email_address_info_t;
+
+typedef struct
+{
+       GList *from;
+       GList *to;
+       GList *cc;
+       GList *bcc;
+} email_address_info_list_t;
+
+typedef struct
+{
+       int     address_type;           /* type of mail (sender : 0, recipient : 1)*/
+       int     address_count;  /*  The number of email addresses */
+       char  **address_list;   /*  strings of email addresses */
+} email_email_address_list_t;
+
+
+typedef struct _email_search_filter_t {
+       email_search_filter_type search_filter_type; /* type of search filter */
+       union {
+               int            integer_type_key_value;
+               time_t         time_type_key_value;
+               char          *string_type_key_value;
+       } search_filter_key_value;
+} email_search_filter_t;
+
+typedef enum {
+       EMAIL_LIST_FILTER_RULE_EQUAL                  = 0,
+       EMAIL_LIST_FILTER_RULE_NOT_EQUAL              = 1,
+       EMAIL_LIST_FILTER_RULE_LESS_THAN              = 2,
+       EMAIL_LIST_FILTER_RULE_GREATER_THAN           = 3,
+       EMAIL_LIST_FILTER_RULE_LESS_THAN_OR_EQUAL     = 4,
+       EMAIL_LIST_FILTER_RULE_GREATER_THAN_OR_EQUAL  = 5,
+       EMAIL_LIST_FILTER_RULE_INCLUDE                = 6,
+       EMAIL_LIST_FILTER_RULE_IN                     = 7,
+       EMAIL_LIST_FILTER_RULE_NOT_IN                 = 8
+} email_list_filter_rule_type_t;
+
+typedef enum {
+       EMAIL_CASE_SENSITIVE                          = 0,
+       EMAIL_CASE_INSENSITIVE                        = 1,
+} email_list_filter_case_sensitivity_t;
+
+typedef union {
+       int                                    integer_type_value;
+       char                                  *string_type_value;
+       time_t                                 datetime_type_value;
+} email_mail_attribute_value_t;
+
+typedef struct {
+       email_list_filter_rule_type_t          rule_type;
+       email_mail_attribute_type              target_attribute;
+       email_mail_attribute_value_t           key_value;
+       email_list_filter_case_sensitivity_t   case_sensitivity;
+} email_list_filter_rule_t;
+
+typedef enum {
+       EMAIL_LIST_FILTER_ITEM_RULE                     = 0,
+       EMAIL_LIST_FILTER_ITEM_OPERATOR                 = 1,
+} email_list_filter_item_type_t;
+
+typedef enum {
+       EMAIL_LIST_FILTER_OPERATOR_AND                  = 0,
+       EMAIL_LIST_FILTER_OPERATOR_OR                   = 1,
+       EMAIL_LIST_FILTER_OPERATOR_LEFT_PARENTHESIS     = 2,
+       EMAIL_LIST_FILTER_OPERATOR_RIGHT_PARENTHESIS    = 3
+} email_list_filter_operator_type_t;
+
+typedef struct {
+       email_list_filter_item_type_t          list_filter_item_type;
+
+       union {
+               email_list_filter_rule_t           rule;
+               email_list_filter_operator_type_t  operator_type;
+       } list_filter_item;
+
+} email_list_filter_t;
+
+typedef enum {
+       EMAIL_SORT_ORDER_ASCEND                             = 0,
+       EMAIL_SORT_ORDER_DESCEND                            = 1
+} email_list_filter_sort_order_t;
+
+typedef struct {
+       email_mail_attribute_type              target_attribute;
+       bool                                   force_boolean_check;
+       email_list_filter_sort_order_t         sort_order;
+} email_list_sorting_rule_t;
+
+/*****************************************************************************/
+/*  For Active Sync                                                          */
+/*****************************************************************************/
+
+#define VCONFKEY_EMAIL_SERVICE_ACTIVE_SYNC_HANDLE "db/email_handle/active_sync_handle"
+#define EMAIL_ACTIVE_SYNC_NOTI                      "User.Email.ActiveSync"
+
+typedef enum
+{
+       ACTIVE_SYNC_NOTI_SEND_MAIL,                                   /*  a sending notification to ASE (active sync engine */
+       ACTIVE_SYNC_NOTI_SEND_SAVED,                                  /*  a sending notification to ASE (active sync engine), All saved mails should be sent */
+       ACTIVE_SYNC_NOTI_SEND_REPORT,                                 /*  a sending notification to ASE (active sync engine), report should be sen */
+       ACTIVE_SYNC_NOTI_SYNC_HEADER,                                 /*  a sync header - download mails from server. */
+                                                                  /*  It is depended on account/s flag1 field whether it excutes downloading header only or downloading header + body */
+                                                                  /*  downloading option : 0 is subject only, 1 is text body, 2 is normal */
+       ACTIVE_SYNC_NOTI_DOWNLOAD_BODY,                               /*  a downloading body notification to AS */
+       ACTIVE_SYNC_NOTI_DOWNLOAD_ATTACHMENT,                         /*  a downloading attachment notification to AS */
+       ACTIVE_SYNC_NOTI_VALIDATE_ACCOUNT,                            /*  a account validating notification to AS */
+       ACTIVE_SYNC_NOTI_CANCEL_JOB,                                  /*  a cancling job notification to AS */
+       ACTIVE_SYNC_NOTI_SEARCH_ON_SERVER,                            /*  a searching on server notification to AS */
+       ACTIVE_SYNC_NOTI_CLEAR_RESULT_OF_SEARCH_ON_SERVER,            /*  a notification for clearing result of search on server to AS */
+       ACTIVE_SYNC_NOTI_EXPUNGE_MAILS_DELETED_FLAGGED,               /*  a notification to expunge deleted flagged mails */
+       ACTIVE_SYNC_NOTI_RESOLVE_RECIPIENT,                           /*  a notification to get the resolve recipients */
+       ACTIVE_SYNC_NOTI_VALIDATE_CERTIFICATE,                        /*  a notification to validate certificate */
+       ACTIVE_SYNC_NOTI_ADD_MAILBOX,                                 /*  a notification to add mailbox */
+       ACTIVE_SYNC_NOTI_RENAME_MAILBOX,                              /*  a notification to rename mailbox */
+       ACTIVE_SYNC_NOTI_DELETE_MAILBOX,                              /*  a notification to delete mailbox */
+       ACTIVE_SYNC_NOTI_CANCEL_SENDING_MAIL,                         /*  a notification to cancel a sending mail */
+       ACTIVE_SYNC_NOTI_DELETE_MAILBOX_EX,                           /*  a notification to delete multiple mailboxes */
+       ACTIVE_SYNC_NOTI_SEND_MAIL_WITH_DOWNLOADING_OF_ORIGINAL_MAIL, /*  a notification to send a mail with downloading attachment of original mail */
+}      eactivesync_noti_t;
+
+typedef union
+{
+       struct _send_mail
+       {
+               int             handle;
+               int             account_id;
+               int             mail_id;
+       } send_mail;
+
+       struct _send_mail_saved
+       {/*  not defined ye */
+               int             handle;
+               int             account_id;
+       } send_mail_saved;
+
+       struct _send_report
+       {/*  not defined ye */
+               int             handle;
+               int             account_id;
+       } send_report;
+
+       struct _sync_header
+       {
+               int             handle;
+               int             account_id;
+               int             mailbox_id;
+       } sync_header;
+
+       struct _download_body
+       {
+               int             handle;
+               int             account_id;
+               int             mail_id;
+               int             with_attachment;      /*  0: without attachments, 1: with attachment */
+       } download_body;
+
+       struct _download_attachment
+       {
+               int             handle;
+               int             account_id;
+               int             mail_id;
+               int             attachment_order;
+       } download_attachment;
+
+       struct _cancel_job
+       {
+               int             account_id;
+               int             handle;               /*  job handle to be canceled. this value is issued by email-service. */
+               int             cancel_type;
+       } cancel_job;
+
+       struct _validate_account
+       {/*  not defined yet */
+               int             handle;
+               int             account_id;
+       } validate_account;
+
+       struct _search_mail_on_server
+       {
+               int                    handle;
+               int                    account_id;
+               int                                        mailbox_id;
+               email_search_filter_t *search_filter_list;
+               int                    search_filter_count;
+       } search_mail_on_server;
+
+       struct _clear_result_of_search_mail_on_server
+       {
+               int                    handle;
+               int                    account_id;
+       } clear_result_of_search_mail_on_server;
+
+       struct _expunge_mails_deleted_flagged
+       {
+               int                    handle;
+               int                    mailbox_id;
+               int                    on_server;
+       } expunge_mails_deleted_flagged;
+
+       struct _get_resolve_recipients
+       {
+               int                     handle;
+               int                     account_id;
+               char                   *email_address;
+       } get_resolve_recipients;
+
+       struct _validate_certificate
+       {
+               int                     handle;
+               int                     account_id;
+               char                   *email_address;
+       } validate_certificate;
+
+       struct _add_mailbox
+       {
+               int                     handle;
+               int                     account_id;
+               char                   *mailbox_path;
+               char                   *mailbox_alias;
+       } add_mailbox;
+
+       struct _rename_mailbox
+       {
+               int                     handle;
+               int                     account_id;
+               int                     mailbox_id;
+               char                   *mailbox_name;
+               char                   *mailbox_alias;
+       } rename_mailbox;
+
+       struct _delete_mailbox
+       {
+               int                     handle;
+               int                     account_id;
+               int                     mailbox_id;
+       } delete_mailbox;
+
+       struct _cancel_sending_mail
+       {
+               int                     mail_id;
+       } cancel_sending_mail;
+
+       struct _delete_mailbox_ex
+       {
+               int                     handle;
+               int                     account_id;
+               int                    *mailbox_id_array;
+               int                     mailbox_id_count;
+               int                     on_server;
+       } delete_mailbox_ex;
+
+       struct _send_mail_with_downloading_attachment_of_original_mail
+       {
+               int                     handle;
+               int                     mail_id;
+       } send_mail_with_downloading_attachment_of_original_mail;
+} ASNotiData;
+
+/*  types for noti string */
+typedef enum
+{
+       EMAIL_CONVERT_STRUCT_TYPE_MAIL_LIST_ITEM,      /** specifies email_mail_list_t */
+} email_convert_struct_type_e;
+
+/* Tasks */
+typedef enum {
+       /* Sync tasks */
+       /* Sync tasks for account - from 11000 */
+       EMAIL_SYNC_TASK_ADD_ACCOUNT                                             = 11010,
+       EMAIL_SYNC_TASK_DELETE_ACCOUNT                                          = 11020,
+       EMAIL_SYNC_TASK_UPDATE_ACCOUNT                                          = 11030,
+       EMAIL_SYNC_TASK_GET_ACCOUNT                                             = 11040,
+       EMAIL_SYNC_TASK_GET_ACCOUNT_LIST                                        = 11050,
+       EMAIL_SYNC_TASK_BACKUP_ACCOUNTS                                         = 11060,
+       EMAIL_SYNC_TASK_RESTORE_ACCOUNTS                                        = 11070,
+       EMAIL_SYNC_TASK_GET_PASSWORD_LENGTH_OF_ACCOUNT                          = 11090,
+
+       /* Sync tasks for mailbox - from 12000 */
+       EMAIL_SYNC_TASK_GET_MAILBOX_COUNT                                       = 12010,
+       EMAIL_SYNC_TASK_GET_MAILBOX_LIST                                        = 12020,
+       EMAIL_SYNC_TASK_GET_SUB_MAILBOX_LIST                                    = 12030,
+       EMAIL_SYNC_TASK_SET_MAIL_SLOT_SIZE                                      = 12040,
+       EMAIL_SYNC_TASK_SET_MAILBOX_TYPE                                        = 12050,
+       EMAIL_SYNC_TASK_SET_LOCAL_MAILBOX                                       = 12060,
+
+       /* Sync tasks for mail - from 13000 */
+       EMAIL_SYNC_GET_ATTACHMENT                                               = 13010,
+       EMAIL_SYNC_CLEAR_RESULT_OF_SEARCH_MAIL_ON_SERVER                        = 13020,
+
+       /* Sync tasks for mail thread - from 14000 */
+
+       /* Sync tasks for rule - from 15000 */
+
+       /* Sync tasks for etc - from 16000 */
+
+       /* Async tasks */
+       EMAIL_ASYNC_TASK_BOUNDARY                                               = 60000,
+       /* Async tasks for account - from 61000 */
+       EMAIL_ASYNC_TASK_VALIDATE_ACCOUNT                                       = 61010,
+       EMAIL_ASYNC_TASK_ADD_ACCOUNT_WITH_VALIDATION                            = 61020,
+
+       /* Async tasks for mailbox - from 62000 */
+       EMAIL_ASYNC_TASK_ADD_MAILBOX                                            = 62010,
+       EMAIL_ASYNC_TASK_DELETE_MAILBOX                                         = 62020,
+       EMAIL_ASYNC_TASK_RENAME_MAILBOX                                         = 62030,
+       EMAIL_ASYNC_TASK_DOWNLOAD_IMAP_MAILBOX_LIST                             = 62040,
+       EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX                                      = 62050,
+
+       /* Async tasks for mail - from 63000 */
+       EMAIL_ASYNC_TASK_ADD_MAIL                                               = 63010,
+       EMAIL_ASYNC_TASK_ADD_READ_RECEIPT                                       = 63020,
+
+       EMAIL_ASYNC_TASK_UPDATE_MAIL                                            = 63030,
+
+       EMAIL_ASYNC_TASK_DELETE_MAIL                                            = 63040,
+       EMAIL_ASYNC_TASK_DELETE_ALL_MAIL                                        = 63050,
+       EMAIL_ASYNC_TASK_EXPUNGE_MAILS_DELETED_FLAGGED                          = 63060,
+
+       EMAIL_ASYNC_TASK_MOVE_MAIL                                              = 63070,
+       EMAIL_ASYNC_TASK_MOVE_ALL_MAIL                                          = 63080,
+       EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT               = 63090,
+
+       EMAIL_ASYNC_TASK_SET_FLAGS_FIELD                                        = 63300,
+
+       EMAIL_ASYNC_TASK_DOWNLOAD_MAIL_LIST                                     = 63400,
+       EMAIL_ASYNC_TASK_DOWNLOAD_BODY                                          = 63410,
+       EMAIL_ASYNC_TASK_DOWNLOAD_ATTACHMENT                                    = 63420,
+
+       EMAIL_ASYNC_TASK_SEND_MAIL                                              = 63500,
+       EMAIL_ASYNC_TASK_SEND_SAVED                                             = 63510,
+       EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL = 63520,
+
+       EMAIL_ASYNC_TASK_SEARCH_MAIL_ON_SERVER                                  = 63600,
+
+       /* Async tasks for mail thread - from 64000 */
+       EMAIL_ASYNC_TASK_MOVE_THREAD_TO_MAILBOX                                 = 64010,
+       EMAIL_ASYNC_TASK_DELETE_THREAD                                          = 64020,
+       EMAIL_ASYNC_TASK_MODIFY_SEEN_FLAG_OF_THREAD                             = 64030,
+
+       /* Async tasks for rule - from 65000 */
+
+       /* Async tasks for etc - from 66000 */
+
+} email_task_type_t;
+
+typedef enum
+{
+       EMAIL_TASK_STATUS_UNUSED                   = 0,
+       EMAIL_TASK_STATUS_WAIT                     = 1,
+       EMAIL_TASK_STATUS_STARTED                  = 2,
+       EMAIL_TASK_STATUS_IN_PROGRESS              = 3,
+       EMAIL_TASK_STATUS_FINISHED                 = 4,
+       EMAIL_TASK_STATUS_FAILED                   = 5,
+       EMAIL_TASK_STATUS_CANCELED                 = 6,
+} email_task_status_type_t;
+
+typedef enum
+{
+       EMAIL_TASK_PRIORITY_UNUSED                 = 0,
+       EMAIL_TASK_PRIORITY_SCHEDULED              = 1,
+       EMAIL_TASK_PRIORITY_LOW                    = 3,
+       EMAIL_TASK_PRIORITY_MID                    = 5,
+       EMAIL_TASK_PRIORITY_HIGH                   = 7,
+       EMAIL_TASK_PRIORITY_BACK_GROUND_TASK       = 9,
+} email_task_priority_t;
+/* Tasks */
+
+#ifdef __cplusplus
+}
+#endif
+
+/**
+* @} @}
+*/
+
+#endif /* __EMAIL_TYPES_H__ */
diff --git a/email-common-use/include/email-utilities.h b/email-common-use/include/email-utilities.h
new file mode 100755 (executable)
index 0000000..0472528
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+/*
+ * email-utilities.h
+ *
+ *  Created on: 2012. 3. 6.
+ *      Author: kyuho.jo@samsung.com
+ */
+
+#ifndef __EMAIL_UTILITIES_H__
+#define __EMAIL_UTILITIES_H__
+
+#include "email-types.h"
+#include "email-internal-types.h"
+#include "email-debug-log.h"
+#include "email-storage.h"
+
+INTERNAL_FUNC void* em_malloc(int len);
+INTERNAL_FUNC void* em_memdup(void* src, int len);
+INTERNAL_FUNC char* em_trim_left(char *str);
+INTERNAL_FUNC char* em_trim_right(char *str);
+INTERNAL_FUNC char* em_upper_string(char *str);
+INTERNAL_FUNC char* em_lower_string(char *str);
+INTERNAL_FUNC int   em_upper_path(char *path);
+
+INTERNAL_FUNC void  em_skip_whitespace(char *addr_str , char **pAddr);
+INTERNAL_FUNC char* em_skip_whitespace_without_strdup(char *source_string);
+INTERNAL_FUNC char* em_replace_all_string(char *source_string, char *old_string, char *new_string);
+INTERNAL_FUNC char* em_replace_string(char *source_string, char *old_string, char *new_string);
+INTERNAL_FUNC void  em_flush_memory();
+INTERNAL_FUNC int   em_get_file_name_from_file_path(char *input_source_file_path, char **output_file_name);
+INTERNAL_FUNC int   em_get_file_name_and_extension_from_file_path(char *input_source_file_path, char **output_file_name, char **output_extention);
+INTERNAL_FUNC char* em_get_extension_from_file_path(char *source_file_path, int *err_code);
+INTERNAL_FUNC int   em_get_encoding_type_from_file_path(const char *input_file_path, char **output_encoding_type);
+INTERNAL_FUNC int   em_get_content_type_from_extension_string(const char *extension_string, int *err_code);
+
+INTERNAL_FUNC int   em_verify_email_address(char *address, int without_bracket, int *err_code);
+INTERNAL_FUNC int   em_verify_email_address_of_mail_data(email_mail_data_t *mail_data, int without_bracket, int *err_code);
+INTERNAL_FUNC int   em_verify_email_address_of_mail_tbl(emstorage_mail_tbl_t *input_mail_tbl, int input_without_bracket);
+
+INTERNAL_FUNC int   em_find_pos_stripped_subject_for_thread_view(char *subject, char *stripped_subject, int stripped_subject_buffer_size);
+INTERNAL_FUNC int   em_find_tag_for_thread_view(char *subject, int *result);
+
+INTERNAL_FUNC int   em_encode_base64(char *src, unsigned long src_len, char **enc, unsigned long* enc_len, int *err_code);
+INTERNAL_FUNC int   em_decode_base64(unsigned char *enc_text, unsigned long enc_len, char **dec_text, unsigned long* dec_len, int *err_code);
+
+extern        char* strcasestr(__const char *__haystack, __const char *__needle) __THROW __attribute_pure__ __nonnull ((1, 2));
+
+INTERNAL_FUNC int   em_get_account_server_type_by_account_id(int account_id, email_account_server_t* account_server_type, int flag, int *error);
+
+INTERNAL_FUNC int   em_get_handle_for_activesync(int *handle, int *error);
+INTERNAL_FUNC int   em_send_notification_to_active_sync_engine(int subType, ASNotiData *data);
+
+#endif /* __EMAIL_UTILITIES_H__ */
diff --git a/email-common-use/include/tpl.h b/email-common-use/include/tpl.h
new file mode 100755 (executable)
index 0000000..51e19c5
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+Copyright (c) 2005-2010, Troy D. Hanson     http://tpl.sourceforge.net
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef TPL_H
+#define TPL_H 
+
+#include <stddef.h>     /* size_t */
+
+#ifdef __INTEL_COMPILER
+#include <tbb/tbbmalloc_proxy.h>
+#endif /* Intel Compiler efficient memcpy etc */
+
+#ifdef _MSC_VER
+typedef unsigned int uint32_t;
+#else
+#include <inttypes.h>   /* uint32_t */
+#endif
+
+#if defined __cplusplus
+extern "C" {
+#endif
+
+#ifdef _WIN32
+#ifdef TPL_EXPORTS
+#define TPL_API __declspec(dllexport)
+#else                                                  /*  */
+#ifdef TPL_NOLIB
+#define TPL_API
+#else
+#define TPL_API __declspec(dllimport)
+#endif /* TPL_NOLIB */
+#endif /* TPL_EXPORTS*/
+#else
+#define TPL_API __attribute__((visibility("default")))
+#endif
+
+/* bit flags (external) */
+#define TPL_FILE      (1 << 0)
+#define TPL_MEM       (1 << 1)
+#define TPL_PREALLOCD (1 << 2)
+#define TPL_EXCESS_OK (1 << 3)
+#define TPL_FD        (1 << 4)
+#define TPL_UFREE     (1 << 5)  
+#define TPL_DATAPEEK  (1 << 6)  
+#define TPL_FXLENS    (1 << 7)  
+#define TPL_GETSIZE   (1 << 8)
+/* do not add flags here without renumbering the internal flags! */
+
+/* flags for tpl_gather mode */
+#define TPL_GATHER_BLOCKING    1
+#define TPL_GATHER_NONBLOCKING 2
+#define TPL_GATHER_MEM         3
+
+/* Hooks for error logging, memory allocation functions and fatal */
+typedef int (tpl_print_fcn)(const char *fmt, ...);
+typedef void *(tpl_malloc_fcn)(size_t sz);
+typedef void *(tpl_realloc_fcn)(void *ptr, size_t sz);
+typedef void (tpl_free_fcn)(void *ptr);
+typedef void (tpl_fatal_fcn)(char *fmt, ...);
+
+typedef struct tpl_hook_t {
+    tpl_print_fcn *oops;
+    tpl_malloc_fcn *malloc;
+    tpl_realloc_fcn *realloc;
+    tpl_free_fcn *free;
+    tpl_fatal_fcn *fatal;
+    size_t gather_max;
+} tpl_hook_t;
+
+typedef struct tpl_node {
+    int type;
+    void *addr;
+    void *data;                  /* r:tpl_root_data*. A:tpl_atyp*. ow:szof type */
+    int num;                     /* length of type if its a C array */
+    size_t ser_osz;              /* serialization output size for subtree */
+    struct tpl_node *children;   /* my children; linked-list */
+    struct tpl_node *next,*prev; /* my siblings (next child of my parent) */
+    struct tpl_node *parent;     /* my parent */
+} tpl_node;
+
+/* used when un/packing 'B' type (binary buffers) */
+typedef struct tpl_bin {
+    void *addr;
+    uint32_t sz;
+} tpl_bin;
+
+/* for async/piecemeal reading of tpl images */
+typedef struct tpl_gather_t {
+    char *img;
+    int len;
+} tpl_gather_t;
+
+/* Callback used when tpl_gather has read a full tpl image */
+typedef int (tpl_gather_cb)(void *img, size_t sz, void *data);
+
+/* Prototypes */
+TPL_API tpl_node *tpl_map(char *fmt,...);       /* define tpl using format */
+TPL_API void tpl_free(tpl_node *r);             /* free a tpl map */
+TPL_API int tpl_pack(tpl_node *r, int i);       /* pack the n'th packable */
+TPL_API int tpl_unpack(tpl_node *r, int i);     /* unpack the n'th packable */
+TPL_API int tpl_dump(tpl_node *r, int mode, ...); /* serialize to mem/file */
+TPL_API int tpl_load(tpl_node *r, int mode, ...); /* set mem/file to unpack */
+TPL_API int tpl_Alen(tpl_node *r, int i);      /* array len of packable i */
+TPL_API char* tpl_peek(int mode, ...);         /* sneak peek at format string */
+TPL_API int tpl_gather( int mode, ...);        /* non-blocking image gather */
+TPL_API int tpl_jot(int mode, ...);            /* quick write a simple tpl */
+
+#if defined __cplusplus
+    }
+#endif
+
+#endif /* TPL_H */
+
diff --git a/email-common-use/tpl.c b/email-common-use/tpl.c
new file mode 100644 (file)
index 0000000..00d3d32
--- /dev/null
@@ -0,0 +1,2477 @@
+/*
+Copyright (c) 2005-2010, Troy D. Hanson     http://tpl.sourceforge.net
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#define TPL_VERSION 1.5
+
+static const char id[]="$Id: tpl.c 192 2009-04-24 10:35:30Z thanson $";
+
+
+#include <stdlib.h>  /* malloc */
+#include <stdarg.h>  /* va_list */
+#include <string.h>  /* memcpy, memset, strchr */
+#include <stdio.h>   /* printf (tpl_hook.oops default function) */
+
+#ifndef _WIN32
+#include <unistd.h>     /* for ftruncate */
+#else
+#include <io.h>
+#define ftruncate(x,y) _chsize(x,y)
+#endif
+#include <sys/types.h>  /* for 'open' */
+#include <sys/stat.h>   /* for 'open' */
+#include <fcntl.h>      /* for 'open' */
+#include <errno.h>
+#ifndef _WIN32
+#include <inttypes.h>   /* uint32_t, uint64_t, etc */
+#else
+typedef unsigned short ushort;
+typedef __int16 int16_t;
+typedef __int32 int32_t;
+typedef __int64 int64_t;
+typedef unsigned __int16 uint16_t;
+typedef unsigned __int32 uint32_t;
+typedef unsigned __int64 uint64_t;
+#endif
+
+
+#if ( defined __CYGWIN__ || defined __MINGW32__ || defined _WIN32 )
+#include "win/mman.h"   /* mmap */
+#else
+#include <sys/mman.h>   /* mmap */
+#endif
+
+#include "tpl.h"
+#include "email-debug-log.h"
+
+
+#define TPL_GATHER_BUFLEN 8192
+#define TPL_MAGIC "tpl"
+
+/* macro to add a structure to a doubly-linked list */
+#define DL_ADD(head,add)                                        \
+    do {                                                        \
+        if (head) {                                             \
+            (add)->prev = (head)->prev;                         \
+            (head)->prev->next = (add);                         \
+            (head)->prev = (add);                               \
+            (add)->next = NULL;                                 \
+        } else {                                                \
+            (head)=(add);                                       \
+            (head)->prev = (head);                              \
+            (head)->next = NULL;                                \
+        }                                                       \
+    } while (0);
+
+#define fatal_oom() tpl_hook.fatal("out of memory\n")
+
+/* bit flags (internal). preceded by the external flags in tpl.h */
+#define TPL_WRONLY         (1 << 9)  /* app has initiated tpl packing  */
+#define TPL_RDONLY         (1 << 10)  /* tpl was loaded (for unpacking) */
+#define TPL_XENDIAN        (1 << 11)  /* swap endianness when unpacking */
+#define TPL_OLD_STRING_FMT (1 << 12) /* tpl has strings in 1.2 format */
+
+/* values for the flags byte that appears after the magic prefix */
+#define TPL_SUPPORTED_BITFLAGS 3
+#define TPL_FL_BIGENDIAN   (1 << 0)
+#define TPL_FL_NULLSTRINGS (1 << 1)
+
+/* char values for node type */
+#define TPL_TYPE_ROOT   0
+#define TPL_TYPE_INT32  1
+#define TPL_TYPE_UINT32 2
+#define TPL_TYPE_BYTE   3
+#define TPL_TYPE_STR    4
+#define TPL_TYPE_ARY    5
+#define TPL_TYPE_BIN    6
+#define TPL_TYPE_DOUBLE 7
+#define TPL_TYPE_INT64  8
+#define TPL_TYPE_UINT64 9
+#define TPL_TYPE_INT16  10
+#define TPL_TYPE_UINT16 11
+#define TPL_TYPE_POUND  12
+
+/* error codes */
+#define ERR_NOT_MINSIZE        (-1)
+#define ERR_MAGIC_MISMATCH     (-2)
+#define ERR_INCONSISTENT_SZ    (-3)
+#define ERR_FMT_INVALID        (-4)
+#define ERR_FMT_MISSING_NUL    (-5)
+#define ERR_FMT_MISMATCH       (-6)
+#define ERR_FLEN_MISMATCH      (-7)
+#define ERR_INCONSISTENT_SZ2   (-8)
+#define ERR_INCONSISTENT_SZ3   (-9)
+#define ERR_INCONSISTENT_SZ4   (-10)
+#define ERR_UNSUPPORTED_FLAGS  (-11)
+
+/* access to A(...) nodes by index */
+typedef struct tpl_pidx {
+    struct tpl_node *node;
+    struct tpl_pidx *next,*prev;
+} tpl_pidx;
+
+/* A(...) node datum */
+typedef struct tpl_atyp {
+    uint32_t num;    /* num elements */
+    size_t sz;       /* size of each backbone's datum */
+    struct tpl_backbone *bb,*bbtail;
+    void *cur;
+} tpl_atyp;
+
+/* backbone to extend A(...) lists dynamically */
+typedef struct tpl_backbone {
+    struct tpl_backbone *next;
+    /* when this structure is malloc'd, extra space is alloc'd at the
+     * end to store the backbone "datum", and data points to it. */
+#if __STDC_VERSION__ < 199901
+    char *data;
+#else
+    char data[];
+#endif
+} tpl_backbone;
+
+/* mmap record */
+typedef struct tpl_mmap_rec {
+    int fd;
+    void *text;
+    size_t text_sz;
+} tpl_mmap_rec;
+
+/* root node datum */
+typedef struct tpl_root_data {
+    int flags;
+    tpl_pidx *pidx;
+    tpl_mmap_rec mmap;
+    char *fmt;
+    int *fxlens, num_fxlens;
+} tpl_root_data;
+
+/* node type to size mapping */
+struct tpl_type_t {
+    char c;
+    int sz;
+};
+
+
+/* Internal prototypes */
+static tpl_node *tpl_node_new(tpl_node *parent);
+static tpl_node *tpl_find_i(tpl_node *n, int i);
+static void *tpl_cpv(void *datav, void *data, size_t sz);
+static void *tpl_extend_backbone(tpl_node *n);
+static char *tpl_fmt(tpl_node *r);
+static void *tpl_dump_atyp(tpl_node *n, tpl_atyp* at, void *dv);
+static size_t tpl_ser_osz(tpl_node *n);
+static void tpl_free_atyp(tpl_node *n,tpl_atyp *atyp);
+static int tpl_dump_to_mem(tpl_node *r, void *addr, size_t sz);
+static int tpl_mmap_file(char *filename, tpl_mmap_rec *map_rec);
+static int tpl_mmap_output_file(char *filename, size_t sz, void **text_out);
+static int tpl_cpu_bigendian(void);
+static int tpl_needs_endian_swap(void *);
+static void tpl_byteswap(void *word, int len);
+static void tpl_fatal(char *fmt, ...);
+static int tpl_serlen(tpl_node *r, tpl_node *n, void *dv, size_t *serlen);
+static int tpl_unpackA0(tpl_node *r);
+static int tpl_oops(const char *fmt, ...);
+static int tpl_gather_mem( char *buf, size_t len, tpl_gather_t **gs, tpl_gather_cb *cb, void *data);
+static int tpl_gather_nonblocking( int fd, tpl_gather_t **gs, tpl_gather_cb *cb, void *data);
+static int tpl_gather_blocking(int fd, void **img, size_t *sz);
+static tpl_node *tpl_map_va(char *fmt, va_list ap);
+
+/* This is used internally to help calculate padding when a 'double'
+ * follows a smaller datatype in a structure. Normally under gcc
+ * on x86, d will be aligned at +4, however use of -malign-double
+ * causes d to be aligned at +8 (this is actually faster on x86).
+ * Also SPARC and x86_64 seem to align always on +8.
+ */
+struct tpl_double_alignment_detector {
+    char a;
+    double d;  /* some platforms align this on +4, others on +8 */
+};
+
+/* this is another case where alignment varies. mac os x/gcc was observed
+ * to align the int64_t at +4 under -m32 and at +8 under -m64 */
+struct tpl_int64_alignment_detector {
+    int i;
+    int64_t j;  /* some platforms align this on +4, others on +8 */
+};
+
+typedef struct {
+  size_t inter_elt_len; /* padded inter-element len; i.e. &a[1].field - &a[0].field */
+  tpl_node *iter_start_node; /* node to jump back to, as we start each new iteration */
+  size_t iternum; /* current iteration number (total req'd. iter's in n->num) */
+} tpl_pound_data;
+
+/* Hooks for customizing tpl mem alloc, error handling, etc. Set defaults. */
+tpl_hook_t tpl_hook = {
+    /* .oops =       */ tpl_oops,
+    /* .malloc =     */ malloc,
+    /* .realloc =    */ realloc,
+    /* .free =       */ free,
+    /* .fatal =      */ tpl_fatal,
+    /* .gather_max = */ 0 /* max tpl size (bytes) for tpl_gather */
+};
+
+static const char tpl_fmt_chars[] = "AS($)BiucsfIUjv#"; /* valid format chars */
+static const char tpl_S_fmt_chars[] = "iucsfIUjv#$()"; /* valid within S(...) */
+static const char tpl_datapeek_ok_chars[] = "iucsfIUjv"; /* valid in datapeek */
+static const struct tpl_type_t tpl_types[] = {
+    /* [TPL_TYPE_ROOT] =   */  {'r', 0},
+    /* [TPL_TYPE_INT32] =  */  {'i', sizeof(int32_t)},
+    /* [TPL_TYPE_UINT32] = */  {'u', sizeof(uint32_t)},
+    /* [TPL_TYPE_BYTE] =   */  {'c', sizeof(char)},
+    /* [TPL_TYPE_STR] =    */  {'s', sizeof(char*)},
+    /* [TPL_TYPE_ARY] =    */  {'A', 0},
+    /* [TPL_TYPE_BIN] =    */  {'B', 0},
+    /* [TPL_TYPE_DOUBLE] = */  {'f', 8}, /* not sizeof(double) as that varies */
+    /* [TPL_TYPE_INT64] =  */  {'I', sizeof(int64_t)},
+    /* [TPL_TYPE_UINT64] = */  {'U', sizeof(uint64_t)},
+    /* [TPL_TYPE_INT16] =  */  {'j', sizeof(int16_t)},
+    /* [TPL_TYPE_UINT16] = */  {'v', sizeof(uint16_t)},
+    /* [TPL_TYPE_POUND] =  */  {'#', 0},
+};
+
+/* default error-reporting function. Just writes to stderr. */
+static int tpl_oops(const char *fmt, ...) {
+       char buf[256];
+    va_list ap;
+    va_start(ap,fmt);
+/*    vfprintf(stderr,fmt,ap); */
+       snprintf(buf, sizeof(buf)-1, fmt, ap);
+       EM_DEBUG_EXCEPTION("%s", buf);
+    va_end(ap);
+    return 0;
+}
+
+
+static tpl_node *tpl_node_new(tpl_node *parent) {
+    tpl_node *n;
+    if ((n=tpl_hook.malloc(sizeof(tpl_node))) == NULL) {
+        fatal_oom();
+    }
+    n->addr=NULL;
+    n->data=NULL;
+    n->num=1;
+    n->ser_osz=0;
+    n->children=NULL;
+    n->next=NULL;
+    n->parent=parent;
+    return n;
+}
+
+/* Used in S(..) formats to pack several fields from a structure based on
+ * only the structure address. We need to calculate field addresses
+ * manually taking into account the size of the fields and intervening padding.
+ * The wrinkle is that double is not normally aligned on x86-32 but the
+ * -malign-double compiler option causes it to be. Double are aligned
+ * on Sparc, and apparently on 64 bit x86. We use a helper structure
+ * to detect whether double is aligned in this compilation environment.
+ */
+char *calc_field_addr(tpl_node *parent, int type,char *struct_addr, int ordinal) {
+    tpl_node *prev;
+    int offset;
+    int align_sz;
+
+    if (ordinal == 1) return struct_addr;  /* first field starts on structure address */
+
+    /* generate enough padding so field addr is divisible by it's align_sz. 4, 8, etc */
+    prev = parent->children->prev;
+    switch(type) {
+      case TPL_TYPE_DOUBLE:
+        align_sz = sizeof(struct tpl_double_alignment_detector) > 12 ? 8 : 4;
+        break;
+      case TPL_TYPE_INT64:
+      case TPL_TYPE_UINT64:
+        align_sz = sizeof(struct tpl_int64_alignment_detector) > 12 ? 8 : 4;
+        break;
+      default:
+        align_sz = tpl_types[type].sz;
+        break;
+    }
+    offset = ((uintptr_t)prev->addr - (uintptr_t)struct_addr)
+            + (tpl_types[prev->type].sz * prev->num);
+    offset = (offset + align_sz - 1) / align_sz * align_sz;
+    return struct_addr + offset;
+}
+
+TPL_API tpl_node *tpl_map(char *fmt,...) {
+  va_list ap;
+  tpl_node *tn;
+
+  va_start(ap,fmt);
+  tn = tpl_map_va(fmt, ap);
+  va_end(ap);
+  return tn;
+}
+
+static tpl_node *tpl_map_va(char *fmt, va_list ap) {
+    int lparen_level=0,expect_lparen=0,t=0,in_structure=0,ordinal=0;
+    int in_nested_structure=0;
+    char *c, *peek, *struct_addr=NULL, *struct_next;
+    tpl_node *root,*parent,*n=NULL,*preceding,*iter_start_node=NULL,
+             *struct_widest_node=NULL, *np; tpl_pidx *pidx;
+    tpl_pound_data *pd;
+    int *fxlens, num_fxlens, pound_num, pound_prod, applies_to_struct;
+    int contig_fxlens[10]; /* temp space for contiguous fxlens */
+    int num_contig_fxlens, i, j;
+    ptrdiff_t inter_elt_len=0; /* padded element length of contiguous structs in array */
+
+
+    root = tpl_node_new(NULL);
+    root->type = TPL_TYPE_ROOT;
+    root->data = (tpl_root_data*)tpl_hook.malloc(sizeof(tpl_root_data));
+    if (!root->data) fatal_oom();
+    memset((tpl_root_data*)root->data,0,sizeof(tpl_root_data));
+
+    /* set up root nodes special ser_osz to reflect overhead of preamble */
+    root->ser_osz =  sizeof(uint32_t); /* tpl leading length */
+    root->ser_osz += EM_SAFE_STRLEN(fmt) + 1;  /* fmt + NUL-terminator */
+    root->ser_osz += 4;                /* 'tpl' magic prefix + flags byte */
+
+    parent=root;
+
+    c=fmt;
+    while (*c != '\0') {
+        switch (*c) {
+            case 'c':
+            case 'i':
+            case 'u':
+            case 'j':
+            case 'v':
+            case 'I':
+            case 'U':
+            case 'f':
+                if      (*c=='c') t=TPL_TYPE_BYTE;
+                else if (*c=='i') t=TPL_TYPE_INT32;
+                else if (*c=='u') t=TPL_TYPE_UINT32;
+                else if (*c=='j') t=TPL_TYPE_INT16;
+                else if (*c=='v') t=TPL_TYPE_UINT16;
+                else if (*c=='I') t=TPL_TYPE_INT64;
+                else if (*c=='U') t=TPL_TYPE_UINT64;
+                else if (*c=='f') t=TPL_TYPE_DOUBLE;
+
+                if (expect_lparen) goto fail;
+                n = tpl_node_new(parent);
+                n->type = t;
+                if (in_structure) {
+                    if (ordinal == 1) {
+                      /* for S(...)# iteration. Apply any changes to case 's' too!!! */
+                      iter_start_node = n;
+                      struct_widest_node = n;
+                    }
+                    if (tpl_types[n->type].sz > tpl_types[struct_widest_node->type].sz) {
+                      struct_widest_node = n;
+                    }
+                    n->addr = calc_field_addr(parent,n->type,struct_addr,ordinal++);
+                } else n->addr = (void*)va_arg(ap,void*);
+                n->data = tpl_hook.malloc(tpl_types[t].sz);
+                if (!n->data) fatal_oom();
+                if (n->parent->type == TPL_TYPE_ARY)
+                    ((tpl_atyp*)(n->parent->data))->sz += tpl_types[t].sz;
+                DL_ADD(parent->children,n);
+                break;
+            case 's':
+                if (expect_lparen) goto fail;
+                n = tpl_node_new(parent);
+                n->type = TPL_TYPE_STR;
+                if (in_structure) {
+                    if (ordinal == 1) {
+                      iter_start_node = n; /* for S(...)# iteration */
+                      struct_widest_node = n;
+                    }
+                    if (tpl_types[n->type].sz > tpl_types[struct_widest_node->type].sz) {
+                      struct_widest_node = n;
+                    }
+                    n->addr = calc_field_addr(parent,n->type,struct_addr,ordinal++);
+                } else n->addr = (void*)va_arg(ap,void*);
+                n->data = tpl_hook.malloc(sizeof(char*));
+                if (!n->data) fatal_oom();
+                *(char**)(n->data) = NULL;
+                if (n->parent->type == TPL_TYPE_ARY)
+                    ((tpl_atyp*)(n->parent->data))->sz += sizeof(void*);
+                DL_ADD(parent->children,n);
+                break;
+            case '#':
+                /* apply a 'num' to preceding atom */
+                if (!parent->children) goto fail;
+                preceding = parent->children->prev; /* first child's prev is 'last child'*/
+                t = preceding->type;
+                applies_to_struct = (*(c-1) == ')') ? 1 : 0;
+                if (!applies_to_struct) {
+                  if (!(t == TPL_TYPE_BYTE   || t == TPL_TYPE_INT32 ||
+                        t == TPL_TYPE_UINT32 || t == TPL_TYPE_DOUBLE ||
+                        t == TPL_TYPE_UINT64 || t == TPL_TYPE_INT64 ||
+                        t == TPL_TYPE_UINT16 || t == TPL_TYPE_INT16 ||
+                        t == TPL_TYPE_STR )) goto fail;
+                }
+                /* count up how many contiguous # and form their product */
+                pound_prod=1;
+                num_contig_fxlens=0;
+                for(peek=c; *peek == '#'; peek++) {
+                  pound_num = va_arg(ap, int);
+                  if (pound_num < 1) {
+                    tpl_hook.fatal("non-positive iteration count %d\n", pound_num);
+                  }
+                  if (num_contig_fxlens >= (sizeof(contig_fxlens)/sizeof(contig_fxlens[0]))) {
+                    tpl_hook.fatal("contiguous # exceeds hardcoded limit\n");
+                  }
+                  contig_fxlens[num_contig_fxlens++] = pound_num;
+                  pound_prod *= pound_num;
+                }
+                /* increment c to skip contiguous # so its points to last one */
+                c = peek-1;
+                /* differentiate atom-# from struct-# by noting preceding rparen */
+                if (applies_to_struct) { /* insert # node to induce looping */
+                  n = tpl_node_new(parent);
+                  n->type = TPL_TYPE_POUND;
+                  n->num = pound_prod;
+                  n->data = tpl_hook.malloc(sizeof(tpl_pound_data));
+                  if (!n->data) fatal_oom();
+                  pd = (tpl_pound_data*)n->data;
+                  pd->inter_elt_len = inter_elt_len;
+                  pd->iter_start_node = iter_start_node;
+                  pd->iternum = 0;
+                  DL_ADD(parent->children,n);
+                  /* multiply the 'num' and data space on each atom in the structure */
+                  for(np = iter_start_node; np != n; np = np->next) {
+                    if (n->parent->type == TPL_TYPE_ARY) {
+                      ((tpl_atyp*)(n->parent->data))->sz +=
+                         tpl_types[np->type].sz * (np->num * (n->num - 1));
+                    }
+                    np->data = tpl_hook.realloc(np->data, tpl_types[np->type].sz *
+                                                          np->num * n->num);
+                    if (!np->data) fatal_oom();
+                    memset(np->data, 0, tpl_types[np->type].sz * np->num * n->num);
+                  }
+                } else { /* simple atom-# form does not require a loop */
+                  preceding->num = pound_prod;
+                  preceding->data = tpl_hook.realloc(preceding->data,
+                      tpl_types[t].sz * preceding->num);
+                  if (!preceding->data) fatal_oom();
+                  memset(preceding->data,0,tpl_types[t].sz * preceding->num);
+                  if (n->parent->type == TPL_TYPE_ARY) {
+                      ((tpl_atyp*)(n->parent->data))->sz += tpl_types[t].sz *
+                                                            (preceding->num-1);
+                  }
+                }
+                root->ser_osz += (sizeof(uint32_t) * num_contig_fxlens);
+
+                j = ((tpl_root_data*)root->data)->num_fxlens; /* before incrementing */
+                (((tpl_root_data*)root->data)->num_fxlens) += num_contig_fxlens;
+                num_fxlens = ((tpl_root_data*)root->data)->num_fxlens; /* new value */
+                fxlens = ((tpl_root_data*)root->data)->fxlens;
+                fxlens = tpl_hook.realloc(fxlens, sizeof(int) * num_fxlens);
+                if (!fxlens) fatal_oom();
+                ((tpl_root_data*)root->data)->fxlens = fxlens;
+                for(i=0; i < num_contig_fxlens; i++) fxlens[j++] = contig_fxlens[i];
+
+                break;
+            case 'B':
+                if (expect_lparen) goto fail;
+                if (in_structure) goto fail;
+                n = tpl_node_new(parent);
+                n->type = TPL_TYPE_BIN;
+                n->addr = (tpl_bin*)va_arg(ap,void*);
+                n->data = tpl_hook.malloc(sizeof(tpl_bin*));
+                if (!n->data) fatal_oom();
+                *((tpl_bin**)n->data) = NULL;
+                if (n->parent->type == TPL_TYPE_ARY)
+                    ((tpl_atyp*)(n->parent->data))->sz += sizeof(tpl_bin);
+                DL_ADD(parent->children,n);
+                break;
+            case 'A':
+                if (in_structure) goto fail;
+                n = tpl_node_new(parent);
+                n->type = TPL_TYPE_ARY;
+                DL_ADD(parent->children,n);
+                parent = n;
+                expect_lparen=1;
+                pidx = (tpl_pidx*)tpl_hook.malloc(sizeof(tpl_pidx));
+                if (!pidx) fatal_oom();
+                pidx->node = n;
+                pidx->next = NULL;
+                DL_ADD(((tpl_root_data*)(root->data))->pidx,pidx);
+                /* set up the A's tpl_atyp */
+                n->data = (tpl_atyp*)tpl_hook.malloc(sizeof(tpl_atyp));
+                if (!n->data) fatal_oom();
+                ((tpl_atyp*)(n->data))->num = 0;
+                ((tpl_atyp*)(n->data))->sz = 0;
+                ((tpl_atyp*)(n->data))->bb = NULL;
+                ((tpl_atyp*)(n->data))->bbtail = NULL;
+                ((tpl_atyp*)(n->data))->cur = NULL;
+                if (n->parent->type == TPL_TYPE_ARY)
+                    ((tpl_atyp*)(n->parent->data))->sz += sizeof(void*);
+                break;
+            case 'S':
+                if (in_structure) goto fail;
+                expect_lparen=1;
+                ordinal=1;  /* index upcoming atoms in S(..) */
+                in_structure=1+lparen_level; /* so we can tell where S fmt ends */
+                struct_addr = (char*)va_arg(ap,void*);
+                break;
+            case '$': /* nested structure */
+                if (!in_structure) goto fail;
+                expect_lparen=1;
+                in_nested_structure++;
+                break;
+            case ')':
+                lparen_level--;
+                if (lparen_level < 0) goto fail;
+                if (*(c-1) == '(') goto fail;
+                if (in_nested_structure) in_nested_structure--;
+                else if (in_structure && (in_structure-1 == lparen_level)) {
+                  /* calculate delta between contiguous structures in array */
+                  struct_next = calc_field_addr(parent, struct_widest_node->type,
+                                                struct_addr, ordinal++);
+                  inter_elt_len = struct_next - struct_addr;
+                  in_structure=0;
+                }
+                else parent = parent->parent; /* rparen ends A() type, not S() type */
+                break;
+            case '(':
+                if (!expect_lparen) goto fail;
+                expect_lparen=0;
+                lparen_level++;
+                break;
+            default:
+                tpl_hook.oops("unsupported option %c\n", *c);
+                goto fail;
+        }
+        c++;
+    }
+    if (lparen_level != 0) goto fail;
+
+    /* copy the format string, save for convenience */
+    ((tpl_root_data*)(root->data))->fmt = tpl_hook.malloc(EM_SAFE_STRLEN(fmt)+1);
+    if (((tpl_root_data*)(root->data))->fmt == NULL)
+        fatal_oom();
+    memcpy(((tpl_root_data*)(root->data))->fmt,fmt,EM_SAFE_STRLEN(fmt)+1);
+
+    return root;
+
+fail:
+    tpl_hook.oops("failed to parse %s\n", fmt);
+    tpl_free(root);
+    return NULL;
+}
+
+static int tpl_unmap_file( tpl_mmap_rec *mr) {
+
+    if ( munmap( mr->text, mr->text_sz ) == -1 ) {
+        tpl_hook.oops("Failed to munmap: %s\n", strerror(errno));
+    }
+    close(mr->fd);
+    mr->text = NULL;
+    mr->text_sz = 0;
+    return 0;
+}
+
+static void tpl_free_keep_map(tpl_node *r) {
+    int mmap_bits = (TPL_RDONLY|TPL_FILE);
+    int ufree_bits = (TPL_MEM|TPL_UFREE);
+    tpl_node *nxtc,*c;
+    int find_next_node=0,looking,i;
+    size_t sz;
+
+    /* For mmap'd files, or for 'ufree' memory images , do appropriate release */
+    if ((((tpl_root_data*)(r->data))->flags & mmap_bits) == mmap_bits) {
+        tpl_unmap_file( &((tpl_root_data*)(r->data))->mmap);
+    } else if ((((tpl_root_data*)(r->data))->flags & ufree_bits) == ufree_bits) {
+        tpl_hook.free( ((tpl_root_data*)(r->data))->mmap.text );
+    }
+
+    c = r->children;
+    if (c) {
+        while(c->type != TPL_TYPE_ROOT) {    /* loop until we come back to root node */
+            switch (c->type) {
+                case TPL_TYPE_BIN:
+                    /* free any binary buffer hanging from tpl_bin */
+                    if ( *((tpl_bin**)(c->data)) ) {
+                        if ( (*((tpl_bin**)(c->data)))->addr ) {
+                            tpl_hook.free( (*((tpl_bin**)(c->data)))->addr );
+                        }
+                        *((tpl_bin**)c->data) = NULL; /* reset tpl_bin */
+                    }
+                    find_next_node=1;
+                    break;
+                case TPL_TYPE_STR:
+                    /* free any packed (copied) string */
+                    for(i=0; i < c->num; i++) {
+                      char *str = ((char**)c->data)[i];
+                      if (str) {
+                        tpl_hook.free(str);
+                        ((char**)c->data)[i] = NULL;
+                      }
+                    }
+                    find_next_node=1;
+                    break;
+                case TPL_TYPE_INT32:
+                case TPL_TYPE_UINT32:
+                case TPL_TYPE_INT64:
+                case TPL_TYPE_UINT64:
+                case TPL_TYPE_BYTE:
+                case TPL_TYPE_DOUBLE:
+                case TPL_TYPE_INT16:
+                case TPL_TYPE_UINT16:
+                case TPL_TYPE_POUND:
+                    find_next_node=1;
+                    break;
+                case TPL_TYPE_ARY:
+                    c->ser_osz = 0; /* zero out the serialization output size */
+
+                    sz = ((tpl_atyp*)(c->data))->sz;  /* save sz to use below */
+                    tpl_free_atyp(c,c->data);
+
+                    /* make new atyp */
+                    c->data = (tpl_atyp*)tpl_hook.malloc(sizeof(tpl_atyp));
+                    if (!c->data) fatal_oom();
+                    ((tpl_atyp*)(c->data))->num = 0;
+                    ((tpl_atyp*)(c->data))->sz = sz;  /* restore bb datum sz */
+                    ((tpl_atyp*)(c->data))->bb = NULL;
+                    ((tpl_atyp*)(c->data))->bbtail = NULL;
+                    ((tpl_atyp*)(c->data))->cur = NULL;
+
+                    c = c->children;
+                    break;
+                default:
+                    tpl_hook.fatal("unsupported format character\n");
+                    break;
+            }
+
+            if (find_next_node) {
+                find_next_node=0;
+                looking=1;
+                while(looking) {
+                    if (c->next) {
+                        nxtc=c->next;
+                        c=nxtc;
+                        looking=0;
+                    } else {
+                        if (c->type == TPL_TYPE_ROOT) break; /* root node */
+                        else {
+                            nxtc=c->parent;
+                            c=nxtc;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    ((tpl_root_data*)(r->data))->flags = 0;  /* reset flags */
+}
+
+TPL_API void tpl_free(tpl_node *r) {
+    int mmap_bits = (TPL_RDONLY|TPL_FILE);
+    int ufree_bits = (TPL_MEM|TPL_UFREE);
+    tpl_node *nxtc,*c;
+    int find_next_node=0,looking,i;
+    tpl_pidx *pidx,*pidx_nxt;
+
+    /* For mmap'd files, or for 'ufree' memory images , do appropriate release */
+    if ((((tpl_root_data*)(r->data))->flags & mmap_bits) == mmap_bits) {
+        tpl_unmap_file( &((tpl_root_data*)(r->data))->mmap);
+    } else if ((((tpl_root_data*)(r->data))->flags & ufree_bits) == ufree_bits) {
+        tpl_hook.free( ((tpl_root_data*)(r->data))->mmap.text );
+    }
+
+    c = r->children;
+    if (c) {
+        while(c->type != TPL_TYPE_ROOT) {    /* loop until we come back to root node */
+            switch (c->type) {
+                case TPL_TYPE_BIN:
+                    /* free any binary buffer hanging from tpl_bin */
+                    if ( *((tpl_bin**)(c->data)) ) {
+                        if ( (*((tpl_bin**)(c->data)))->sz != 0 ) {
+                            tpl_hook.free( (*((tpl_bin**)(c->data)))->addr );
+                        }
+                        tpl_hook.free(*((tpl_bin**)c->data)); /* free tpl_bin */
+                    }
+                    tpl_hook.free(c->data);  /* free tpl_bin* */
+                    find_next_node=1;
+                    break;
+                case TPL_TYPE_STR:
+                    /* free any packed (copied) string */
+                    for(i=0; i < c->num; i++) {
+                      char *str = ((char**)c->data)[i];
+                      if (str) {
+                        tpl_hook.free(str);
+                        ((char**)c->data)[i] = NULL;
+                      }
+                    }
+                    tpl_hook.free(c->data);
+                    find_next_node=1;
+                    break;
+                case TPL_TYPE_INT32:
+                case TPL_TYPE_UINT32:
+                case TPL_TYPE_INT64:
+                case TPL_TYPE_UINT64:
+                case TPL_TYPE_BYTE:
+                case TPL_TYPE_DOUBLE:
+                case TPL_TYPE_INT16:
+                case TPL_TYPE_UINT16:
+                case TPL_TYPE_POUND:
+                    tpl_hook.free(c->data);
+                    find_next_node=1;
+                    break;
+                case TPL_TYPE_ARY:
+                    tpl_free_atyp(c,c->data);
+                    if (c->children) c = c->children; /* normal case */
+                    else find_next_node=1; /* edge case, handle bad format A() */
+                    break;
+                default:
+                    tpl_hook.fatal("unsupported format character\n");
+                    break;
+            }
+
+            if (find_next_node) {
+                find_next_node=0;
+                looking=1;
+                while(looking) {
+                    if (c->next) {
+                        nxtc=c->next;
+                        tpl_hook.free(c);
+                        c=nxtc;
+                        looking=0;
+                    } else {
+                        if (c->type == TPL_TYPE_ROOT) break; /* root node */
+                        else {
+                            nxtc=c->parent;
+                            tpl_hook.free(c);
+                            c=nxtc;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    /* free root */
+    for(pidx=((tpl_root_data*)(r->data))->pidx; pidx; pidx=pidx_nxt) {
+        pidx_nxt = pidx->next;
+        tpl_hook.free(pidx);
+    }
+    tpl_hook.free(((tpl_root_data*)(r->data))->fmt);
+    if (((tpl_root_data*)(r->data))->num_fxlens > 0) {
+        tpl_hook.free(((tpl_root_data*)(r->data))->fxlens);
+    }
+    tpl_hook.free(r->data);  /* tpl_root_data */
+    tpl_hook.free(r);
+}
+
+
+/* Find the i'th packable ('A' node) */
+static tpl_node *tpl_find_i(tpl_node *n, int i) {
+    int j=0;
+    tpl_pidx *pidx;
+    if (n->type != TPL_TYPE_ROOT) return NULL;
+    if (i == 0) return n;  /* packable 0 is root */
+    for(pidx=((tpl_root_data*)(n->data))->pidx; pidx; pidx=pidx->next) {
+        if (++j == i) return pidx->node;
+    }
+    return NULL;
+}
+
+static void *tpl_cpv(void *datav, void *data, size_t sz) {
+    if (sz>0) memcpy(datav,data,sz);
+    return (void*)((uintptr_t)datav + sz);
+}
+
+static void *tpl_extend_backbone(tpl_node *n) {
+    tpl_backbone *bb;
+    bb = (tpl_backbone*)tpl_hook.malloc(sizeof(tpl_backbone) +
+      ((tpl_atyp*)(n->data))->sz );  /* datum hangs on coattails of bb */
+    if (!bb) fatal_oom();
+#if __STDC_VERSION__ < 199901
+    bb->data = (char*)((uintptr_t)bb + sizeof(tpl_backbone));
+#endif
+    memset(bb->data,0,((tpl_atyp*)(n->data))->sz);
+    bb->next = NULL;
+    /* Add the new backbone to the tail, also setting head if necessary  */
+    if (((tpl_atyp*)(n->data))->bb == NULL) {
+        ((tpl_atyp*)(n->data))->bb = bb;
+        ((tpl_atyp*)(n->data))->bbtail = bb;
+    } else {
+        ((tpl_atyp*)(n->data))->bbtail->next = bb;
+        ((tpl_atyp*)(n->data))->bbtail = bb;
+    }
+
+    ((tpl_atyp*)(n->data))->num++;
+    return bb->data;
+}
+
+/* Get the format string corresponding to a given tpl (root node) */
+static char *tpl_fmt(tpl_node *r) {
+    return ((tpl_root_data*)(r->data))->fmt;
+}
+
+/* Get the fmt # lengths as a contiguous buffer of ints (length num_fxlens) */
+static int *tpl_fxlens(tpl_node *r, int *num_fxlens) {
+    *num_fxlens = ((tpl_root_data*)(r->data))->num_fxlens;
+    return ((tpl_root_data*)(r->data))->fxlens;
+}
+
+/* called when serializing an 'A' type node into a buffer which has
+ * already been set up with the proper space. The backbone is walked
+ * which was obtained from the tpl_atyp header passed in.
+ */
+static void *tpl_dump_atyp(tpl_node *n, tpl_atyp* at, void *dv) {
+    tpl_backbone *bb;
+    tpl_node *c;
+    void *datav;
+    uint32_t slen;
+    tpl_bin *binp;
+    char *strp;
+    tpl_atyp *atypp;
+    tpl_pound_data *pd;
+    int i;
+    size_t itermax;
+
+    /* handle 'A' nodes */
+    dv = tpl_cpv(dv,&at->num,sizeof(uint32_t));  /* array len */
+    for(bb=at->bb; bb; bb=bb->next) {
+        datav = bb->data;
+        c=n->children;
+        while(c) {
+            switch (c->type) {
+                case TPL_TYPE_BYTE:
+                case TPL_TYPE_DOUBLE:
+                case TPL_TYPE_INT32:
+                case TPL_TYPE_UINT32:
+                case TPL_TYPE_INT64:
+                case TPL_TYPE_UINT64:
+                case TPL_TYPE_INT16:
+                case TPL_TYPE_UINT16:
+                    dv = tpl_cpv(dv,datav,tpl_types[c->type].sz * c->num);
+                    datav = (void*)((uintptr_t)datav + tpl_types[c->type].sz * c->num);
+                    break;
+                case TPL_TYPE_BIN:
+                    /* dump the buffer length followed by the buffer */
+                    memcpy(&binp,datav,sizeof(tpl_bin*)); /* cp to aligned */
+                    slen = binp->sz;
+                    dv = tpl_cpv(dv,&slen,sizeof(uint32_t));
+                    dv = tpl_cpv(dv,binp->addr,slen);
+                    datav = (void*)((uintptr_t)datav + sizeof(tpl_bin*));
+                    break;
+                case TPL_TYPE_STR:
+                    /* dump the string length followed by the string */
+                    for(i=0; i < c->num; i++) {
+                      memcpy(&strp,datav,sizeof(char*)); /* cp to aligned */
+                      slen = strp ? (EM_SAFE_STRLEN(strp)+1) : 0;
+                      dv = tpl_cpv(dv,&slen,sizeof(uint32_t));
+                      if (slen > 1) dv = tpl_cpv(dv,strp,slen-1);
+                      datav = (void*)((uintptr_t)datav + sizeof(char*));
+                    }
+                    break;
+                case TPL_TYPE_ARY:
+                    memcpy(&atypp,datav,sizeof(tpl_atyp*)); /* cp to aligned */
+                    dv = tpl_dump_atyp(c,atypp,dv);
+                    datav = (void*)((uintptr_t)datav + sizeof(void*));
+                    break;
+                case TPL_TYPE_POUND:
+                    /* iterate over the preceding nodes */
+                    pd = (tpl_pound_data*)c->data;
+                    itermax = c->num;
+                    if (++(pd->iternum) < itermax) {
+                      c = pd->iter_start_node;
+                      continue;
+                    } else { /* loop complete. */
+                      pd->iternum = 0;
+                    }
+                    break;
+                default:
+                    tpl_hook.fatal("unsupported format character\n");
+                    break;
+            }
+            c=c->next;
+        }
+    }
+    return dv;
+}
+
+/* figure the serialization output size needed for tpl whose root is n*/
+static size_t tpl_ser_osz(tpl_node *n) {
+    tpl_node *c, *np;
+    size_t sz, itermax;
+    tpl_bin *binp;
+    char *strp;
+    tpl_pound_data *pd;
+    int i;
+
+    /* handle the root node ONLY (subtree's ser_osz have been bubbled-up) */
+    if (n->type != TPL_TYPE_ROOT) {
+        tpl_hook.fatal("internal error: tpl_ser_osz on non-root node\n");
+    }
+
+    sz = n->ser_osz;    /* start with fixed overhead, already stored */
+    c=n->children;
+    while (c) {
+        switch (c->type) {
+            case TPL_TYPE_BYTE:
+            case TPL_TYPE_DOUBLE:
+            case TPL_TYPE_INT32:
+            case TPL_TYPE_UINT32:
+            case TPL_TYPE_INT64:
+            case TPL_TYPE_UINT64:
+            case TPL_TYPE_INT16:
+            case TPL_TYPE_UINT16:
+                sz += tpl_types[c->type].sz * c->num;
+                break;
+            case TPL_TYPE_BIN:
+                sz += sizeof(uint32_t);  /* binary buf len */
+                memcpy(&binp,c->data,sizeof(tpl_bin*)); /* cp to aligned */
+                sz += binp->sz;
+                break;
+            case TPL_TYPE_STR:
+                for(i=0; i < c->num; i++) {
+                  sz += sizeof(uint32_t);  /* string len */
+                  memcpy(&strp,&((char**)c->data)[i],sizeof(char*)); /* cp to aligned */
+                  sz += strp ? EM_SAFE_STRLEN(strp) : 0;
+                }
+                break;
+            case TPL_TYPE_ARY:
+                sz += sizeof(uint32_t);  /* array len */
+                sz += c->ser_osz;        /* bubbled-up child array ser_osz */
+                break;
+            case TPL_TYPE_POUND:
+                /* iterate over the preceding nodes */
+                itermax = c->num;
+                pd = (tpl_pound_data*)c->data;
+                if (++(pd->iternum) < itermax) {
+                  for(np=pd->iter_start_node; np != c; np = np->next) {
+                     np->data = (char*)(np->data) +
+                                (tpl_types[np->type].sz * np->num);
+                  }
+                  c = pd->iter_start_node;
+                  continue;
+                } else { /* loop complete. */
+                  pd->iternum = 0;
+                  for(np=pd->iter_start_node; np != c; np = np->next) {
+                     np->data = (char*)(np->data) - ((itermax-1) *
+                                                     tpl_types[np->type].sz *
+                                                     np->num);
+                  }
+                }
+                break;
+            default:
+                tpl_hook.fatal("unsupported format character\n");
+                break;
+        }
+        c=c->next;
+    }
+    return sz;
+}
+
+
+TPL_API int tpl_dump(tpl_node *r, int mode, ...) {
+    va_list ap;
+    char *filename, *bufv;
+    void **addr_out,*buf, *pa_addr;
+    int fd,rc=0;
+    size_t sz,*sz_out, pa_sz;
+
+    if (((tpl_root_data*)(r->data))->flags & TPL_RDONLY) {  /* unusual */
+        tpl_hook.oops("error: tpl_dump called for a loaded tpl\n");
+        return -1;
+    }
+
+    sz = tpl_ser_osz(r); /* compute the size needed to serialize  */
+
+    va_start(ap,mode);
+    if (mode & TPL_FILE) {
+        filename = va_arg(ap,char*);
+        fd = tpl_mmap_output_file(filename, sz, &buf);
+        if (fd == -1) rc = -1;
+        else {
+            rc = tpl_dump_to_mem(r,buf,sz);
+            if (msync(buf,sz,MS_SYNC) == -1) {
+                tpl_hook.oops("msync failed on fd %d: %s\n", fd, strerror(errno));
+            }
+            if (munmap(buf, sz) == -1) {
+                tpl_hook.oops("munmap failed on fd %d: %s\n", fd, strerror(errno));
+            }
+            close(fd);
+        }
+    } else if (mode & TPL_FD) {
+        fd = va_arg(ap, int);
+        if ( (buf = tpl_hook.malloc(sz)) == NULL) fatal_oom();
+        tpl_dump_to_mem(r,buf,sz);
+        bufv = buf;
+        do {
+            rc = write(fd,bufv,sz);
+            if (rc > 0) {
+                sz -= rc;
+                bufv += rc;
+            } else if (rc == -1) {
+                if (errno == EINTR || errno == EAGAIN) continue;
+                tpl_hook.oops("error writing to fd %d: %s\n", fd, strerror(errno));
+                free(buf);
+                return -1;
+            }
+        } while (sz > 0);
+        free(buf);
+        rc = 0;
+    } else if (mode & TPL_MEM) {
+        if (mode & TPL_PREALLOCD) { /* caller allocated */
+          pa_addr = (void*)va_arg(ap, void*);
+          pa_sz = va_arg(ap, size_t);
+          if (pa_sz < sz) {
+              tpl_hook.oops("tpl_dump: buffer too small, need %d bytes\n", sz);
+              return -1;
+          }
+          rc=tpl_dump_to_mem(r,pa_addr,sz);
+        } else { /* we allocate */
+          addr_out = (void**)va_arg(ap, void*);
+          sz_out = va_arg(ap, size_t*);
+          if ( (buf = tpl_hook.malloc(sz)) == NULL) fatal_oom();
+          *sz_out = sz;
+          *addr_out = buf;
+          rc=tpl_dump_to_mem(r,buf,sz);
+        }
+    } else if (mode & TPL_GETSIZE) {
+        sz_out = va_arg(ap, size_t*);
+        *sz_out = sz;
+    } else {
+        tpl_hook.oops("unsupported tpl_dump mode %d\n", mode);
+        rc=-1;
+    }
+    va_end(ap);
+    return rc;
+}
+
+/* This function expects the caller to have set up a memory buffer of
+ * adequate size to hold the serialized tpl. The sz parameter must be
+ * the result of tpl_ser_osz(r).
+ */
+static int tpl_dump_to_mem(tpl_node *r,void *addr,size_t sz) {
+    uint32_t slen, sz32;
+    int *fxlens, num_fxlens, i;
+    void *dv;
+    char *fmt,flags;
+    tpl_node *c, *np;
+    tpl_pound_data *pd;
+    size_t itermax;
+
+    fmt = tpl_fmt(r);
+    flags = 0;
+    if (tpl_cpu_bigendian()) flags |= TPL_FL_BIGENDIAN;
+    if (strchr(fmt,'s')) flags |= TPL_FL_NULLSTRINGS;
+    sz32 = sz;
+
+    dv = addr;
+    dv = tpl_cpv(dv,TPL_MAGIC,3);         /* copy tpl magic prefix */
+    dv = tpl_cpv(dv,&flags,1);            /* copy flags byte */
+    dv = tpl_cpv(dv,&sz32,sizeof(uint32_t));/* overall length (inclusive) */
+    dv = tpl_cpv(dv,fmt,EM_SAFE_STRLEN(fmt)+1);   /* copy format with NUL-term */
+    fxlens = tpl_fxlens(r,&num_fxlens);
+    dv = tpl_cpv(dv,fxlens,num_fxlens*sizeof(uint32_t));/* fmt # lengths */
+
+    /* serialize the tpl content, iterating over direct children of root */
+    c = r->children;
+    while (c) {
+        switch (c->type) {
+            case TPL_TYPE_BYTE:
+            case TPL_TYPE_DOUBLE:
+            case TPL_TYPE_INT32:
+            case TPL_TYPE_UINT32:
+            case TPL_TYPE_INT64:
+            case TPL_TYPE_UINT64:
+            case TPL_TYPE_INT16:
+            case TPL_TYPE_UINT16:
+                dv = tpl_cpv(dv,c->data,tpl_types[c->type].sz * c->num);
+                break;
+            case TPL_TYPE_BIN:
+                slen = (*(tpl_bin**)(c->data))->sz;
+                dv = tpl_cpv(dv,&slen,sizeof(uint32_t));  /* buffer len */
+                dv = tpl_cpv(dv,(*(tpl_bin**)(c->data))->addr,slen); /* buf */
+                break;
+            case TPL_TYPE_STR:
+                for(i=0; i < c->num; i++) {
+                  char *str = ((char**)c->data)[i];
+                  slen = str ? EM_SAFE_STRLEN(str)+1 : 0;
+                  dv = tpl_cpv(dv,&slen,sizeof(uint32_t));  /* string len */
+                  if (slen>1) dv = tpl_cpv(dv,str,slen-1); /*string*/
+                }
+                break;
+            case TPL_TYPE_ARY:
+                dv = tpl_dump_atyp(c,(tpl_atyp*)c->data,dv);
+                break;
+            case TPL_TYPE_POUND:
+                 pd = (tpl_pound_data*)c->data;
+                 itermax = c->num;
+                 if (++(pd->iternum) < itermax) {
+
+                   /* in start or midst of loop. advance data pointers. */
+                   for(np=pd->iter_start_node; np != c; np = np->next) {
+                     np->data = (char*)(np->data) +
+                                (tpl_types[np->type].sz * np->num);
+                   }
+                   /* do next iteration */
+                   c = pd->iter_start_node;
+                   continue;
+
+                 } else { /* loop complete. */
+
+                   /* reset iteration index and addr/data pointers. */
+                   pd->iternum = 0;
+                   for(np=pd->iter_start_node; np != c; np = np->next) {
+                     np->data = (char*)(np->data) - ((itermax-1) *
+                                                     tpl_types[np->type].sz *
+                                                     np->num);
+                   }
+
+                 }
+                 break;
+            default:
+                tpl_hook.fatal("unsupported format character\n");
+                break;
+        }
+        c = c->next;
+    }
+
+    return 0;
+}
+
+static int tpl_cpu_bigendian() {
+   unsigned i = 1;
+   char *c;
+   c = (char*)&i;
+   return (c[0] == 1 ? 0 : 1);
+}
+
+
+/*
+ * algorithm for sanity-checking a tpl image:
+ * scan the tpl whilst not exceeding the buffer size (bufsz) ,
+ * formulating a calculated (expected) size of the tpl based
+ * on walking its data. When calcsize has been calculated it
+ * should exactly match the buffer size (bufsz) and the internal
+ * recorded size (intlsz)
+ */
+static int tpl_sanity(tpl_node *r, int excess_ok) {
+    uint32_t intlsz;
+    int found_nul=0,rc, octothorpes=0, num_fxlens, *fxlens, flen;
+    void *d, *dv;
+    char intlflags, *fmt, c, *mapfmt;
+    size_t bufsz, serlen;
+
+    d = ((tpl_root_data*)(r->data))->mmap.text;
+    bufsz = ((tpl_root_data*)(r->data))->mmap.text_sz;
+
+    dv = d;
+    if (bufsz < (4 + sizeof(uint32_t) + 1)) return ERR_NOT_MINSIZE; /* min sz: magic+flags+len+nul */
+    if (memcmp(dv,TPL_MAGIC, 3) != 0) return ERR_MAGIC_MISMATCH; /* missing tpl magic prefix */
+    if (tpl_needs_endian_swap(dv)) ((tpl_root_data*)(r->data))->flags |= TPL_XENDIAN;
+    dv = (void*)((uintptr_t)dv + 3);
+    memcpy(&intlflags,dv,sizeof(char));  /* extract flags */
+    if (intlflags & ~TPL_SUPPORTED_BITFLAGS) return ERR_UNSUPPORTED_FLAGS;
+    /* TPL1.3 stores strings with a "length+1" prefix to discern NULL strings from
+       empty strings from non-empty strings; TPL1.2 only handled the latter two.
+       So we need to be mindful of which string format we're reading from. */
+    if (!(intlflags & TPL_FL_NULLSTRINGS)) {
+      ((tpl_root_data*)(r->data))->flags |= TPL_OLD_STRING_FMT;
+    }
+    dv = (void*)((uintptr_t)dv + 1);
+    memcpy(&intlsz,dv,sizeof(uint32_t));  /* extract internal size */
+    if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN) tpl_byteswap(&intlsz, sizeof(uint32_t));
+    if (!excess_ok && (intlsz != bufsz)) return ERR_INCONSISTENT_SZ;  /* inconsisent buffer/internal size */
+    dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+
+    /* dv points to the start of the format string. Look for nul w/in buf sz */
+    fmt = (char*)dv;
+    while ((uintptr_t)dv-(uintptr_t)d < bufsz && !found_nul) {
+        if ( (c = *(char*)dv) != '\0') {
+            if (strchr(tpl_fmt_chars,c) == NULL)
+               return ERR_FMT_INVALID;  /* invalid char in format string */
+            if ( (c = *(char*)dv) == '#') octothorpes++;
+            dv = (void*)((uintptr_t)dv + 1);
+        }
+        else found_nul = 1;
+    }
+    if (!found_nul) return ERR_FMT_MISSING_NUL;  /* runaway format string */
+    dv = (void*)((uintptr_t)dv + 1);   /* advance to octothorpe lengths buffer */
+
+    /* compare the map format to the format of this tpl image */
+    mapfmt = tpl_fmt(r);
+    rc = strcmp(mapfmt,fmt);
+    if (rc != 0) return ERR_FMT_MISMATCH;
+
+    /* compare octothorpe lengths in image to the mapped values */
+    if ((((uintptr_t)dv + (octothorpes * 4)) - (uintptr_t)d) > bufsz) return ERR_INCONSISTENT_SZ4;
+    fxlens = tpl_fxlens(r,&num_fxlens);  /* mapped fxlens */
+    while(num_fxlens--) {
+        memcpy(&flen,dv,sizeof(uint32_t)); /* stored flen */
+        if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN) tpl_byteswap(&flen, sizeof(uint32_t));
+        if (flen != *fxlens) return ERR_FLEN_MISMATCH;
+        dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+        fxlens++;
+    }
+
+    /* dv now points to beginning of data */
+    rc = tpl_serlen(r,r,dv,&serlen);  /* get computed serlen of data part */
+    if (rc == -1) return ERR_INCONSISTENT_SZ2; /* internal inconsistency in tpl image */
+    serlen += ((uintptr_t)dv - (uintptr_t)d);   /* add back serlen of preamble part */
+    if (excess_ok && (bufsz < serlen)) return ERR_INCONSISTENT_SZ3;
+    if (!excess_ok && (serlen != bufsz)) return ERR_INCONSISTENT_SZ3;  /* buffer/internal sz exceeds serlen */
+    return 0;
+}
+
+static void *tpl_find_data_start(void *d) {
+    int octothorpes=0;
+    d = (void*)((uintptr_t)d + 4); /* skip TPL_MAGIC and flags byte */
+    d = (void*)((uintptr_t)d + 4); /* skip int32 overall len */
+    while(*(char*)d != '\0') {
+        if (*(char*)d == '#') octothorpes++;
+        d = (void*)((uintptr_t)d + 1);
+    }
+    d = (void*)((uintptr_t)d +  1);  /* skip NUL */
+    d = (void*)((uintptr_t)d +  (octothorpes * sizeof(uint32_t)));  /* skip # array lens */
+    return d;
+}
+
+static int tpl_needs_endian_swap(void *d) {
+    char *c;
+    int cpu_is_bigendian;
+    c = (char*)d;
+    cpu_is_bigendian = tpl_cpu_bigendian();
+    return ((c[3] & TPL_FL_BIGENDIAN) == cpu_is_bigendian) ? 0 : 1;
+}
+
+static size_t tpl_size_for(char c) {
+  int i;
+  for(i=0; i < sizeof(tpl_types)/sizeof(tpl_types[0]); i++) {
+    if (tpl_types[i].c == c) return tpl_types[i].sz;
+  }
+  return 0;
+}
+
+TPL_API char* tpl_peek(int mode, ...) {
+    va_list ap;
+    int xendian=0,found_nul=0,old_string_format=0;
+    char *filename=NULL, *datapeek_f=NULL, *datapeek_c, *datapeek_s;
+    void *addr=NULL, *dv, *datapeek_p=NULL;
+    size_t sz=0, fmt_len, first_atom, num_fxlens=0;
+    uint32_t datapeek_ssz, datapeek_csz, datapeek_flen;
+    tpl_mmap_rec mr = {0,NULL,0};
+    char *fmt,*fmt_cpy=NULL,c;
+    uint32_t intlsz, **fxlens=NULL, *num_fxlens_out=NULL, *fxlensv;
+
+    va_start(ap,mode);
+    if ((mode & TPL_FXLENS) && (mode & TPL_DATAPEEK)) {
+        tpl_hook.oops("TPL_FXLENS and TPL_DATAPEEK mutually exclusive\n");
+        goto fail;
+    }
+    if (mode & TPL_FILE) filename = va_arg(ap,char *);
+    else if (mode & TPL_MEM) {
+        addr = va_arg(ap,void *);
+        sz = va_arg(ap,size_t);
+    } else {
+        tpl_hook.oops("unsupported tpl_peek mode %d\n", mode);
+        goto fail;
+    }
+    if (mode & TPL_DATAPEEK) {
+        datapeek_f = va_arg(ap, char*);
+    }
+    if (mode & TPL_FXLENS) {
+        num_fxlens_out = va_arg(ap,uint32_t *);
+        fxlens = va_arg(ap,uint32_t **);
+        *num_fxlens_out = 0;
+        *fxlens = NULL;
+    }
+
+    if (mode & TPL_FILE) {
+        if (tpl_mmap_file(filename, &mr) != 0) {
+            tpl_hook.oops("tpl_peek failed for file %s\n", filename);
+            goto fail;
+        }
+        addr = mr.text;
+        sz = mr.text_sz;
+    }
+
+    dv = addr;
+    if (sz < (4 + sizeof(uint32_t) + 1)) goto fail; /* min sz */
+    if (memcmp(dv,TPL_MAGIC, 3) != 0) goto fail; /* missing tpl magic prefix */
+    if (tpl_needs_endian_swap(dv)) xendian=1;
+    if ((((char*)dv)[3] & TPL_FL_NULLSTRINGS)==0) old_string_format=1;
+    dv = (void*)((uintptr_t)dv + 4);
+    memcpy(&intlsz,dv,sizeof(uint32_t));  /* extract internal size */
+    if (xendian) tpl_byteswap(&intlsz, sizeof(uint32_t));
+    if (intlsz != sz) goto fail;  /* inconsisent buffer/internal size */
+    dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+
+    /* dv points to the start of the format string. Look for nul w/in buf sz */
+    fmt = (char*)dv;
+    while ((uintptr_t)dv-(uintptr_t)addr < sz && !found_nul) {
+        if ( (c = *(char*)dv) == '\0') {
+            found_nul = 1;
+        } else if (c == '#') {
+          num_fxlens++;
+        }
+        dv = (void*)((uintptr_t)dv + 1);
+    }
+    if (!found_nul) goto fail;  /* runaway format string */
+    fmt_len = (char*)dv - fmt;  /* include space for \0 */
+    fmt_cpy = tpl_hook.malloc(fmt_len);
+    if (fmt_cpy == NULL) {
+        fatal_oom();
+    }
+    memcpy(fmt_cpy, fmt, fmt_len);
+
+    /* retrieve the octothorpic lengths if requested */
+    if (num_fxlens > 0) {
+      if (sz < ((uintptr_t)dv + (num_fxlens * sizeof(uint32_t)) - (uintptr_t)addr)) {
+        goto fail;
+      }
+    }
+    if ((mode & TPL_FXLENS) && (num_fxlens > 0)) {
+      *fxlens = tpl_hook.malloc(num_fxlens * sizeof(uint32_t));
+      if (*fxlens == NULL) tpl_hook.fatal("out of memory");
+      *num_fxlens_out = num_fxlens;
+      fxlensv = *fxlens;
+      while(num_fxlens--) {
+          memcpy(fxlensv,dv,sizeof(uint32_t));
+          if (xendian) tpl_byteswap(fxlensv, sizeof(uint32_t));
+          dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+          fxlensv++;
+      }
+    }
+    /* if caller requested, peek into the specified data elements */
+    if (mode & TPL_DATAPEEK) {
+
+       first_atom = strspn(fmt, "S()"); /* skip any leading S() */
+
+       datapeek_flen = EM_SAFE_STRLEN(datapeek_f);
+       if (strspn(datapeek_f, tpl_datapeek_ok_chars) < datapeek_flen) {
+         tpl_hook.oops("invalid TPL_DATAPEEK format: %s\n", datapeek_f);
+         tpl_hook.free(fmt_cpy); fmt_cpy = NULL; /* fail */
+         goto fail;
+       }
+
+       if (strncmp( &fmt[first_atom], datapeek_f, datapeek_flen) != 0) {
+         tpl_hook.oops("TPL_DATAPEEK format mismatches tpl iamge\n");
+         tpl_hook.free(fmt_cpy); fmt_cpy = NULL; /* fail */
+         goto fail;
+       }
+
+       /* advance to data start, then copy out requested elements */
+       dv = (void*)((uintptr_t)dv +  (num_fxlens * sizeof(uint32_t)));
+       for(datapeek_c = datapeek_f; *datapeek_c != '\0'; datapeek_c++) {
+         datapeek_p = va_arg(ap, void*);
+         if (*datapeek_c == 's') {  /* special handling for strings */
+           if ((uintptr_t)dv-(uintptr_t)addr + sizeof(uint32_t) > sz) {
+             tpl_hook.oops("tpl_peek: tpl has insufficient length\n");
+             tpl_hook.free(fmt_cpy); fmt_cpy = NULL; /* fail */
+             goto fail;
+           }
+           memcpy(&datapeek_ssz,dv,sizeof(uint32_t)); /* get slen */
+           if (xendian) tpl_byteswap(&datapeek_ssz, sizeof(uint32_t));
+           if (old_string_format) datapeek_ssz++;
+           dv = (void*)((uintptr_t)dv + sizeof(uint32_t)); /* adv. to str */
+           if (datapeek_ssz == 0) datapeek_s = NULL;
+           else {
+             if ((uintptr_t)dv-(uintptr_t)addr + datapeek_ssz-1 > sz) {
+               tpl_hook.oops("tpl_peek: tpl has insufficient length\n");
+               tpl_hook.free(fmt_cpy); fmt_cpy = NULL; /* fail */
+               goto fail;
+             }
+             datapeek_s = tpl_hook.malloc(datapeek_ssz);
+             if (datapeek_s == NULL) fatal_oom();
+             memcpy(datapeek_s, dv, datapeek_ssz-1);
+             datapeek_s[datapeek_ssz-1] = '\0';
+             dv = (void*)((uintptr_t)dv + datapeek_ssz-1);
+           }
+           *(char**)datapeek_p = datapeek_s;
+         } else {
+           datapeek_csz = tpl_size_for(*datapeek_c);
+           if ((uintptr_t)dv-(uintptr_t)addr + datapeek_csz > sz) {
+             tpl_hook.oops("tpl_peek: tpl has insufficient length\n");
+             tpl_hook.free(fmt_cpy); fmt_cpy = NULL; /* fail */
+             goto fail;
+           }
+           memcpy(datapeek_p, dv, datapeek_csz);
+           if (xendian) tpl_byteswap(datapeek_p, datapeek_csz);
+           dv = (void*)((uintptr_t)dv + datapeek_csz);
+         }
+       }
+    }
+
+fail:
+    va_end(ap);
+    if ((mode & TPL_FILE) && mr.text != NULL) tpl_unmap_file( &mr );
+    return fmt_cpy;
+}
+
+/* tpl_jot(TPL_FILE, "file.tpl", "si", &s, &i); */
+/* tpl_jot(TPL_MEM, &buf, &sz, "si", &s, &i); */
+/* tpl_jot(TPL_FD, fd, "si", &s, &i); */
+TPL_API int tpl_jot(int mode, ...) {
+    va_list ap;
+    char *filename, *fmt;
+    size_t *sz;
+    int fd, rc=0;
+    void **buf;
+    tpl_node *tn;
+
+    va_start(ap,mode);
+    if (mode & TPL_FILE) {
+      filename = va_arg(ap,char*);
+      fmt = va_arg(ap,char*);
+      tn = tpl_map_va(fmt, ap);
+      if (tn == NULL) { rc=-1; goto fail;}
+      tpl_pack(tn, 0);
+      rc = tpl_dump(tn, TPL_FILE, filename);
+      tpl_free(tn);
+    } else if (mode & TPL_MEM) {
+      buf = va_arg(ap,void*);
+      sz = va_arg(ap,size_t*);
+      fmt = va_arg(ap,char*);
+      tn = tpl_map_va(fmt,ap);
+      if (tn == NULL) { rc=-1; goto fail;}
+      tpl_pack(tn,0);
+      rc = tpl_dump(tn, TPL_MEM, buf, sz);
+      tpl_free(tn);
+    } else if (mode & TPL_FD) {
+      fd = va_arg(ap,int);
+      fmt = va_arg(ap,char*);
+      tn = tpl_map_va(fmt,ap);
+      if (tn == NULL) { rc=-1; goto fail;}
+      tpl_pack(tn,0);
+      rc = tpl_dump(tn, TPL_FD, fd);
+      tpl_free(tn);
+    } else {
+      tpl_hook.fatal("invalid tpl_jot mode\n");
+    }
+
+fail:
+    va_end(ap);
+    return rc;
+}
+
+TPL_API int tpl_load(tpl_node *r, int mode, ...) {
+    va_list ap;
+    int rc=0,fd=0;
+    char *filename=NULL;
+    void *addr;
+    size_t sz;
+
+    va_start(ap,mode);
+    if (mode & TPL_FILE) filename = va_arg(ap,char *);
+    else if (mode & TPL_MEM) {
+        addr = va_arg(ap,void *);
+        sz = va_arg(ap,size_t);
+    } else if (mode & TPL_FD) {
+        fd = va_arg(ap,int);
+    } else {
+        tpl_hook.oops("unsupported tpl_load mode %d\n", mode);
+        return -1;
+    }
+    va_end(ap);
+
+    if (r->type != TPL_TYPE_ROOT) {
+        tpl_hook.oops("error: tpl_load to non-root node\n");
+        return -1;
+    }
+    if (((tpl_root_data*)(r->data))->flags & (TPL_WRONLY|TPL_RDONLY)) {
+        /* already packed or loaded, so reset it as if newly mapped */
+        tpl_free_keep_map(r);
+    }
+    if (mode & TPL_FILE) {
+        if (tpl_mmap_file(filename, &((tpl_root_data*)(r->data))->mmap) != 0) {
+            tpl_hook.oops("tpl_load failed for file %s\n", filename);
+            return -1;
+        }
+        if ( (rc = tpl_sanity(r, (mode & TPL_EXCESS_OK))) != 0) {
+            if (rc == ERR_FMT_MISMATCH) {
+                tpl_hook.oops("%s: format signature mismatch\n", filename);
+            } else if (rc == ERR_FLEN_MISMATCH) {
+                tpl_hook.oops("%s: array lengths mismatch\n", filename);
+            } else {
+                tpl_hook.oops("%s: not a valid tpl file\n", filename);
+            }
+            tpl_unmap_file( &((tpl_root_data*)(r->data))->mmap );
+            return -1;
+        }
+        ((tpl_root_data*)(r->data))->flags = (TPL_FILE | TPL_RDONLY);
+    } else if (mode & TPL_MEM) {
+        ((tpl_root_data*)(r->data))->mmap.text = addr;
+        ((tpl_root_data*)(r->data))->mmap.text_sz = sz;
+        if ( (rc = tpl_sanity(r, (mode & TPL_EXCESS_OK))) != 0) {
+            if (rc == ERR_FMT_MISMATCH) {
+                tpl_hook.oops("format signature mismatch\n");
+            } else {
+                tpl_hook.oops("not a valid tpl file\n");
+            }
+            return -1;
+        }
+        ((tpl_root_data*)(r->data))->flags = (TPL_MEM | TPL_RDONLY);
+        if (mode & TPL_UFREE) ((tpl_root_data*)(r->data))->flags |= TPL_UFREE;
+    } else if (mode & TPL_FD) {
+        /* if fd read succeeds, resulting mem img is used for load */
+        if (tpl_gather(TPL_GATHER_BLOCKING,fd,&addr,&sz) > 0) {
+            return tpl_load(r, TPL_MEM|TPL_UFREE, addr, sz);
+        } else return -1;
+    } else {
+        tpl_hook.oops("invalid tpl_load mode %d\n", mode);
+        return -1;
+    }
+    /* this applies to TPL_MEM or TPL_FILE */
+    if (tpl_needs_endian_swap(((tpl_root_data*)(r->data))->mmap.text))
+        ((tpl_root_data*)(r->data))->flags |= TPL_XENDIAN;
+    tpl_unpackA0(r);   /* prepare root A nodes for use */
+    return 0;
+}
+
+TPL_API int tpl_Alen(tpl_node *r, int i) {
+    tpl_node *n;
+
+    n = tpl_find_i(r,i);
+    if (n == NULL) {
+        tpl_hook.oops("invalid index %d to tpl_unpack\n", i);
+        return -1;
+    }
+    if (n->type != TPL_TYPE_ARY) return -1;
+    return ((tpl_atyp*)(n->data))->num;
+}
+
+static void tpl_free_atyp(tpl_node *n, tpl_atyp *atyp) {
+    tpl_backbone *bb,*bbnxt;
+    tpl_node *c;
+    void *dv;
+    tpl_bin *binp;
+    tpl_atyp *atypp;
+    char *strp;
+    size_t itermax;
+    tpl_pound_data *pd;
+    int i;
+
+    bb = atyp->bb;
+    while (bb) {
+        bbnxt = bb->next;
+        dv = bb->data;
+        c=n->children;
+        while (c) {
+            switch (c->type) {
+                case TPL_TYPE_BYTE:
+                case TPL_TYPE_DOUBLE:
+                case TPL_TYPE_INT32:
+                case TPL_TYPE_UINT32:
+                case TPL_TYPE_INT64:
+                case TPL_TYPE_UINT64:
+                case TPL_TYPE_INT16:
+                case TPL_TYPE_UINT16:
+                    dv = (void*)((uintptr_t)dv + tpl_types[c->type].sz*c->num);
+                    break;
+                case TPL_TYPE_BIN:
+                    memcpy(&binp,dv,sizeof(tpl_bin*)); /* cp to aligned */
+                    if (binp->addr) tpl_hook.free( binp->addr ); /* free buf */
+                    tpl_hook.free(binp);  /* free tpl_bin */
+                    dv = (void*)((uintptr_t)dv + sizeof(tpl_bin*));
+                    break;
+                case TPL_TYPE_STR:
+                    for(i=0; i < c->num; i++) {
+                      memcpy(&strp,dv,sizeof(char*)); /* cp to aligned */
+                      if (strp) tpl_hook.free(strp); /* free string */
+                      dv = (void*)((uintptr_t)dv + sizeof(char*));
+                    }
+                    break;
+                case TPL_TYPE_POUND:
+                    /* iterate over the preceding nodes */
+                    itermax = c->num;
+                    pd = (tpl_pound_data*)c->data;
+                    if (++(pd->iternum) < itermax) {
+                      c = pd->iter_start_node;
+                      continue;
+                    } else { /* loop complete. */
+                      pd->iternum = 0;
+                    }
+                    break;
+                case TPL_TYPE_ARY:
+                    memcpy(&atypp,dv,sizeof(tpl_atyp*)); /* cp to aligned */
+                    tpl_free_atyp(c,atypp);  /* free atyp */
+                    dv = (void*)((uintptr_t)dv + sizeof(void*));
+                    break;
+                default:
+                    tpl_hook.fatal("unsupported format character\n");
+                    break;
+            }
+            c=c->next;
+        }
+        tpl_hook.free(bb);
+        bb = bbnxt;
+    }
+    tpl_hook.free(atyp);
+}
+
+/* determine (by walking) byte length of serialized r/A node at address dv
+ * returns 0 on success, or -1 if the tpl isn't trustworthy (fails consistency)
+ */
+static int tpl_serlen(tpl_node *r, tpl_node *n, void *dv, size_t *serlen) {
+    uint32_t slen;
+    int num,fidx;
+    tpl_node *c;
+    size_t len=0, alen, buf_past, itermax;
+    tpl_pound_data *pd;
+
+    buf_past = ((uintptr_t)((tpl_root_data*)(r->data))->mmap.text +
+                      ((tpl_root_data*)(r->data))->mmap.text_sz);
+
+    if (n->type == TPL_TYPE_ROOT) num = 1;
+    else if (n->type == TPL_TYPE_ARY) {
+        if ((uintptr_t)dv + sizeof(uint32_t) > buf_past) return -1;
+        memcpy(&num,dv,sizeof(uint32_t));
+        if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+             tpl_byteswap(&num, sizeof(uint32_t));
+        dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+        len += sizeof(uint32_t);
+    } else tpl_hook.fatal("internal error in tpl_serlen\n");
+
+    while (num-- > 0) {
+        c=n->children;
+        while (c) {
+            switch (c->type) {
+                case TPL_TYPE_BYTE:
+                case TPL_TYPE_DOUBLE:
+                case TPL_TYPE_INT32:
+                case TPL_TYPE_UINT32:
+                case TPL_TYPE_INT64:
+                case TPL_TYPE_UINT64:
+                case TPL_TYPE_INT16:
+                case TPL_TYPE_UINT16:
+                    for(fidx=0; fidx < c->num; fidx++) {  /* octothorpe support */
+                        if ((uintptr_t)dv + tpl_types[c->type].sz > buf_past) return -1;
+                        dv = (void*)((uintptr_t)dv + tpl_types[c->type].sz);
+                        len += tpl_types[c->type].sz;
+                    }
+                    break;
+                case TPL_TYPE_BIN:
+                    len += sizeof(uint32_t);
+                    if ((uintptr_t)dv + sizeof(uint32_t) > buf_past) return -1;
+                    memcpy(&slen,dv,sizeof(uint32_t));
+                    if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+                        tpl_byteswap(&slen, sizeof(uint32_t));
+                    len += slen;
+                    dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+                    if ((uintptr_t)dv + slen > buf_past) return -1;
+                    dv = (void*)((uintptr_t)dv + slen);
+                    break;
+                case TPL_TYPE_STR:
+                    for(fidx=0; fidx < c->num; fidx++) {  /* octothorpe support */
+                      len += sizeof(uint32_t);
+                      if ((uintptr_t)dv + sizeof(uint32_t) > buf_past) return -1;
+                      memcpy(&slen,dv,sizeof(uint32_t));
+                      if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+                          tpl_byteswap(&slen, sizeof(uint32_t));
+                      if (!(((tpl_root_data*)(r->data))->flags & TPL_OLD_STRING_FMT))
+                         slen = (slen>1) ? (slen-1) : 0;
+                      len += slen;
+                      dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+                      if ((uintptr_t)dv + slen > buf_past) return -1;
+                      dv = (void*)((uintptr_t)dv + slen);
+                    }
+                    break;
+                case TPL_TYPE_ARY:
+                    if ( tpl_serlen(r,c,dv, &alen) == -1) return -1;
+                    dv = (void*)((uintptr_t)dv + alen);
+                    len += alen;
+                    break;
+                case TPL_TYPE_POUND:
+                    /* iterate over the preceding nodes */
+                    itermax = c->num;
+                    pd = (tpl_pound_data*)c->data;
+                    if (++(pd->iternum) < itermax) {
+                      c = pd->iter_start_node;
+                      continue;
+                    } else { /* loop complete. */
+                      pd->iternum = 0;
+                    }
+                    break;
+                default:
+                    tpl_hook.fatal("unsupported format character\n");
+                    break;
+            }
+            c=c->next;
+        }
+    }
+    *serlen = len;
+    return 0;
+}
+
+static int tpl_mmap_output_file(char *filename, size_t sz, void **text_out) {
+    void *text;
+    int fd,perms;
+
+#ifndef _WIN32
+    perms = S_IRUSR|S_IWUSR|S_IWGRP|S_IRGRP|S_IROTH;  /* ug+w o+r */
+    fd=open(filename,O_CREAT|O_TRUNC|O_RDWR,perms);
+#else
+       perms = _S_IWRITE;
+    fd=_open(filename,_O_CREAT|_O_TRUNC|_O_RDWR,perms);
+#endif
+
+    if ( fd == -1 ) {
+        tpl_hook.oops("Couldn't open file %s: %s\n", filename, strerror(errno));
+        return -1;
+    }
+
+    text = mmap(0, sz, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
+    if (text == MAP_FAILED) {
+        tpl_hook.oops("Failed to mmap %s: %s\n", filename, strerror(errno));
+        close(fd);
+        return -1;
+    }
+    if (ftruncate(fd,sz) == -1) {
+        tpl_hook.oops("ftruncate failed: %s\n", strerror(errno));
+        munmap( text, sz );
+        close(fd);
+        return -1;
+    }
+    *text_out = text;
+    return fd;
+}
+
+static int tpl_mmap_file(char *filename, tpl_mmap_rec *mr) {
+    struct stat stat_buf;
+
+    if ( (mr->fd = open(filename, O_RDONLY)) == -1 ) {
+        tpl_hook.oops("Couldn't open file %s: %s\n", filename, strerror(errno));
+        return -1;
+    }
+
+    if ( fstat(mr->fd, &stat_buf) == -1) {
+        close(mr->fd);
+        tpl_hook.oops("Couldn't stat file %s: %s\n", filename, strerror(errno));
+        return -1;
+    }
+
+    mr->text_sz = (size_t)stat_buf.st_size;
+    mr->text = mmap(0, stat_buf.st_size, PROT_READ, MAP_PRIVATE, mr->fd, 0);
+    if (mr->text == MAP_FAILED) {
+        close(mr->fd);
+        tpl_hook.oops("Failed to mmap %s: %s\n", filename, strerror(errno));
+        return -1;
+    }
+
+    return 0;
+}
+
+TPL_API int tpl_pack(tpl_node *r, int i) {
+    tpl_node *n, *child, *np;
+    void *datav=NULL;
+    size_t sz, itermax;
+    uint32_t slen;
+    char *str;
+    tpl_bin *bin;
+    tpl_pound_data *pd;
+    int fidx;
+
+    n = tpl_find_i(r,i);
+    if (n == NULL) {
+        tpl_hook.oops("invalid index %d to tpl_pack\n", i);
+        return -1;
+    }
+
+    if (((tpl_root_data*)(r->data))->flags & TPL_RDONLY) {
+        /* convert to an writeable tpl, initially empty */
+        tpl_free_keep_map(r);
+    }
+
+    ((tpl_root_data*)(r->data))->flags |= TPL_WRONLY;
+
+    if (n->type == TPL_TYPE_ARY) datav = tpl_extend_backbone(n);
+    child = n->children;
+    while(child) {
+        switch(child->type) {
+            case TPL_TYPE_BYTE:
+            case TPL_TYPE_DOUBLE:
+            case TPL_TYPE_INT32:
+            case TPL_TYPE_UINT32:
+            case TPL_TYPE_INT64:
+            case TPL_TYPE_UINT64:
+            case TPL_TYPE_INT16:
+            case TPL_TYPE_UINT16:
+                /* no need to use fidx iteration here; we can copy multiple values in one memcpy */
+                memcpy(child->data,child->addr,tpl_types[child->type].sz * child->num);
+                if (datav) datav = tpl_cpv(datav,child->data,tpl_types[child->type].sz * child->num);
+                if (n->type == TPL_TYPE_ARY) n->ser_osz += tpl_types[child->type].sz * child->num;
+                break;
+            case TPL_TYPE_BIN:
+                /* copy the buffer to be packed */
+                slen = ((tpl_bin*)child->addr)->sz;
+                if (slen >0) {
+                    str = tpl_hook.malloc(slen);
+                    if (!str) fatal_oom();
+                    memcpy(str,((tpl_bin*)child->addr)->addr,slen);
+                } else str = NULL;
+                /* and make a tpl_bin to point to it */
+                bin = tpl_hook.malloc(sizeof(tpl_bin));
+                if (!bin) fatal_oom();
+                bin->addr = str;
+                bin->sz = slen;
+                /* now pack its pointer, first deep freeing any pre-existing bin */
+                if (*(tpl_bin**)(child->data) != NULL) {
+                    if ((*(tpl_bin**)(child->data))->sz != 0) {
+                            tpl_hook.free( (*(tpl_bin**)(child->data))->addr );
+                    }
+                    tpl_hook.free(*(tpl_bin**)(child->data));
+                }
+                memcpy(child->data,&bin,sizeof(tpl_bin*));
+                if (datav) {
+                    datav = tpl_cpv(datav, &bin, sizeof(tpl_bin*));
+                    *(tpl_bin**)(child->data) = NULL;
+                }
+                if (n->type == TPL_TYPE_ARY) {
+                    n->ser_osz += sizeof(uint32_t); /* binary buf len word */
+                    n->ser_osz += bin->sz;          /* binary buf */
+                }
+                break;
+            case TPL_TYPE_STR:
+                for(fidx=0; fidx < child->num; fidx++) {
+                  /* copy the string to be packed. slen includes \0. this
+                     block also works if the string pointer is NULL. */
+                  char *caddr = ((char**)child->addr)[fidx];
+                  char **cdata = &((char**)child->data)[fidx];
+                  slen = caddr ?  (EM_SAFE_STRLEN(caddr) + 1) : 0;
+                  if (slen) {
+                    str = tpl_hook.malloc(slen);
+                    if (!str) fatal_oom();
+                    memcpy(str,caddr,slen); /* include \0 */
+                  } else {
+                    str = NULL;
+                  }
+                  /* now pack its pointer, first freeing any pre-existing string */
+                  if (*cdata != NULL) {
+                      tpl_hook.free(*cdata);
+                  }
+                  memcpy(cdata,&str,sizeof(char*));
+                  if (datav) {
+                      datav = tpl_cpv(datav, &str, sizeof(char*));
+                      *cdata = NULL;
+                  }
+                  if (n->type == TPL_TYPE_ARY) {
+                      n->ser_osz += sizeof(uint32_t); /* string len word */
+                      if (slen>1) n->ser_osz += slen-1;/* string (without nul) */
+                  }
+                }
+                break;
+            case TPL_TYPE_ARY:
+                /* copy the child's tpl_atype* and reset it to empty */
+                if (datav) {
+                    sz = ((tpl_atyp*)(child->data))->sz;
+                    datav = tpl_cpv(datav, &child->data, sizeof(void*));
+                    child->data = tpl_hook.malloc(sizeof(tpl_atyp));
+                    if (!child->data) fatal_oom();
+                    ((tpl_atyp*)(child->data))->num = 0;
+                    ((tpl_atyp*)(child->data))->sz = sz;
+                    ((tpl_atyp*)(child->data))->bb = NULL;
+                    ((tpl_atyp*)(child->data))->bbtail = NULL;
+                }
+                /* parent is array? then bubble up child array's ser_osz */
+                if (n->type == TPL_TYPE_ARY) {
+                    n->ser_osz += sizeof(uint32_t); /* array len word */
+                    n->ser_osz += child->ser_osz;   /* child array ser_osz */
+                    child->ser_osz = 0;             /* reset child array ser_osz */
+                }
+                break;
+
+            case TPL_TYPE_POUND:
+                /* we need to iterate n times over preceding nodes in S(...).
+                 * we may be in the midst of an iteration each time or starting. */
+                 pd = (tpl_pound_data*)child->data;
+                 itermax = child->num;
+
+                 /* itermax is total num of iterations needed  */
+                 /* pd->iternum is current iteration index  */
+                 /* pd->inter_elt_len is element-to-element len of contiguous structs */
+                 /* pd->iter_start_node is where we jump to at each iteration. */
+
+                 if (++(pd->iternum) < itermax) {
+
+                   /* in start or midst of loop. advance addr/data pointers. */
+                   for(np=pd->iter_start_node; np != child; np = np->next) {
+                     np->data = (char*)(np->data) +
+                          (tpl_types[np->type].sz * np->num);
+                     np->addr = (char*)(np->addr) + pd->inter_elt_len;
+                   }
+                   /* do next iteration */
+                   child = pd->iter_start_node;
+                   continue;
+
+                 } else { /* loop complete. */
+
+                   /* reset iteration index and addr/data pointers. */
+                   pd->iternum = 0;
+                   for(np=pd->iter_start_node; np != child; np = np->next) {
+                     np->data = (char*)(np->data) - ((itermax-1) *
+                                                      tpl_types[np->type].sz *
+                                                      np->num);
+                     np->addr = (char*)(np->addr) - ((itermax-1) * pd->inter_elt_len);
+                   }
+
+                 }
+                break;
+            default:
+                tpl_hook.fatal("unsupported format character\n");
+                break;
+        }
+        child=child->next;
+    }
+    return 0;
+}
+
+TPL_API int tpl_unpack(tpl_node *r, int i) {
+    tpl_node *n, *c, *np;
+    uint32_t slen;
+    int rc=1, fidx;
+    char *str;
+    void *dv=NULL, *caddr;
+    size_t A_bytes, itermax;
+    tpl_pound_data *pd;
+    void *img;
+    size_t sz;
+
+
+    /* handle unusual case of tpl_pack,tpl_unpack without an
+     * intervening tpl_dump. do a dump/load implicitly. */
+    if (((tpl_root_data*)(r->data))->flags & TPL_WRONLY) {
+        if (tpl_dump(r,TPL_MEM,&img,&sz) != 0) return -1;
+        if (tpl_load(r,TPL_MEM|TPL_UFREE,img,sz) != 0) {
+            tpl_hook.free(img);
+            return -1;
+        };
+    }
+
+    n = tpl_find_i(r,i);
+    if (n == NULL) {
+        tpl_hook.oops("invalid index %d to tpl_unpack\n", i);
+        return -1;
+    }
+
+    /* either root node or an A node */
+    if (n->type == TPL_TYPE_ROOT) {
+        dv = tpl_find_data_start( ((tpl_root_data*)(n->data))->mmap.text );
+    } else if (n->type == TPL_TYPE_ARY) {
+        if (((tpl_atyp*)(n->data))->num <= 0) return 0; /* array consumed */
+        else rc = ((tpl_atyp*)(n->data))->num--;
+        dv = ((tpl_atyp*)(n->data))->cur;
+        if (!dv) tpl_hook.fatal("must unpack parent of node before node itself\n");
+    }
+
+    c = n->children;
+    while (c) {
+        switch (c->type) {
+            case TPL_TYPE_BYTE:
+            case TPL_TYPE_DOUBLE:
+            case TPL_TYPE_INT32:
+            case TPL_TYPE_UINT32:
+            case TPL_TYPE_INT64:
+            case TPL_TYPE_UINT64:
+            case TPL_TYPE_INT16:
+            case TPL_TYPE_UINT16:
+                /* unpack elements of cross-endian octothorpic array individually */
+                if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN) {
+                    for(fidx=0; fidx < c->num; fidx++) {
+                        caddr = (void*)((uintptr_t)c->addr + (fidx * tpl_types[c->type].sz));
+                        memcpy(caddr,dv,tpl_types[c->type].sz);
+                        tpl_byteswap(caddr, tpl_types[c->type].sz);
+                        dv = (void*)((uintptr_t)dv + tpl_types[c->type].sz);
+                    }
+                } else {
+                    /* bulk unpack ok if not cross-endian */
+                    memcpy(c->addr, dv, tpl_types[c->type].sz * c->num);
+                    dv = (void*)((uintptr_t)dv + tpl_types[c->type].sz * c->num);
+                }
+                break;
+            case TPL_TYPE_BIN:
+                memcpy(&slen,dv,sizeof(uint32_t));
+                if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+                    tpl_byteswap(&slen, sizeof(uint32_t));
+                if (slen > 0) {
+                    str = (char*)tpl_hook.malloc(slen);
+                    if (!str) fatal_oom();
+                } else str=NULL;
+                dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+                if (slen>0) memcpy(str,dv,slen);
+                memcpy(&(((tpl_bin*)c->addr)->addr),&str,sizeof(void*));
+                memcpy(&(((tpl_bin*)c->addr)->sz),&slen,sizeof(uint32_t));
+                dv = (void*)((uintptr_t)dv + slen);
+                break;
+            case TPL_TYPE_STR:
+                for(fidx=0; fidx < c->num; fidx++) {
+                  memcpy(&slen,dv,sizeof(uint32_t));
+                  if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+                      tpl_byteswap(&slen, sizeof(uint32_t));
+                  if (((tpl_root_data*)(r->data))->flags & TPL_OLD_STRING_FMT)
+                    slen += 1;
+                  dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+                  if (slen) {  /* slen includes \0 */
+                    str = (char*)tpl_hook.malloc(slen);
+                    if (!str) fatal_oom();
+                    if (slen>1) memcpy(str,dv,slen-1);
+                    str[slen-1] = '\0'; /* nul terminate */
+                    dv = (void*)((uintptr_t)dv + slen-1);
+                  } else str=NULL;
+                  memcpy(&((char**)c->addr)[fidx],&str,sizeof(char*));
+                }
+                break;
+            case TPL_TYPE_POUND:
+                /* iterate over preceding nodes */
+                pd = (tpl_pound_data*)c->data;
+                itermax = c->num;
+                if (++(pd->iternum) < itermax) {
+                  /* in start or midst of loop. advance addr/data pointers. */
+                  for(np=pd->iter_start_node; np != c; np = np->next) {
+                    np->addr = (char*)(np->addr) + pd->inter_elt_len;
+                  }
+                  /* do next iteration */
+                  c = pd->iter_start_node;
+                  continue;
+
+                } else { /* loop complete. */
+
+                  /* reset iteration index and addr/data pointers. */
+                  pd->iternum = 0;
+                  for(np=pd->iter_start_node; np != c; np = np->next) {
+                    np->addr = (char*)(np->addr) - ((itermax-1) * pd->inter_elt_len);
+                  }
+
+                }
+                break;
+            case TPL_TYPE_ARY:
+                if (tpl_serlen(r,c,dv, &A_bytes) == -1)
+                    tpl_hook.fatal("internal error in unpack\n");
+                memcpy( &((tpl_atyp*)(c->data))->num, dv, sizeof(uint32_t));
+                if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+                    tpl_byteswap(&((tpl_atyp*)(c->data))->num, sizeof(uint32_t));
+                ((tpl_atyp*)(c->data))->cur = (void*)((uintptr_t)dv+sizeof(uint32_t));
+                dv = (void*)((uintptr_t)dv + A_bytes);
+                break;
+            default:
+                tpl_hook.fatal("unsupported format character\n");
+                break;
+        }
+
+        c = c->next;
+    }
+    if (n->type == TPL_TYPE_ARY) ((tpl_atyp*)(n->data))->cur = dv; /* next element */
+    return rc;
+}
+
+/* Specialized function that unpacks only the root's A nodes, after tpl_load  */
+static int tpl_unpackA0(tpl_node *r) {
+    tpl_node *n, *c;
+    uint32_t slen;
+    int rc=1,fidx,i;
+    void *dv;
+    size_t A_bytes, itermax;
+    tpl_pound_data *pd;
+
+    n = r;
+    dv = tpl_find_data_start( ((tpl_root_data*)(r->data))->mmap.text);
+
+    c=n->children;
+    while (c)  {
+        switch (c->type) {
+            case TPL_TYPE_BYTE:
+            case TPL_TYPE_DOUBLE:
+            case TPL_TYPE_INT32:
+            case TPL_TYPE_UINT32:
+            case TPL_TYPE_INT64:
+            case TPL_TYPE_UINT64:
+            case TPL_TYPE_INT16:
+            case TPL_TYPE_UINT16:
+                for(fidx=0;fidx < c->num; fidx++) {
+                    dv = (void*)((uintptr_t)dv + tpl_types[c->type].sz);
+                }
+                break;
+            case TPL_TYPE_BIN:
+                memcpy(&slen,dv,sizeof(uint32_t));
+                if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+                    tpl_byteswap(&slen, sizeof(uint32_t));
+                dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+                dv = (void*)((uintptr_t)dv + slen);
+                break;
+            case TPL_TYPE_STR:
+                for(i=0; i<c->num; i++) {
+                  memcpy(&slen,dv,sizeof(uint32_t));
+                  if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+                      tpl_byteswap(&slen, sizeof(uint32_t));
+                  if (((tpl_root_data*)(r->data))->flags & TPL_OLD_STRING_FMT)
+                    slen += 1;
+                  dv = (void*)((uintptr_t)dv + sizeof(uint32_t));
+                  if (slen>1) dv = (void*)((uintptr_t)dv + slen-1);
+                }
+                break;
+            case TPL_TYPE_POUND:
+                /* iterate over the preceding nodes */
+                itermax = c->num;
+                pd = (tpl_pound_data*)c->data;
+                if (++(pd->iternum) < itermax) {
+                  c = pd->iter_start_node;
+                  continue;
+                } else { /* loop complete. */
+                  pd->iternum = 0;
+                }
+                break;
+            case TPL_TYPE_ARY:
+                if ( tpl_serlen(r,c,dv, &A_bytes) == -1)
+                    tpl_hook.fatal("internal error in unpackA0\n");
+                memcpy( &((tpl_atyp*)(c->data))->num, dv, sizeof(uint32_t));
+                if (((tpl_root_data*)(r->data))->flags & TPL_XENDIAN)
+                    tpl_byteswap(&((tpl_atyp*)(c->data))->num, sizeof(uint32_t));
+                ((tpl_atyp*)(c->data))->cur = (void*)((uintptr_t)dv+sizeof(uint32_t));
+                dv = (void*)((uintptr_t)dv + A_bytes);
+                break;
+            default:
+                tpl_hook.fatal("unsupported format character\n");
+                break;
+        }
+        c=c->next;
+    }
+    return rc;
+}
+
+/* In-place byte order swapping of a word of length "len" bytes */
+static void tpl_byteswap(void *word, int len) {
+    int i;
+    char c, *w;
+    w = (char*)word;
+    for(i=0; i<len/2; i++) {
+        c = w[i];
+        w[i] = w[len-1-i];
+        w[len-1-i] = c;
+    }
+}
+
+static void tpl_fatal(char *fmt, ...) {
+    va_list ap;
+    char exit_msg[100];
+
+    va_start(ap,fmt);
+    vsnprintf(exit_msg, 100, fmt, ap);
+    va_end(ap);
+
+    tpl_hook.oops("%s", exit_msg);
+    exit(-1);
+}
+
+TPL_API int tpl_gather(int mode, ...) {
+    va_list ap;
+    int fd,rc=0;
+    size_t *szp,sz;
+    void **img,*addr,*data;
+    tpl_gather_t **gs;
+    tpl_gather_cb *cb;
+
+    va_start(ap,mode);
+    switch (mode) {
+        case TPL_GATHER_BLOCKING:
+            fd = va_arg(ap,int);
+            img = va_arg(ap,void*);
+            szp = va_arg(ap,size_t*);
+            rc = tpl_gather_blocking(fd,img,szp);
+            break;
+        case TPL_GATHER_NONBLOCKING:
+            fd = va_arg(ap,int);
+            gs = (tpl_gather_t**)va_arg(ap,void*);
+            cb = (tpl_gather_cb*)va_arg(ap,tpl_gather_cb*);
+            data = va_arg(ap,void*);
+            rc = tpl_gather_nonblocking(fd,gs,cb,data);
+            break;
+        case TPL_GATHER_MEM:
+            addr = va_arg(ap,void*);
+            sz = va_arg(ap,size_t);
+            gs = (tpl_gather_t**)va_arg(ap,void*);
+            cb = (tpl_gather_cb*)va_arg(ap,tpl_gather_cb*);
+            data = va_arg(ap,void*);
+            rc = tpl_gather_mem(addr,sz,gs,cb,data);
+            break;
+        default:
+            tpl_hook.fatal("unsupported tpl_gather mode %d\n",mode);
+            break;
+    }
+    va_end(ap);
+    return rc;
+}
+
+/* dequeue a tpl by reading until one full tpl image is obtained.
+ * We take care not to read past the end of the tpl.
+ * This is intended as a blocking call i.e. for use with a blocking fd.
+ * It can be given a non-blocking fd, but the read spins if we have to wait.
+ */
+static int tpl_gather_blocking(int fd, void **img, size_t *sz) {
+    char preamble[8];
+    int i=0, rc;
+    uint32_t tpllen;
+
+    do {
+        rc = read(fd,&preamble[i],8-i);
+        i += (rc>0) ? rc : 0;
+    } while ((rc==-1 && (errno==EINTR||errno==EAGAIN)) || (rc>0 && i<8));
+
+    if (rc<0) {
+        tpl_hook.oops("tpl_gather_fd_blocking failed: %s\n", strerror(errno));
+        return -1;
+    } else if (rc == 0) {
+        /* tpl_hook.oops("tpl_gather_fd_blocking: eof\n"); */
+        return 0;
+    } else if (i != 8) {
+        tpl_hook.oops("internal error\n");
+        return -1;
+    }
+
+    if (preamble[0] == 't' && preamble[1] == 'p' && preamble[2] == 'l') {
+        memcpy(&tpllen,&preamble[4],4);
+        if (tpl_needs_endian_swap(preamble)) tpl_byteswap(&tpllen,4);
+    } else {
+        tpl_hook.oops("tpl_gather_fd_blocking: non-tpl input\n");
+        return -1;
+    }
+
+    /* malloc space for remainder of tpl image (overall length tpllen)
+     * and read it in
+     */
+    if (tpl_hook.gather_max > 0 &&
+        tpllen > tpl_hook.gather_max) {
+        tpl_hook.oops("tpl exceeds max length %d\n",
+            tpl_hook.gather_max);
+        return -2;
+    }
+    *sz = tpllen;
+    if ( (*img = tpl_hook.malloc(tpllen)) == NULL) {
+        fatal_oom();
+    }
+
+    memcpy(*img,preamble,8);  /* copy preamble to output buffer */
+    i=8;
+    do {
+        rc = read(fd,&((*(char**)img)[i]),tpllen-i);
+        i += (rc>0) ? rc : 0;
+    } while ((rc==-1 && (errno==EINTR||errno==EAGAIN)) || (rc>0 && i<tpllen));
+
+    if (rc<0) {
+        tpl_hook.oops("tpl_gather_fd_blocking failed: %s\n", strerror(errno));
+        tpl_hook.free(*img);
+        return -1;
+    } else if (rc == 0) {
+        /* tpl_hook.oops("tpl_gather_fd_blocking: eof\n"); */
+        tpl_hook.free(*img);
+        return 0;
+    } else if (i != tpllen) {
+        tpl_hook.oops("internal error\n");
+        tpl_hook.free(*img);
+        return -1;
+    }
+
+    return 1;
+}
+
+/* Used by select()-driven apps which want to gather tpl images piecemeal */
+/* the file descriptor must be non-blocking for this functino to work. */
+static int tpl_gather_nonblocking( int fd, tpl_gather_t **gs, tpl_gather_cb *cb, void *data) {
+    char buf[TPL_GATHER_BUFLEN], *img, *tpl;
+    int rc, keep_looping, cbrc=0;
+    size_t catlen;
+    uint32_t tpllen;
+
+    while (1) {
+        rc = read(fd,buf,TPL_GATHER_BUFLEN);
+        if (rc == -1) {
+            if (errno == EINTR) continue;  /* got signal during read, ignore */
+            if (errno == EAGAIN) return 1; /* nothing to read right now */
+            else {
+                tpl_hook.oops("tpl_gather failed: %s\n", strerror(errno));
+                if (*gs) {
+                    tpl_hook.free((*gs)->img);
+                    tpl_hook.free(*gs);
+                    *gs = NULL;
+                }
+                return -1;                 /* error, caller should close fd  */
+            }
+        } else if (rc == 0) {
+            if (*gs) {
+                tpl_hook.oops("tpl_gather: partial tpl image precedes EOF\n");
+                tpl_hook.free((*gs)->img);
+                tpl_hook.free(*gs);
+                *gs = NULL;
+            }
+            return 0;                      /* EOF, caller should close fd */
+        } else {
+            /* concatenate any partial tpl from last read with new buffer */
+            if (*gs) {
+                catlen = (*gs)->len + rc;
+                if (tpl_hook.gather_max > 0 &&
+                    catlen > tpl_hook.gather_max) {
+                    tpl_hook.free( (*gs)->img );
+                    tpl_hook.free( (*gs) );
+                    *gs = NULL;
+                    tpl_hook.oops("tpl exceeds max length %d\n",
+                        tpl_hook.gather_max);
+                    return -2;              /* error, caller should close fd */
+                }
+                if ( (img = tpl_hook.realloc((*gs)->img, catlen)) == NULL) {
+                    fatal_oom();
+                }
+                memcpy(img + (*gs)->len, buf, rc);
+                tpl_hook.free(*gs);
+                *gs = NULL;
+            } else {
+                img = buf;
+                catlen = rc;
+            }
+            /* isolate any full tpl(s) in img and invoke cb for each */
+            tpl = img;
+            keep_looping = (tpl+8 < img+catlen) ? 1 : 0;
+            while (keep_looping) {
+                if (strncmp("tpl", tpl, 3) != 0) {
+                    tpl_hook.oops("tpl prefix invalid\n");
+                    if (img != buf) tpl_hook.free(img);
+                    tpl_hook.free(*gs);
+                    *gs = NULL;
+                    return -3; /* error, caller should close fd */
+                }
+                memcpy(&tpllen,&tpl[4],4);
+                if (tpl_needs_endian_swap(tpl)) tpl_byteswap(&tpllen,4);
+                if (tpl+tpllen <= img+catlen) {
+                    cbrc = (cb)(tpl,tpllen,data);  /* invoke cb for tpl image */
+                    tpl += tpllen;                 /* point to next tpl image */
+                    if (cbrc < 0) keep_looping = 0;
+                    else keep_looping = (tpl+8 < img+catlen) ? 1 : 0;
+                } else keep_looping=0;
+            }
+            /* check if app callback requested closure of tpl source */
+            if (cbrc < 0) {
+                tpl_hook.oops("tpl_fd_gather aborted by app callback\n");
+                if (img != buf) tpl_hook.free(img);
+                if (*gs) tpl_hook.free(*gs);
+                *gs = NULL;
+                return -4;
+            }
+            /* store any leftover, partial tpl fragment for next read */
+            if (tpl == img && img != buf) {
+                /* consumed nothing from img!=buf */
+                if ( (*gs = tpl_hook.malloc(sizeof(tpl_gather_t))) == NULL ) {
+                    fatal_oom();
+                }
+                (*gs)->img = tpl;
+                (*gs)->len = catlen;
+            } else if (tpl < img+catlen) {
+                /* consumed 1+ tpl(s) from img!=buf or 0 from img==buf */
+                if ( (*gs = tpl_hook.malloc(sizeof(tpl_gather_t))) == NULL ) {
+                    fatal_oom();
+                }
+                if ( ((*gs)->img = tpl_hook.malloc(img+catlen - tpl)) == NULL ) {
+                    fatal_oom();
+                }
+                (*gs)->len = img+catlen - tpl;
+                memcpy( (*gs)->img, tpl, img+catlen - tpl);
+                /* free partially consumed concat buffer if used */
+                if (img != buf) tpl_hook.free(img);
+            } else {                        /* tpl(s) fully consumed */
+                /* free consumed concat buffer if used */
+                if (img != buf) tpl_hook.free(img);
+            }
+        }
+    }
+}
+
+/* gather tpl piecemeal from memory buffer (not fd) e.g., from a lower-level api */
+static int tpl_gather_mem( char *buf, size_t len, tpl_gather_t **gs, tpl_gather_cb *cb, void *data) {
+    char *img, *tpl;
+    int keep_looping, cbrc=0;
+    size_t catlen;
+    uint32_t tpllen;
+
+    /* concatenate any partial tpl from last read with new buffer */
+    if (*gs) {
+        catlen = (*gs)->len + len;
+        if (tpl_hook.gather_max > 0 &&
+            catlen > tpl_hook.gather_max) {
+            tpl_hook.free( (*gs)->img );
+            tpl_hook.free( (*gs) );
+            *gs = NULL;
+            tpl_hook.oops("tpl exceeds max length %d\n",
+                tpl_hook.gather_max);
+            return -2;              /* error, caller should stop accepting input from source*/
+        }
+        if ( (img = tpl_hook.realloc((*gs)->img, catlen)) == NULL) {
+            fatal_oom();
+        }
+        memcpy(img + (*gs)->len, buf, len);
+        tpl_hook.free(*gs);
+        *gs = NULL;
+    } else {
+        img = buf;
+        catlen = len;
+    }
+    /* isolate any full tpl(s) in img and invoke cb for each */
+    tpl = img;
+    keep_looping = (tpl+8 < img+catlen) ? 1 : 0;
+    while (keep_looping) {
+        if (strncmp("tpl", tpl, 3) != 0) {
+            tpl_hook.oops("tpl prefix invalid\n");
+            if (img != buf) tpl_hook.free(img);
+            tpl_hook.free(*gs);
+            *gs = NULL;
+            return -3; /* error, caller should stop accepting input from source*/
+        }
+        memcpy(&tpllen,&tpl[4],4);
+        if (tpl_needs_endian_swap(tpl)) tpl_byteswap(&tpllen,4);
+        if (tpl+tpllen <= img+catlen) {
+            cbrc = (cb)(tpl,tpllen,data);  /* invoke cb for tpl image */
+            tpl += tpllen;               /* point to next tpl image */
+            if (cbrc < 0) keep_looping = 0;
+            else keep_looping = (tpl+8 < img+catlen) ? 1 : 0;
+        } else keep_looping=0;
+    }
+    /* check if app callback requested closure of tpl source */
+    if (cbrc < 0) {
+        tpl_hook.oops("tpl_mem_gather aborted by app callback\n");
+        if (img != buf) tpl_hook.free(img);
+        if (*gs) tpl_hook.free(*gs);
+        *gs = NULL;
+        return -4;
+    }
+    /* store any leftover, partial tpl fragment for next read */
+    if (tpl == img && img != buf) {
+        /* consumed nothing from img!=buf */
+        if ( (*gs = tpl_hook.malloc(sizeof(tpl_gather_t))) == NULL ) {
+            fatal_oom();
+        }
+        (*gs)->img = tpl;
+        (*gs)->len = catlen;
+    } else if (tpl < img+catlen) {
+        /* consumed 1+ tpl(s) from img!=buf or 0 from img==buf */
+        if ( (*gs = tpl_hook.malloc(sizeof(tpl_gather_t))) == NULL ) {
+            fatal_oom();
+        }
+        if ( ((*gs)->img = tpl_hook.malloc(img+catlen - tpl)) == NULL ) {
+            fatal_oom();
+        }
+        (*gs)->len = img+catlen - tpl;
+        memcpy( (*gs)->img, tpl, img+catlen - tpl);
+        /* free partially consumed concat buffer if used */
+        if (img != buf) tpl_hook.free(img);
+    } else {                        /* tpl(s) fully consumed */
+        /* free consumed concat buffer if used */
+        if (img != buf) tpl_hook.free(img);
+    }
+    return 1;
+}
index fb8dfe6..0d32b1f 100755 (executable)
@@ -1,5 +1,5 @@
 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
-PROJECT(email-storage)
+PROJECT(email-core)
 
 SET(CMAKE_SKIP_BUILD_RPATH TRUE)
 
@@ -12,30 +12,67 @@ MESSAGE(">>> current directory: ${CMAKE_CURRENT_SOURCE_DIR}")
 MESSAGE(">>> Build type: ${CMAKE_BUILD_TYPE}")
 
 
-SET(VISIBILITY "-DEXPORT_API=\"__attribute__((visibility(\\\"default\\\")))\"")
 SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden")
 
+
+##########################################################
+# Define device lib
+##########################################################
+
+SET(DEVICE-LIB "email-device")
+SET(DEVICE-SRCS 
+       ./email-device/email-device.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-device/include
+)
+
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(storage_pkgs REQUIRED glib-2.0 dlog vconf dbus-1)
+
+set(EXTRA_CFLAGS "")
+FOREACH(flag ${device_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+#message(">>> extra_cflags ${EXTRA_CFLAGS}")
+#message(">>> result ${CMAKE_C_FLAGS}")
+
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${DEVICE-LIB} SHARED ${DEVICE-SRCS})
+TARGET_LINK_LIBRARIES(${DEVICE-LIB} ${device_LDFLAGS} ${BASE-LIB})
+SET_TARGET_PROPERTIES(${DEVICE-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${DEVICE-LIB} PROPERTIES VERSION ${VERSION})
+
+INSTALL(TARGETS ${DEVICE-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
+
 ##########################################################
-# Define STORAGE lib
+# Define storage lib
 ##########################################################
 
 SET(STORAGE-LIB "email-storage")
 SET(STORAGE-SRCS 
-       ./em-storage/em-storage-noti.c
-       ./em-storage/em-storage.c
-       ${CMAKE_SOURCE_DIR}/emf-emn-storage/emf-emn-storage.c
+       ./email-storage/email-storage.c
 )
 
 INCLUDE_DIRECTORIES(
-       ${CMAKE_ROOT_DIR}/include/common/include
-       ${CMAKE_ROOT_DIR}/include
-       ${CMAKE_SOURCE_DIR}/include
-       ${CMAKE_SOURCE_DIR}/em-storage/include
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+       ${CMAKE_SOURCE_DIR}/email-daemon/include
+       ${CMAKE_SOURCE_DIR}/email-core/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
 )
 
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(storage_pkgs REQUIRED drm-service glib-2.0 dlog db-util openssl vconf secure-storage dbus-1 contacts-service)
+pkg_check_modules(storage_pkgs REQUIRED drm-client glib-2.0 dlog db-util openssl vconf secure-storage dbus-1 contacts-service2)
 
 set(EXTRA_CFLAGS "")
 FOREACH(flag ${storage_pkgs_CFLAGS})
@@ -55,7 +92,6 @@ TARGET_LINK_LIBRARIES(${STORAGE-LIB} ${storage_LDFLAGS} ${BASE-LIB} ss-client)
 SET_TARGET_PROPERTIES(${STORAGE-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
 SET_TARGET_PROPERTIES(${STORAGE-LIB} PROPERTIES VERSION ${VERSION})
 
-#INSTALL(TARGETS ${STORAGE-LIB} LIBRARY DESTINATION lib)
 INSTALL(TARGETS ${STORAGE-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
 
 
@@ -65,14 +101,14 @@ INSTALL(TARGETS ${STORAGE-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
 
 SET(NETWORK-LIB "email-network")
 SET(NETWORK-SRCS 
-       ./em-network/em-network.c
+       ./email-network/email-network.c
 )
 
 INCLUDE_DIRECTORIES(
-       ${CMAKE_SOURCE_DIR}/include/common/include
-       ${CMAKE_SOURCE_DIR}/include
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+       ${CMAKE_SOURCE_DIR}/email-daemon/include
        ${CMAKE_SOURCE_DIR}/email-core/include
-       ${CMAKE_SOURCE_DIR}/email-core/em-storage/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
 )
 
 INCLUDE(FindPkgConfig)
@@ -101,35 +137,40 @@ INSTALL(TARGETS ${NETWORK-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
 
 SET(CORE-LIB "email-core")
 SET(CORE-SRCS 
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-event.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-imap-mailbox.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-mailbox.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-mailbox-sync.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-mesg.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-mm-callbacks.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-utils.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-api.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-smtp.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-timer.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-imap-idle.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-global.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-account.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-mime.c
-       ${CMAKE_SOURCE_DIR}/email-core/em-core-sound.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-event.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-imap-mailbox.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-mailbox.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-mailbox-sync.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-mail.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-mm-callbacks.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-utils.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-api.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-smtp.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-timer.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-imap-idle.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-global.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-account.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-mime.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-smime.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-cert.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-sound.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-task-manager.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-tasks.c
+       ${CMAKE_SOURCE_DIR}/email-core/email-core-signal.c
 )
 
 INCLUDE_DIRECTORIES(
-       ${CMAKE_SOURCE_DIR}/include/common/include
-       ${CMAKE_SOURCE_DIR}/include/
-       ${CMAKE_SOURCE_DIR}/email-core/em-storage/include
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+       ${CMAKE_SOURCE_DIR}/email-daemon/include/
        ${CMAKE_SOURCE_DIR}/email-core/include
-       ${CMAKE_SOURCE_DIR}/Common/include
-       ${CMAKE_SOURCE_DIR}/email-core/em-network/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-network/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-device/include
 )
 
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(core_pkgs REQUIRED glib-2.0 drm-service dlog dbus-1 gthread-2.0 uw-imap-toolkit vconf contacts-service secure-storage openssl accounts-svc mm-player mm-session devman_haptic alarm-service notification libcurl libxml-2.0)
+pkg_check_modules(core_pkgs REQUIRED glib-2.0 drm-client dlog dbus-1 gthread-2.0 uw-imap-toolkit vconf vconf-internal-keys contacts-service2 secure-storage openssl accounts-svc mm-player mm-session feedback alarm-service notification libcurl libxml-2.0 cert-svc cert-svc-vcore badge)
 
 set(EXTRA_CFLAGS "")
 FOREACH(flag ${core_pkgs_CFLAGS})
@@ -161,7 +202,7 @@ SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_LIBRARY(${CORE-LIB} SHARED ${CORE-SRCS})
 
-TARGET_LINK_LIBRARIES(${CORE-LIB} ${core_pkgs_LDFLAGS} ${STORAGE-LIB} ${NETWORK-LIB})
+TARGET_LINK_LIBRARIES(${CORE-LIB} ${core_pkgs_LDFLAGS} ${STORAGE-LIB} ${NETWORK-LIB} ${DEVICE-LIB})
 
 SET_TARGET_PROPERTIES(${CORE-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
 SET_TARGET_PROPERTIES(${CORE-LIB} PROPERTIES VERSION ${VERSION})
diff --git a/email-core/email-core-account.c b/email-core/email-core-account.c
new file mode 100755 (executable)
index 0000000..a93c3cc
--- /dev/null
@@ -0,0 +1,1331 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-account.c
+ * Desc :  Account Management
+ *
+ * Auth :  Kyuho Jo
+ *
+ * History :
+ *    2010.08.25  :  created
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <sys/types.h>
+#include <vconf.h>
+
+#include "email-convert.h"
+#include "email-types.h"
+#include "email-daemon.h"
+#include "email-debug-log.h"
+#include "email-storage.h"
+#include "email-network.h"
+#include "email-utilities.h"
+#include "email-core-utils.h"
+#include "email-core-event.h"
+#include "email-core-global.h"
+#include "email-core-account.h"
+#include "email-core-mailbox.h"
+#include "email-core-signal.h"
+#include "email-core-imap-mailbox.h"
+
+#ifdef __FEATURE_USING_ACCOUNT_SVC__
+#include "account.h"
+#include "account-types.h"
+#endif /*  __FEATURE_USING_ACCOUNT_SVC__ */
+
+char *g_default_mbox_alias[MAILBOX_COUNT] =
+{
+       EMAIL_INBOX_DISPLAY_NAME,
+       EMAIL_DRAFTBOX_DISPLAY_NAME,
+       EMAIL_OUTBOX_DISPLAY_NAME,
+       EMAIL_SENTBOX_DISPLAY_NAME,
+       EMAIL_TRASH_DISPLAY_NAME,
+       EMAIL_SPAMBOX_DISPLAY_NAME,
+};
+
+char *g_default_mbox_name[MAILBOX_COUNT]  =
+{
+       EMAIL_INBOX_NAME,
+       EMAIL_DRAFTBOX_NAME,
+       EMAIL_OUTBOX_NAME,
+       EMAIL_SENTBOX_NAME,
+       EMAIL_TRASH_DISPLAY_NAME,
+       EMAIL_SPAMBOX_NAME,
+};
+
+email_mailbox_type_e g_default_mbox_type[MAILBOX_COUNT] =
+{
+       EMAIL_MAILBOX_TYPE_INBOX,
+       EMAIL_MAILBOX_TYPE_DRAFT,
+       EMAIL_MAILBOX_TYPE_OUTBOX,
+       EMAIL_MAILBOX_TYPE_SENTBOX,
+       EMAIL_MAILBOX_TYPE_TRASH,
+       EMAIL_MAILBOX_TYPE_SPAMBOX,
+};
+
+static email_account_list_t *g_account_list = NULL;
+static int g_account_num = 0;
+static pthread_mutex_t _account_ref_lock = PTHREAD_MUTEX_INITIALIZER;
+
+INTERNAL_FUNC email_account_t* emcore_get_account_reference(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d]", account_id);
+       email_account_list_t **p;
+       email_account_t *result_account = NULL;
+
+       if (account_id < 0){
+               emcore_get_account_from_unvalidated_account_list(account_id, &result_account);
+               return result_account;
+       }
+       else if (account_id > 0)  {
+               ENTER_CRITICAL_SECTION(_account_ref_lock);
+               p = &g_account_list;
+               while (*p)  {
+                       if ((*p)->account->account_id == account_id) {
+                               emcore_duplicate_account((*p)->account, &result_account, NULL);
+                               break;
+                       }
+                       p = &(*p)->next;
+               }
+               LEAVE_CRITICAL_SECTION(_account_ref_lock);
+
+               if (result_account)
+                       goto FINISH_OFF;
+
+               /*  refresh and check once again */
+               emcore_init_account_reference();
+               ENTER_CRITICAL_SECTION(_account_ref_lock);
+               if (g_account_num > 0 && g_account_list) {
+                       p = &g_account_list;
+                       while (*p)  {
+                               if ((*p)->account->account_id == account_id) {
+                                       emcore_duplicate_account((*p)->account, &result_account, NULL);
+                                       break;
+                               }
+                               p = &(*p)->next;
+                       }
+               }
+               LEAVE_CRITICAL_SECTION(_account_ref_lock);
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("[%p]", result_account);
+       return result_account;
+}
+
+
+INTERNAL_FUNC int emcore_validate_account_with_account_info(email_account_t *account, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p], err_code[%p], incoming_server_address [%s]", account, err_code, account->incoming_server_address);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_session_t *session = NULL;
+       SENDSTREAM *stream = NULL;
+       MAILSTREAM *tmp_stream = NULL;
+
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       if (!emnetwork_check_network_status(&err))  {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG("Network available");
+
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_empty_session(&session))  {
+               EM_DEBUG_EXCEPTION("emcore_get_empty_session failed...");
+               err = EMAIL_ERROR_SESSION_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+#ifdef _SMTP_ACCOUNT_VALIDATION_
+       /* validate connection for smt */
+       EM_DEBUG_LOG("Validate connection for SMTP");
+
+       if (!emcore_check_thread_status()) {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       if (!emcore_connect_to_remote_mailbox_with_account_info(account, (char *)ENCODED_PATH_SMTP, (void **)&stream, &err) || !stream)  {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed 1 - %d", err);
+               if (EMAIL_ERROR_AUTHENTICATE == err || EMAIL_ERROR_LOGIN_FAILURE == err) {      /*  wrong password or etc */
+                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed  :  Login or Authentication fail 1- %d", err);
+                       goto FINISH_OFF;
+               }
+
+               if (account->outgoing_server_secure_connection == 0x01) /*  0x01 == ss */ {
+                       /*  retry with tl */
+                       EM_DEBUG_LOG("Retry with TLS");
+                       account->outgoing_server_secure_connection = 0x02;      /*  0x02 == tl */
+                       if (!emcore_check_thread_status())  {
+                               err = EMAIL_ERROR_CANCELLED;
+                               goto FINISH_OFF;
+                       }
+
+                   if (!emcore_connect_to_remote_mailbox_with_account_info(account, (char *)ENCODED_PATH_SMTP, (void **)&stream, &err) || !stream)  {
+                               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed 2 - %d", err);
+                               if (EMAIL_ERROR_AUTHENTICATE == err || EMAIL_ERROR_LOGIN_FAILURE == err) {      /*  wrong password or etc */
+                                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed  :  Login or Authentication fail 2 - %d", err);
+                               }
+                               else if (EMAIL_ERROR_CONNECTION_FAILURE != err) {
+                                       err = EMAIL_ERROR_VALIDATE_ACCOUNT;
+                               }
+                               account->outgoing_server_secure_connection = 0x01;      /*  restore to the previous value */
+                               goto FINISH_OFF;
+                   }
+
+                       if (!emcore_check_thread_status())  {
+                               err = EMAIL_ERROR_CANCELLED;
+                               goto FINISH_OFF;
+                       }
+
+                       /*  save outgoing_server_secure_connection = 0x02 (tls) to the d */
+                       if (!emstorage_update_account(account_id, (emstorage_account_tbl_t  *)account, true, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_update_account failed - %d", err);
+                               account->outgoing_server_secure_connection = 0x01;      /*  restore to the previous value */
+                               err = EMAIL_ERROR_VALIDATE_ACCOUNT;
+                               goto FINISH_OFF;
+                       }
+               }
+               else {
+                       if (EMAIL_ERROR_CONNECTION_FAILURE != err)
+                               err = EMAIL_ERROR_VALIDATE_ACCOUNT;
+                       goto FINISH_OFF;
+               }
+       }
+#endif
+
+       /* validate connection for pop3/ima */
+       EM_DEBUG_LOG("Validate connection for POP3/IMAP4");
+       if (EMAIL_ERROR_NONE == err) {
+               if (!emcore_check_thread_status())  {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+                if (!emcore_connect_to_remote_mailbox_with_account_info(account, 0, (void **)&tmp_stream, &err) || !tmp_stream)
+                {
+                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed - %d", err);
+                       if (EMAIL_ERROR_AUTHENTICATE == err || EMAIL_ERROR_LOGIN_FAILURE == err) {      /*  wrong password or etc */
+                               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed : Login or Authentication failed - %d", err);
+                       }
+                       else if (EMAIL_ERROR_CONNECTION_FAILURE != err) {
+                               /* err = EMAIL_ERROR_VALIDATE_ACCOUNT */
+                       }
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (!emcore_check_thread_status())  {
+               if (!emcore_delete_account(account->account_id, NULL))
+                       EM_DEBUG_EXCEPTION("emdaemon_delete_account failed [%d]", account->account_id);
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (stream)
+               smtp_close(stream);
+
+       if (tmp_stream)
+               emcore_close_mailbox(0 , tmp_stream);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       emcore_clear_session(session);
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_validate_account(int account_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], err_code[%p]", account_id, err_code);
+
+       int err = EMAIL_ERROR_NONE, ret = false;
+       email_account_t *ref_account = NULL;
+
+
+       if (account_id <= 0)
+    {
+               EM_DEBUG_EXCEPTION("account_id[%p]", account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (ref_account && emcore_validate_account_with_account_info(ref_account, &err) == false) {
+               EM_DEBUG_EXCEPTION("emcore_validate_account_with_account_info failed (%d)", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_delete_account(int account_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], err_code[%p]", account_id, err_code);
+
+       /*  default variabl */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (account_id < FIRST_ACCOUNT_ID)  {
+               EM_DEBUG_EXCEPTION("account_id[%d]", account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       /* Delete all local activities of previous account */
+       
+
+       emstorage_activity_tbl_t activity;
+       memset(&activity, 0x00, sizeof(emstorage_activity_tbl_t));
+       activity.account_id = account_id;
+
+       if (!emcore_delete_activity(&activity, &err)) {
+               EM_DEBUG_LOG("\t emcore_delete_activity failed - %d", err);
+
+               goto FINISH_OFF;
+       }
+#endif
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+       if (false == emcore_clear_partial_body_thd_event_que(&err))
+               EM_DEBUG_EXCEPTION(" emcore_clear_partial_body_thd_event_que [%d]", err);
+
+       if (false == emstorage_delete_full_pbd_activity_data(account_id, true, &err))
+               EM_DEBUG_EXCEPTION("emstorage_delete_full_pbd_activity_data failed [%d]", err);
+
+#endif
+
+#ifdef __FEATURE_USING_ACCOUNT_SVC__
+       {
+               int error_code;
+               email_account_t *account_to_be_deleted;
+
+               account_to_be_deleted = emcore_get_account_reference(account_id);
+               if (account_to_be_deleted && account_to_be_deleted->incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+                       EM_DEBUG_LOG("Calling account_svc_delete with account_svc_id[%d]", account_to_be_deleted->account_svc_id);
+                       error_code = account_connect();
+                       EM_DEBUG_LOG("account_connect returns [%d]", error_code);
+                       error_code = account_delete_from_db_by_id(account_to_be_deleted->account_svc_id);
+                       EM_DEBUG_LOG("account_delete_from_db_by_id returns [%d]", error_code);
+                       error_code = account_disconnect();
+                       EM_DEBUG_LOG("account_disconnect returns [%d]", error_code);
+               }
+
+               if (account_to_be_deleted) {
+                       emcore_free_account(account_to_be_deleted);
+                       EM_SAFE_FREE(account_to_be_deleted);
+               }
+       }
+#endif
+       if (emcore_cancel_all_threads_of_an_account(account_id) < EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("There are some remaining jobs. I couldn't stop them.");
+               err = EMAIL_ERROR_CANNOT_STOP_THREAD;
+               goto FINISH_OFF;
+       }
+
+       /* Delete contact log */
+       if ( ((err = emcore_delete_contacts_log(account_id)) != EMAIL_ERROR_NONE) && (err != EMAIL_ERROR_DATA_NOT_FOUND) ) {
+                       EM_DEBUG_EXCEPTION("emcore_delete_contacts_log failed : [%d]", err);
+       }
+
+       /*  BEGIN TRANSACTION;           */
+       emstorage_begin_transaction(NULL, NULL, NULL);
+       
+       if (!emstorage_delete_account(account_id, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_delete_account failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+       /* emcore_reset_streams(); */
+       emcore_remove_connection_info(account_id);
+#endif
+       
+       if ((err = emcore_delete_all_mails_of_acount(account_id)) != EMAIL_ERROR_NONE)  {
+               EM_DEBUG_EXCEPTION("emcore_delete_all_mails_of_acount failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /*  delete all mailboxes */
+       if (!emstorage_delete_mailbox(account_id, -1, 0, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_delete_mailbox failed - %d", err);
+               goto FINISH_OFF;
+       }
+
+       /*  delete local imap sync mailbox from imap mailbox tabl */
+       if (!emstorage_remove_downloaded_mail(account_id, NULL, NULL, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_remove_downloaded_mail failed - %d", err);
+               goto FINISH_OFF;
+       }
+
+       emcore_display_unread_in_badge();
+       emcore_delete_notification_by_account(account_id);
+       emcore_init_account_reference();
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true) {      /*  COMMIT TRANSACTION; */
+               if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+                       err = EMAIL_ERROR_DB_FAILURE;
+                       ret = false;
+               }
+               if (!emcore_notify_storage_event(NOTI_ACCOUNT_DELETE, account_id, 0, NULL, 0))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_ACCOUNT_DELETE] : Notification Failed >>> ");
+
+       }
+       else {  /*  ROLLBACK TRANSACTION; */
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       err = EMAIL_ERROR_DB_FAILURE;
+               if (!emcore_notify_storage_event(NOTI_ACCOUNT_DELETE_FAIL, account_id, err, NULL, 0))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_ACCOUNT_DELETE] : Notification Failed >>> ");
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_create_account(email_account_t *account, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p], err_code[%p]", account, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int i, count = 0;
+       int private_id = 0;
+       char vconf_private_id[MAX_PATH] = {0, };
+       email_mailbox_t local_mailbox = {0};
+       emstorage_account_tbl_t *temp_account_tbl = NULL;
+
+       if (account == NULL)  {
+               EM_DEBUG_EXCEPTION("account[%p]", account);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_account_count(&count, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_count failed - %d", err);
+               goto FINISH_OFF;
+       }
+
+
+       if (count >= EMAIL_ACCOUNT_MAX)  {
+               EM_DEBUG_EXCEPTION("too many accounts...");
+               err = EMAIL_ERROR_ACCOUNT_MAX_COUNT;
+               goto FINISH_OFF;
+       }
+
+       account->account_id = 0;
+
+       /* Temporarily code - begin */
+       if (account->auto_download_size == 0) {
+               account->auto_download_size = PARTIAL_BODY_SIZE_IN_BYTES;
+               EM_DEBUG_LOG("account->auto_download_size [%d]", account->auto_download_size);
+       }
+
+       if (account->default_mail_slot_size == 0) {
+               account->default_mail_slot_size = 50;
+               EM_DEBUG_LOG("account->default_mail_slot_size [%d]", account->default_mail_slot_size);
+       }
+       /* Temporarily code - end */
+
+       /* check for email address validation */
+       EM_DEBUG_LOG("account->user_email_address[%s]", account->user_email_address);
+       if (account->user_email_address) {
+               if (!em_verify_email_address(account->user_email_address, true, &err)) {
+                       err = EMAIL_ERROR_INVALID_ADDRESS;
+                       EM_DEBUG_EXCEPTION("Invalid Email Address");
+                       goto FINISH_OFF;
+               }
+       }
+
+#ifdef __FEATURE_USING_ACCOUNT_SVC__
+       if (account->incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               int account_svc_id = 0;
+               int error_code;
+               account_h account_handle = NULL;
+
+               error_code = account_connect();
+               if(error_code != ACCOUNT_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("account_connect failed [%d]", error_code);
+                       err = error_code;
+                       goto FINISH_OFF;
+               }
+
+               error_code = account_create(&account_handle);
+               if(error_code != ACCOUNT_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("account_create failed [%d]", error_code);
+                       err = error_code;
+                       account_disconnect();
+                       goto FINISH_OFF;
+               }
+
+               account_set_user_name(account_handle, account->incoming_server_user_name);
+               account_set_domain_name(account_handle, account->account_name); 
+               account_set_email_address(account_handle,  account->user_email_address);
+               account_set_source(account_handle, "SLP EMAIL");
+               account_set_package_name(account_handle, "email-setting-efl");
+               /* account_set_capability(account_handle , ACCOUNT_CAPABILITY_EMAIL, ACCOUNT_CAPABILITY_ENABLED); OLD API */
+               account_set_capability(account_handle , ACCOUNT_SUPPORTS_CAPABILITY_EMAIL , ACCOUNT_CAPABILITY_ENABLED);
+               account_set_sync_support(account_handle, ACCOUNT_SYNC_STATUS_IDLE); /* This means "The account is supporting 'sync' and initialized as idle status" */
+               if (account->logo_icon_path)
+                       account_set_icon_path(account_handle, account->logo_icon_path);
+               error_code = account_insert_to_db(account_handle, &account_svc_id); 
+
+               if (error_code != ACCOUNT_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("account_insert_to_db failed [%d]", error_code);
+                       err = error_code;
+                       if (account_handle)
+                               account_destroy(account_handle);
+
+                       account_disconnect();
+                       goto FINISH_OFF;
+               }
+
+               account->account_svc_id = account_svc_id;
+                       
+               EM_DEBUG_LOG("account_insert_to_db succeed");
+
+               if (account_handle)
+                       account_destroy(account_handle);
+               account_disconnect();
+       }
+#endif  /*  __FEATURE_USING_ACCOUNT_SVC__ */
+
+       temp_account_tbl = em_malloc(sizeof(emstorage_account_tbl_t));
+       if (!temp_account_tbl) {
+               EM_DEBUG_EXCEPTION("allocation failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       em_convert_account_to_account_tbl(account, temp_account_tbl);
+
+       if (!emstorage_add_account(temp_account_tbl, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_add_account failed - %d", err);
+               goto FINISH_OFF;
+       }
+       account->account_id = temp_account_tbl->account_id;
+
+       if (account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) {
+               /* 1. create default local mailbox
+               *    (Inbox, Draft, Outbox, Sentbox) */
+               for (i = 0; i < MAILBOX_COUNT; i++) {
+               EM_DEBUG_LOG("g_default_mbox_name [%d/%d] is [%s]", i, MAILBOX_COUNT, g_default_mbox_name[i]);
+                       local_mailbox.account_id = temp_account_tbl->account_id;
+                       local_mailbox.mailbox_name  = g_default_mbox_name[i];
+                       local_mailbox.mailbox_type      = g_default_mbox_type[i];
+                       if (local_mailbox.mailbox_type == EMAIL_MAILBOX_TYPE_INBOX) {
+                               local_mailbox.local = EMAIL_MAILBOX_FROM_SERVER;
+                       }
+                       else {
+                               local_mailbox.local = EMAIL_MAILBOX_FROM_LOCAL;
+                       }
+                       local_mailbox.alias = g_default_mbox_alias[i];
+                       local_mailbox.mail_slot_size = temp_account_tbl->default_mail_slot_size;
+
+                       if (!emcore_create_mailbox(&local_mailbox, 0, &err))  {
+                               EM_DEBUG_EXCEPTION("emcore_create failed - %d", err);
+                               goto FINISH_OFF;
+                       }
+                       
+               }
+       }
+
+       /* Initialize the noti private id */    
+       SNPRINTF(vconf_private_id, sizeof(vconf_private_id), "%s/%d", VCONF_KEY_NOTI_PRIVATE_ID, account->account_id);
+       if (vconf_get_int(vconf_private_id, &private_id) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+       } else {
+               if (vconf_set_int(vconf_private_id, 0) != 0) {
+                       EM_DEBUG_EXCEPTION("vconf_set_int failed : [NOTI key initialize]");
+               }
+       }
+       
+       ret = true;
+       
+FINISH_OFF: 
+       if (temp_account_tbl)
+               emstorage_free_account(&temp_account_tbl, 1, NULL);
+       
+       if (ret == false && account != NULL)  {
+               if (!emcore_delete_account(account->account_id, NULL))
+                       EM_DEBUG_EXCEPTION("emdaemon_delete_account Failed [%d]", account->account_id);
+       }
+       
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("Return value [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_init_account_reference()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int err = EMAIL_ERROR_NONE;
+       
+       email_account_list_t *account_list = NULL;
+       email_account_list_t **p = NULL;
+       email_account_t *account = NULL;
+       emstorage_account_tbl_t *account_tbl_array = NULL;
+       int count = 0;          
+       int i = 0;
+       
+       /* free account reference if any */
+       emcore_free_account_reference();
+
+       if (!emstorage_get_account_list(&count, &account_tbl_array, true, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for (p = &account_list, i = 0; i < count; i++) {
+               account = em_malloc(sizeof(email_account_t));
+               if (!account) {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               
+               em_convert_account_tbl_to_account(account_tbl_array + i, account);
+
+               *p = (email_account_list_t*) em_malloc(sizeof(email_account_list_t));
+               if (!(*p)) {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       emcore_free_account(account);
+                       EM_SAFE_FREE(account);
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               (*p)->account = account;
+
+               p = &(*p)->next;
+       }
+
+       ENTER_CRITICAL_SECTION(_account_ref_lock);
+       g_account_num = count;
+       g_account_list = account_list;
+       LEAVE_CRITICAL_SECTION(_account_ref_lock);
+
+FINISH_OFF: 
+       if (account_tbl_array)
+               emstorage_free_account(&account_tbl_array, count, NULL);
+       
+       if (err != EMAIL_ERROR_NONE && account_list && i > 0) {
+               g_account_list = account_list;
+               emcore_free_account_reference();
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_free_account_reference()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       ENTER_CRITICAL_SECTION(_account_ref_lock);
+
+       email_account_list_t *p = g_account_list;
+       email_account_list_t *p_next = NULL;
+       while (p) {
+               emcore_free_account(p->account);
+               EM_SAFE_FREE(p->account);
+               
+               p_next = p->next;
+               EM_SAFE_FREE(p);
+               p = p_next;
+       }
+
+       g_account_num = 0;
+       g_account_list = NULL;
+
+       LEAVE_CRITICAL_SECTION(_account_ref_lock);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+INTERNAL_FUNC int emcore_free_account_list(email_account_t **account_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_list[%p], count[%d], err_code[%p]", account_list, count, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (count <= 0 || !account_list || !*account_list)  {
+                       err = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+       }
+               
+       email_account_t *p = *account_list;
+       int i;
+       for (i = 0; i < count; i++)
+               emcore_free_account(p+i);
+               
+       EM_SAFE_FREE(p);
+       *account_list = NULL;
+       
+       ret = true;
+       
+FINISH_OFF: 
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC void emcore_free_option(email_option_t *option)
+{
+       EM_SAFE_FREE(option->display_name_from);
+       EM_SAFE_FREE(option->signature);
+}
+
+
+INTERNAL_FUNC void emcore_free_account(email_account_t *account)
+{
+       if(!account) return;
+
+       EM_SAFE_FREE(account->account_name);
+       EM_SAFE_FREE(account->incoming_server_address);
+       EM_SAFE_FREE(account->user_email_address);
+       EM_SAFE_FREE(account->incoming_server_user_name);
+       EM_SAFE_FREE(account->incoming_server_password);
+       EM_SAFE_FREE(account->outgoing_server_address);
+       EM_SAFE_FREE(account->outgoing_server_user_name);
+       EM_SAFE_FREE(account->outgoing_server_password);
+       EM_SAFE_FREE(account->user_display_name);
+       EM_SAFE_FREE(account->reply_to_address);
+       EM_SAFE_FREE(account->return_address);
+       EM_SAFE_FREE(account->logo_icon_path);
+       EM_SAFE_FREE(account->certificate_path);
+       EM_SAFE_FREE(account->user_data);
+       account->user_data_length = 0;
+       emcore_free_option(&account->options);
+
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+INTERNAL_FUNC void emcore_duplicate_account(const email_account_t *account, email_account_t **account_dup, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p]", account);
+       email_account_t *temp_account = NULL;
+
+       if(!account || !account_dup) { /*prevent 40514*/
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if(err_code) *err_code = EMAIL_ERROR_INVALID_PARAM; 
+               return;
+       }
+
+       *account_dup = em_malloc(sizeof(email_account_t));
+       if(!*account_dup) { /*prevent 40514*/
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               if(err_code) *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               return;
+       }
+
+       memcpy(*account_dup, account , sizeof(email_account_t));
+       temp_account = *account_dup;
+
+       temp_account->account_name                             = EM_SAFE_STRDUP(account->account_name);
+       temp_account->incoming_server_address                  = EM_SAFE_STRDUP(account->incoming_server_address);
+       temp_account->user_email_address                       = EM_SAFE_STRDUP(account->user_email_address);
+       temp_account->incoming_server_user_name                = EM_SAFE_STRDUP(account->incoming_server_user_name);
+       temp_account->incoming_server_password                 = EM_SAFE_STRDUP(account->incoming_server_password);
+       temp_account->outgoing_server_address                  = EM_SAFE_STRDUP(account->outgoing_server_address);
+       temp_account->outgoing_server_user_name                = EM_SAFE_STRDUP(account->outgoing_server_user_name);
+       temp_account->outgoing_server_password                 = EM_SAFE_STRDUP(account->outgoing_server_password);
+       temp_account->user_display_name                        = EM_SAFE_STRDUP(account->user_display_name);
+       temp_account->reply_to_address                         = EM_SAFE_STRDUP(account->reply_to_address);
+       temp_account->return_address                           = EM_SAFE_STRDUP(account->return_address);
+       temp_account->logo_icon_path                           = EM_SAFE_STRDUP(account->logo_icon_path);
+       temp_account->user_data                                = em_memdup(account->user_data, account->user_data_length);
+       temp_account->options.display_name_from                = EM_SAFE_STRDUP(account->options.display_name_from);
+       temp_account->options.signature                        = EM_SAFE_STRDUP(account->options.signature);
+       temp_account->certificate_path                         = EM_SAFE_STRDUP(account->certificate_path);
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC int emcore_get_account_reference_list(email_account_t **account_list, int *count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_list[%p], count[%p], err_code[%p]", account_list, count, err_code);
+       int i, countOfAccounts = 0;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t *accountRef;
+       email_account_list_t *p;
+
+       ENTER_CRITICAL_SECTION(_account_ref_lock);
+
+       if (!account_list || !count)  {
+               EM_DEBUG_EXCEPTION("account_list[%p], count[%p]", account_list, count);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       p = g_account_list;
+
+       while (p) {
+               countOfAccounts++;
+               p = p->next;
+       }
+
+       EM_DEBUG_LOG("Result count[%d]", countOfAccounts);
+       *count = countOfAccounts;
+
+       if (countOfAccounts > 0) {
+               *account_list = malloc(sizeof(email_account_t) * countOfAccounts);
+               if (!*account_list)  {
+                       EM_DEBUG_LOG("malloc failed...");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+       }
+
+       p = g_account_list;
+       for (i = 0; i < countOfAccounts; i++)  {
+               accountRef = (*account_list) + i;
+               memcpy(accountRef, p->account , sizeof(email_account_t));
+               EM_DEBUG_LOG("Result account id[%d], name[%s]", accountRef->account_id, accountRef->account_name);
+               p = p->next;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == false) {
+               if (account_list && *account_list)
+                       EM_SAFE_FREE(*account_list);
+       }
+
+       LEAVE_CRITICAL_SECTION(_account_ref_lock);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+#ifdef __FEATURE_BACKUP_ACCOUNT__
+#include <ss_manager.h>
+
+static int append_data_into_buffer(char **target_buffer, int *target_buffer_lenth, char *input_data, int input_data_length, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN("target_buffer [%p], target_buffer_lenth [%p], input_data [%p], input_data_length[%d]", target_buffer, target_buffer_lenth, input_data, input_data_length);
+       int local_error_code = EMAIL_ERROR_NONE, ret_code = false;
+
+       if (!target_buffer || !target_buffer_lenth || !input_data) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               local_error_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (*target_buffer_lenth > 0 && input_data_length) {
+               EM_DEBUG_LOG("*target_buffer_lenth [%d]", *target_buffer_lenth);
+               *target_buffer = realloc(*target_buffer, (*target_buffer_lenth) + input_data_length);
+               if (!*target_buffer) {
+                       EM_DEBUG_EXCEPTION("realloc failed");
+                       local_error_code = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               memcpy(*target_buffer + (*target_buffer_lenth), input_data, input_data_length);
+               *target_buffer_lenth += input_data_length;
+               EM_DEBUG_LOG("*target_buffer_lenth [%d] input_data_length [%d]", *target_buffer_lenth, input_data_length);
+       }
+       else {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               local_error_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ret_code = true;
+
+FINISH_OFF: 
+
+       if (error_code)
+               *error_code = local_error_code;
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+
+       return ret_code;
+}
+
+
+static int emcore_write_account_into_buffer(char **target_buffer, int *target_buffer_lenth, emstorage_account_tbl_t *account_tbl_ptr, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN("target_buffer [%p], target_buffer_lenth [%p], account_tbl_ptr [%p], error_code [%p]", target_buffer, target_buffer_lenth, account_tbl_ptr, error_code);
+       int local_error_code = EMAIL_ERROR_NONE, ret_code = false, stream_length = 0;
+       email_account_t temp_account = {0};
+       char *byte_stream = NULL;
+
+       if (em_convert_account_tbl_to_account(account_tbl_ptr, &temp_account)) {
+               byte_stream = em_convert_account_to_byte_stream(&temp_account, &stream_length);
+               EM_DEBUG_LOG("stream_length [%d]", stream_length);
+               /*  EM_DEBUG_LOG("incoming_server_password [%s]", temp_account->password) */
+
+               if (byte_stream) {
+                       if (!append_data_into_buffer(target_buffer, target_buffer_lenth, (char *)&stream_length, sizeof(int), &local_error_code)) {
+                               EM_DEBUG_EXCEPTION("append_data_into_buffer failed");
+                               goto FINISH_OFF;
+                       }
+                       EM_DEBUG_LOG("append_data_into_buffer succeed for stream_length");
+
+                       if (!append_data_into_buffer(target_buffer, target_buffer_lenth, byte_stream, stream_length, &local_error_code)) {
+                               EM_DEBUG_EXCEPTION("append_data_into_buffer failed");
+                               goto FINISH_OFF;
+                       }
+                       EM_DEBUG_LOG("append_data_into_buffer succeed for byte_stream");
+               }
+       }
+       else {
+               EM_DEBUG_EXCEPTION("em_convert_account_tbl_to_account failed");
+               local_error_code = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       ret_code = true;
+FINISH_OFF: 
+       emcore_free_account(&temp_account);
+       if (error_code)
+               *error_code = local_error_code;
+
+       EM_SAFE_FREE(byte_stream);
+
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+       return ret_code;
+}
+
+INTERNAL_FUNC int emcore_backup_accounts(const char *file_path, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN("file_path [%s], error_code [%p]", file_path, error_code);
+       int local_error_code = EMAIL_ERROR_NONE, local_error_code_2 = EMAIL_ERROR_NONE, ret_code = false;
+       int select_num, i, target_buff_length = 0;
+       char *target_buffer = NULL;
+       emstorage_account_tbl_t *account_list = NULL;
+
+       if (!file_path) {
+               local_error_code = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               goto FINISH_OFF;        
+       }
+
+       select_num = 1000;
+       
+       if (!emstorage_get_account_list(&select_num, &account_list, true, true, &local_error_code)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", local_error_code);
+               goto FINISH_OFF;        
+       }
+       
+       EM_DEBUG_LOG("select_num [%d]", select_num);
+       
+       if (account_list) {
+               target_buffer = em_malloc(sizeof(int));
+               if (!target_buffer)  {
+                       EM_DEBUG_EXCEPTION("malloc failed");
+                       local_error_code = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               memcpy(target_buffer, (char *)&select_num, sizeof(int));
+               target_buff_length = sizeof(int);
+
+               for (i = 0; i < select_num; i++) {
+                       if (!emcore_write_account_into_buffer(&target_buffer, &target_buff_length, account_list + i, &local_error_code)) {
+                               EM_DEBUG_EXCEPTION("emcore_write_account_into_buffer failed [%d]", local_error_code);
+                               goto FINISH_OFF;        
+                       }
+               }
+
+               EM_DEBUG_LOG("target_buff_length [%d]", target_buff_length);
+
+               ssm_delete_file(file_path, SSM_FLAG_SECRET_OPERATION, NULL);
+               
+               if (ssm_write_buffer(target_buffer, target_buff_length, file_path, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+                       EM_DEBUG_EXCEPTION("ssm_write_buffer failed [%d]", local_error_code);
+                       local_error_code = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;        
+               }
+               
+       }
+
+       ret_code = true;        
+FINISH_OFF: 
+
+       EM_SAFE_FREE(target_buffer);
+       if (account_list)
+               emstorage_free_account(&account_list, select_num, &local_error_code_2);
+
+       if (error_code)
+               *error_code = local_error_code;
+
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+       return ret_code;
+}
+
+INTERNAL_FUNC int emcore_restore_accounts(const char *file_path, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN("file_path [%s], error_code [%p]", file_path, error_code);
+       int local_error_code = EMAIL_ERROR_NONE, ret_code = false, buffer_length = 0, read_length = 0;
+       int account_count = 0, i = 0, account_stream_length = 0;
+       char *temp_buffer = NULL, *account_stream = NULL, *buffer_ptr = NULL;
+       email_account_t temp_account = {0};
+       email_account_t *account_list = NULL;
+
+       ssm_file_info_t sfi;
+
+       if (!file_path) {
+               local_error_code = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               goto FINISH_OFF;        
+       }
+
+       if (emcore_get_account_reference_list(&account_list, &account_count, &ret_code)) {
+               for (i = 0; i < account_count; i++) {
+                       if (account_list[i].incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+                               if (!emcore_delete_account(account_list[i].account_id, &ret_code)) {
+                                       local_error_code = EMAIL_ERROR_INVALID_ACCOUNT;
+                                       EM_DEBUG_EXCEPTION("emcore_delete_account failed");
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+
+               EM_SAFE_FREE(account_list);
+       }
+
+       if (ssm_getinfo(file_path, &sfi, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+               EM_DEBUG_EXCEPTION("ssm_getinfo() failed.");
+               ret_code = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       buffer_length = sfi.originSize;
+       EM_DEBUG_LOG("account buffer_length[%d]", buffer_length);
+       if ((temp_buffer = (char *)em_malloc(buffer_length + 1)) == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               ret_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (ssm_read(file_path, temp_buffer, buffer_length, (size_t *)&read_length, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+               EM_DEBUG_EXCEPTION("ssm_read() failed.");
+               ret_code = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("read_length[%d]", read_length);
+
+       if (buffer_length == read_length) {
+               memcpy((void *)&account_count, temp_buffer, sizeof(int));
+               buffer_ptr = temp_buffer + sizeof(int);
+
+               EM_DEBUG_LOG("account_count[%d]", account_count);               
+
+               for (i = 0; i < account_count; i++) {
+                       memcpy((void *)&account_stream_length, buffer_ptr, sizeof(int));
+                       buffer_ptr += sizeof(int);
+                       EM_DEBUG_LOG("account_stream_length [%d]", account_stream_length);
+                       if (account_stream_length) {
+                               account_stream = em_malloc(account_stream_length);
+                               if (!account_stream) {
+                                       EM_DEBUG_EXCEPTION("em_malloc() failed.");
+                                       ret_code = EMAIL_ERROR_OUT_OF_MEMORY ;
+                                       goto FINISH_OFF;
+                               }
+                               memcpy(account_stream, buffer_ptr, account_stream_length);
+
+                               em_convert_byte_stream_to_account(account_stream, account_stream_length, &temp_account);
+                               EM_SAFE_FREE(account_stream);
+                       
+                               if (!emcore_create_account(&temp_account, &ret_code)) {
+                                       EM_DEBUG_EXCEPTION("emcore_create_account() failed.");
+                                       goto FINISH_OFF;
+                               }
+
+                               emcore_free_account(&temp_account);
+                       }
+                       buffer_ptr += account_stream_length;
+                       account_stream_length = 0;
+               }
+       } else {
+               EM_DEBUG_EXCEPTION("ssm_read() failed.");
+               ret_code = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       ret_code = true;        
+FINISH_OFF: 
+       emcore_free_account(&temp_account);
+       EM_SAFE_FREE(account_stream);
+       EM_SAFE_FREE(temp_buffer);
+
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+       return ret_code;
+}
+
+#endif /*  __FEATURE_BACKUP_ACCOUNT_ */
+
+
+
+INTERNAL_FUNC int emcore_query_server_info(const char* domain_name, email_server_info_t **result_server_info)
+{
+       EM_DEBUG_FUNC_BEGIN("domain_name [%s], result_server_info [%p]", domain_name, result_server_info);
+       int ret_code = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+       return ret_code;
+}
+
+
+INTERNAL_FUNC int emcore_free_server_info(email_server_info_t **target_server_info)
+{
+       EM_DEBUG_FUNC_BEGIN("result_server_info [%p]", target_server_info);
+       int i, ret_code = EMAIL_ERROR_NONE;
+       email_server_info_t *server_info = NULL;
+
+       if(target_server_info && *target_server_info) {
+               server_info = *target_server_info;
+               EM_SAFE_FREE(server_info->service_name);
+               for(i = 0; i < server_info->protocol_conf_count; i++) {
+                       EM_SAFE_FREE(server_info->protocol_config_array[i].server_addr);
+               }
+               EM_SAFE_FREE(server_info->protocol_config_array);
+               EM_SAFE_FREE(server_info);
+       }
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+       return ret_code;        
+}
+
+INTERNAL_FUNC int emcore_save_default_account_id(int input_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d]", input_account_id);
+       int ret_code = EMAIL_ERROR_NONE, result_value = 0;
+
+       result_value = vconf_set_int(VCONF_KEY_DEFAULT_ACCOUNT_ID, input_account_id);
+       if (result_value < 0) {
+               EM_DEBUG_EXCEPTION("vconf_set_int failed [%d]", result_value);
+               ret_code = EMAIL_ERROR_SYSTEM_FAILURE;
+       }
+
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+       return ret_code;        
+}
+
+static int _recover_from_invalid_default_account_id(int *output_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%p]", output_account_id);
+       int ret_code = EMAIL_ERROR_NONE;
+       int account_count = 100;
+       emstorage_account_tbl_t *result_account_list = NULL;
+
+       if (output_account_id == NULL) {
+               ret_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if(!emstorage_get_account_list(&account_count, &result_account_list, false, false, &ret_code) || !result_account_list) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list() failed [%d]", ret_code);
+               *output_account_id = 0;
+               goto FINISH_OFF;
+       }
+
+       if (account_count > 0) {
+               *output_account_id = result_account_list[0].account_id;
+       }
+
+       EM_DEBUG_LOG("output_account_id [%d]", *output_account_id);
+
+FINISH_OFF:
+
+       if (result_account_list)
+               emstorage_free_account(&result_account_list, account_count, NULL);
+
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+       return ret_code;
+}
+
+INTERNAL_FUNC int emcore_load_default_account_id(int *output_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%p]", output_account_id);
+       int ret_code = EMAIL_ERROR_NONE;
+       int result_value = 0;
+       emstorage_account_tbl_t *result_account = NULL;
+       
+       if (output_account_id == NULL) {
+               ret_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       result_value = vconf_get_int(VCONF_KEY_DEFAULT_ACCOUNT_ID, output_account_id);
+
+       if (result_value < 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int() failed [%d]", result_value);
+               ret_code = EMAIL_ERROR_SYSTEM_FAILURE;
+               *output_account_id = 0;
+       }
+
+       if (*output_account_id != 0) {
+               if (!emstorage_get_account_by_id(*output_account_id, EMAIL_ACC_GET_OPT_DEFAULT, &result_account, false, &ret_code)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id() failed [%d]", ret_code);
+                       if(ret_code == EMAIL_ERROR_ACCOUNT_NOT_FOUND)
+                               *output_account_id = 0;
+                       else
+                               goto FINISH_OFF;
+               }
+       }
+
+       if (*output_account_id == 0) {
+               if ( (ret_code = _recover_from_invalid_default_account_id(output_account_id)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("_recover_from_invalid_default_account() failed [%d]", ret_code);
+                       *output_account_id = 0;
+               }
+       }
+
+FINISH_OFF:
+       if (result_account)
+               emstorage_free_account(&result_account, 1, NULL);
+       
+       EM_DEBUG_FUNC_END("ret_code [%d]", ret_code);
+       return ret_code;        
+}
+
+INTERNAL_FUNC int emcore_recover_from_secured_storage_failure()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       int account_count = 50;
+       emstorage_account_tbl_t *temp_account_tbl_list = NULL;
+       emstorage_account_tbl_t *temp_account_tbl      = NULL;
+
+       if (!emstorage_get_account_list(&account_count, &temp_account_tbl_list, true, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < account_count; i++) {
+               if(!emstorage_get_account_by_id(temp_account_tbl_list[i].account_id, EMAIL_ACC_GET_OPT_DEFAULT | EMAIL_ACC_GET_OPT_PASSWORD, &temp_account_tbl, true, &err)) {
+                       if(err == EMAIL_ERROR_SECURED_STORAGE_FAILURE) {
+                               if(!emcore_delete_account(temp_account_tbl_list[i].account_id, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_delete_account failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+       }
+
+FINISH_OFF:
+
+       emstorage_free_account(&temp_account_tbl_list, account_count, NULL);
+       emstorage_free_account(&temp_account_tbl, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_update_sync_status_of_account(int input_account_id, email_set_type_t input_set_operator, int input_sync_status)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_set_operator [%d], input_sync_status [%d]", input_account_id, input_set_operator, input_sync_status);
+       int err = EMAIL_ERROR_NONE;
+
+#ifdef __FEATURE_USING_ACCOUNT_SVC__
+       int err_from_account_svc = 0;
+       emstorage_account_tbl_t *account_tbl_data = NULL;
+       if (input_account_id != ALL_ACCOUNT && (input_sync_status == SYNC_STATUS_SYNCING)) {
+               if (!emstorage_get_account_by_id(input_account_id, EMAIL_ACC_GET_OPT_DEFAULT | EMAIL_ACC_GET_OPT_OPTIONS, &account_tbl_data, true, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               err_from_account_svc = account_connect();
+               EM_DEBUG_LOG("account_connect returns [%d]", err_from_account_svc);
+
+               EM_DEBUG_LOG("account_tbl_data->account_svc_id [%d]", account_tbl_data->account_svc_id);
+
+               if (input_set_operator == SET_TYPE_SET)
+                       err_from_account_svc = account_update_sync_status_by_id(account_tbl_data->account_svc_id, ACCOUNT_SYNC_STATUS_RUNNING);
+               else if(input_set_operator == SET_TYPE_MINUS)
+                       err_from_account_svc = account_update_sync_status_by_id(account_tbl_data->account_svc_id, ACCOUNT_SYNC_STATUS_IDLE);
+
+               EM_DEBUG_LOG("account_update_sync_status_by_id returns [%d]", err_from_account_svc);
+
+               err_from_account_svc = account_disconnect();
+               EM_DEBUG_LOG("account_disconnect returns [%d]", err_from_account_svc);
+       }
+#endif /* __FEATURE_USING_ACCOUNT_SVC__ */
+
+       if (!emstorage_update_sync_status_of_account(input_account_id, input_set_operator, input_sync_status, true, &err))
+               EM_DEBUG_EXCEPTION("emstorage_update_sync_status_of_account failed [%d]", err);
+
+#ifdef __FEATURE_USING_ACCOUNT_SVC__
+FINISH_OFF:
+       if (account_tbl_data)
+               emstorage_free_account(&account_tbl_data, 1, NULL);
+#endif /* __FEATURE_USING_ACCOUNT_SVC__ */
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-core/email-core-api.c b/email-core/email-core-api.c
new file mode 100755 (executable)
index 0000000..0ca382f
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-api.h
+ * Desc :  Mail Engine API
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "c-client.h"
+#include "email-core-global.h"
+#include "email-network.h"
+#include "email-core-event.h"
+#include "email-core-mailbox.h"
+#include "email-core-utils.h"
+#include "email-debug-log.h"
+
+extern void *
+pop3_parameters(long function, void *value);
+extern void *
+imap_parameters(long function, void *value);
+
+
+
+/* initialize mail core */
+INTERNAL_FUNC int emcore_init(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (err_code != NULL) {
+               *err_code = EMAIL_ERROR_NONE;
+       }
+
+       mail_link(&imapdriver);  /*  link in the imap driver  */
+       mail_link(&pop3driver);  /*  link in the pop3 driver  */
+
+       mail_link(&unixdriver);  /*  link in the unix driver  */
+       mail_link(&dummydriver); /*  link in the dummy driver  */
+
+       ssl_onceonlyinit();
+
+       auth_link(&auth_md5);    /*  link in the md5 authenticator  */
+       auth_link(&auth_pla);    /*  link in the pla authenticator  */
+       auth_link(&auth_log);    /*  link in the log authenticator  */
+
+       /* Disabled to authenticate with plain text */
+       mail_parameters(NIL, SET_DISABLEPLAINTEXT, (void *) 2);
+
+       /* Set max trials for login */
+       imap_parameters(SET_MAXLOGINTRIALS, (void *)1);
+       pop3_parameters(SET_MAXLOGINTRIALS, (void *)1);
+       smtp_parameters(SET_MAXLOGINTRIALS, (void *)1);
+
+       mail_parameters(NIL, SET_SSLCERTIFICATEQUERY, (void *)emnetwork_callback_ssl_cert_query);
+       mail_parameters(NIL, SET_SSLCAPATH, (void *)SSL_CERT_DIRECTORY);
+
+       /* Set time out in second */
+       mail_parameters(NIL, SET_OPENTIMEOUT  , (void *)50);
+       mail_parameters(NIL, SET_READTIMEOUT  , (void *)180);
+       mail_parameters(NIL, SET_WRITETIMEOUT , (void *)180);
+       mail_parameters(NIL, SET_CLOSETIMEOUT , (void *)30);
+
+       if (err_code)
+               *err_code = EMAIL_ERROR_NONE;
+
+    return true;
+}
+
diff --git a/email-core/email-core-cert.c b/email-core/email-core-cert.c
new file mode 100755 (executable)
index 0000000..c0891b1
--- /dev/null
@@ -0,0 +1,668 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-cert.h
+ * Desc :  Certificate API
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#include <openssl/pkcs7.h>
+#include <openssl/pkcs12.h>
+#include <openssl/pem.h>
+#include <openssl/err.h>
+#include <cert-service.h>
+#include <glib.h>
+#include <cert-svc/ccert.h>
+#include <cert-svc/cstring.h>
+#include <cert-svc/cpkcs12.h>
+#include <cert-svc/cinstance.h>
+#include <cert-svc/cprimitives.h>
+
+#include "email-core-cert.h"
+#include "email-core-mail.h"
+#include "email-core-utils.h"
+#include "email-utilities.h"
+#include "email-storage.h"
+#include "email-debug-log.h"
+
+#define READ_MODE "r"
+#define WRITE_MODE "w"
+
+#define TRUSTED_USER "trusteduser/email/"
+
+typedef enum {
+       CERT_TYPE_ETC          = 0,
+       CERT_TYPE_PKCS12,       
+       CERT_TYPE_PKCS7,
+       CERT_TYPE_P7S
+} cert_type;
+
+static int emcore_get_certificate_type(char *extension, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("extensiong is [%s]", extension);
+       int index = 0;
+       int type = 0;
+       int err = EMAIL_ERROR_NONE;
+       char *supported_file_type[] = {"pfx", "p12", "p7s", "pem", "der", "crt", "cer", NULL};
+
+       if (!extension) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       while(supported_file_type[index]) {
+               EM_DEBUG_LOG("certificate extension[%d]:[%s]", index, supported_file_type[index]);
+               if (strcasecmp(extension, supported_file_type[index]) == 0) {
+                       switch (index) {
+                       case 0:
+                       case 1:
+                               type = CERT_TYPE_PKCS12;
+                               err = EMAIL_ERROR_INVALID_CERTIFICATE;
+                               break;
+                       case 2:
+                               type = CERT_TYPE_P7S;
+                               break;
+                       case 3:
+                       case 4:
+                       case 5:
+                       case 6:
+                               type = CERT_TYPE_PKCS7;
+                               break;
+                       default:
+                               type = CERT_TYPE_ETC;
+                               err = EMAIL_ERROR_INVALID_CERTIFICATE;
+                               break;                  
+                       }
+               }
+               index++;
+       }
+
+FINISH_OFF:
+
+       if (err_code) {
+               *err_code = err;
+       }
+
+       EM_DEBUG_FUNC_END("File type is [%d]", type);
+       return type;
+}
+/*     
+static GList *emcore_make_glist_from_string(char *email_address_list)
+{
+       EM_DEBUG_FUNC_BEGIN("email_address list : [%s]", email_address_list);
+       int index = 0;
+       const gchar seperator = 0x01;
+       GList *email_list = NULL;
+       gchar *p_email_address_list = NULL;
+       gchar **token_list = NULL;
+
+       p_email_address_list = g_strdup(email_address_list);
+
+       token_list = g_strsplit(p_email_address_list, &seperator, -1);
+       while (token_list[index] != NULL) {
+               email_list = g_list_append(email_list, token_list[index]);
+               index++;
+       }
+       
+       if (p_email_address_list)
+               g_free(p_email_address_list);
+
+       return email_list;      
+}
+
+static char *emcore_store_public_certificate(STACK_OF(X509) *certificates, char *email_address, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int index = 0;
+       int err = EMAIL_ERROR_NONE;
+       char *file_path = NULL;
+       BIO *outfile = NULL;
+
+       file_path = (char *)em_malloc(256);
+       if (file_path == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(file_path, 256, "%s%s%s", CERT_SVC_STORE_PATH, TRUSTED_USER, email_address);
+       outfile = BIO_new_file(file_path, WRITE_MODE);
+       if (outfile == NULL) {
+               EM_DEBUG_EXCEPTION("File open failed[write mode]");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       for (index = 0; index < sk_X509_num(certificates); index++) {
+               EM_DEBUG_LOG("Write the certificate in pem file : [%d]", index);
+               PEM_write_bio_X509(outfile, sk_X509_value(certificates, index));
+       }
+       
+FINISH_OFF:
+
+       if (outfile)
+               BIO_free(outfile);
+
+       EM_DEBUG_FUNC_END();
+
+       return file_path;
+}
+*/
+#if 0
+INTERNAL_FUNC int emcore_load_PFX_file(char *certificate, char *password, EVP_PKEY **pri_key, X509 **cert, STACK_OF(X509) **ca, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("Certificate path : [%s], password : [%s]", certificate, password);
+
+       int err = EMAIL_ERROR_NONE;
+       int ret = false;
+       FILE *fp = NULL;
+       PKCS12 *p12 = NULL;
+
+       OpenSSL_add_all_algorithms();
+       ERR_load_crypto_strings();
+       if (!(fp = fopen(certificate, "rb"))) {
+               EM_DEBUG_EXCEPTION("fopen failed : [%s]", certificate);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       
+       p12 = d2i_PKCS12_fp(fp, NULL);
+       if (!p12) {
+               EM_DEBUG_EXCEPTION("d2i_PKCS12_fp failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!PKCS12_parse(p12, password, pri_key, cert, ca)) {
+               EM_DEBUG_EXCEPTION("PKCS12_parse failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (fp)
+               fclose(fp);
+
+       if (p12)
+               PKCS12_free(p12);
+
+       if (err_code)
+               *err_code = err;
+
+       return ret;     
+}
+#endif
+
+INTERNAL_FUNC int emcore_load_PFX_file(char *certificate, EVP_PKEY **pri_key, X509 **cert, STACK_OF(X509) **ca, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate : [%s]", certificate);
+       int err = EMAIL_ERROR_NONE;
+       int ret = false;
+       size_t key_size = 0;
+       char *private_key = NULL;
+
+       /* Variable for certificate */
+       X509 *t_cert = NULL;
+       BIO *bio_mem = NULL;
+//     STACK_OF(X509) *t_ca = NULL;
+       
+       /* Variable for private key */
+       EVP_PKEY *t_pri_key = NULL;
+
+       CertSvcString csstring;
+       CertSvcInstance cert_instance;
+       CertSvcCertificate csc_cert;
+       CertSvcCertificateList certificate_list;
+
+       if (certificate == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* Create instance */
+       err = certsvc_instance_new(&cert_instance);
+       if (err != CERTSVC_SUCCESS) {
+               EM_DEBUG_EXCEPTION("certsvc_instance_new failed : [%d]", err);
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Make the pfxID string */
+       err = certsvc_string_new(cert_instance, certificate, EM_SAFE_STRLEN(certificate), &csstring);
+       if (err != CERTSVC_SUCCESS) {
+               EM_DEBUG_EXCEPTION("certsvc_string_new failed : [%d]", err);
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Load the certificate list of pkcs12 type */
+       err = certsvc_pkcs12_load_certificate_list(cert_instance, csstring, &certificate_list);
+       if (err != CERTSVC_SUCCESS) {
+               EM_DEBUG_EXCEPTION("certsvc_pkcs12_load_certificate_list failed : [%d]", err);
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Get a certificate */
+       err = certsvc_certificate_list_get_one(certificate_list, 0, &csc_cert);
+       if (err != CERTSVC_SUCCESS) {
+               EM_DEBUG_EXCEPTION("certsvc_certificate_list_get_one failed : [%d]", err);
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Convert from char to X509 */
+       err = certsvc_certificate_dup_x509(csc_cert, &t_cert);
+       if (t_cert == NULL || err != CERTSVC_SUCCESS) {
+               EM_DEBUG_EXCEPTION("certsvc_certificate_dup_x509 failed");
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Get the private key */
+       err = certsvc_pkcs12_private_key_dup(cert_instance, csstring, &private_key, &key_size);
+       if (err != CERTSVC_SUCCESS) {
+               EM_DEBUG_EXCEPTION("certsvc_pkcs12_private_key_dup failed : [%d]", err);
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("key_size : [%d], private_key : [%s]", key_size, private_key);
+
+       /* Convert char to pkey */
+       bio_mem = BIO_new(BIO_s_mem());
+       if (bio_mem == NULL) {
+               EM_DEBUG_EXCEPTION("malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (BIO_write(bio_mem, private_key, key_size) <= 0) {
+               EM_DEBUG_EXCEPTION("BIO_write failed");
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       t_pri_key = PEM_read_bio_PrivateKey(bio_mem, NULL, 0, NULL);
+       if (t_pri_key == NULL) {
+               EM_DEBUG_EXCEPTION("PEM_read_bio_PrivateKey failed");
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+       
+FINISH_OFF:
+
+       if (bio_mem)
+               BIO_free(bio_mem);
+
+       if (true) {
+               if (cert)
+                       *cert = t_cert;
+
+               if (pri_key)
+                       *pri_key = t_pri_key;
+       } else {
+               X509_free(t_cert);
+               EVP_PKEY_free(t_pri_key);
+       }
+
+       if (private_key)
+               EM_SAFE_FREE(private_key);
+
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_add_public_certificate(char *public_cert_path, char *save_name, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("Path [%s], filename [%s]", public_cert_path, save_name);
+       int err = EMAIL_ERROR_NONE;     
+       int ret = false;
+       int validity = 0;
+       int cert_type = 0;
+       char temp_file[512] = {0, };
+       char temp_save_name[512] = {0, };
+       char filepath[512] = {0, };
+       char *extension = NULL;
+       emstorage_certificate_tbl_t *cert = NULL;
+       CERT_CONTEXT *context = NULL;
+
+       if (public_cert_path == NULL || save_name == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;                
+       }
+       
+       /* Initilize the structure of certificate */
+       context = cert_svc_cert_context_init();
+
+       /* Parse the file type */
+       extension = em_get_extension_from_file_path(public_cert_path, NULL);
+       if (extension == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* Get the file type information */
+       cert_type = emcore_get_certificate_type(extension, &err);
+       if (!cert_type || err == EMAIL_ERROR_INVALID_CERTIFICATE) {
+               EM_DEBUG_EXCEPTION("Invalid certificate");
+               goto FINISH_OFF;
+       }
+
+       /* Create temp file and rename */
+       if (cert_type == CERT_TYPE_P7S) {
+               extension = "der";
+       }
+       
+       SNPRINTF(temp_file, sizeof(temp_file), "%s%s%s.%s", MAILTEMP, DIR_SEPERATOR, save_name, extension);
+       EM_DEBUG_LOG("temp cert path : [%s]", temp_file);
+
+       if (!emstorage_copy_file(public_cert_path, temp_file, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       /* Load the public certificate */
+       err = cert_svc_load_file_to_context(context, temp_file);
+       if (err != CERT_SVC_ERR_NO_ERROR) {
+               EM_DEBUG_EXCEPTION("Load cert failed : [%d]", err);
+               err = EMAIL_ERROR_INVALID_CERTIFICATE;
+               goto FINISH_OFF;
+       }
+
+       /* Verify the certificate */
+       if (cert_svc_verify_certificate(context, &validity) != CERT_SVC_ERR_NO_ERROR) {
+               EM_DEBUG_EXCEPTION("cert_svc_verify_certificate failed");
+//             err = EMAIL_ERROR_INVALID_CERTIFICATE;
+//             goto FINISH_OFF;
+       } 
+
+       if (validity <= 0) {
+               EM_DEBUG_LOG("Invalid certificate");
+       }
+
+       /* Load the certificate information */
+       if (cert_svc_extract_certificate_data(context) != CERT_SVC_ERR_NO_ERROR) {
+               EM_DEBUG_EXCEPTION("Extract the certificate failed");
+               err = EMAIL_ERROR_UNKNOWN;
+               goto FINISH_OFF;
+       }
+
+       /* Store the certificate file to trusted folder */
+       if (cert_svc_add_certificate_to_store(temp_file, TRUSTED_USER) != CERT_SVC_ERR_NO_ERROR) {
+               EM_DEBUG_EXCEPTION("Add certificate to trusted folder");
+               err = EMAIL_ERROR_UNKNOWN;
+               goto FINISH_OFF;
+       }
+
+       /* Store the certificate to DB */
+       SNPRINTF(filepath, sizeof(filepath), "%s%s%s.%s", CERT_SVC_STORE_PATH, TRUSTED_USER, save_name, extension);
+       SNPRINTF(temp_save_name, sizeof(temp_save_name), "<%s>", save_name);
+
+       cert = (emstorage_certificate_tbl_t *)em_malloc(sizeof(emstorage_certificate_tbl_t));
+       if (cert == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       cert->issue_year = context->certDesc->info.validPeriod.firstYear;
+       cert->issue_year = context->certDesc->info.validPeriod.firstYear;
+       cert->issue_month = context->certDesc->info.validPeriod.firstMonth;
+       cert->issue_day = context->certDesc->info.validPeriod.firstDay;         
+       cert->expiration_year= context->certDesc->info.validPeriod.secondYear;          
+       cert->expiration_month = context->certDesc->info.validPeriod.secondMonth;               
+       cert->expiration_day = context->certDesc->info.validPeriod.secondDay;                           
+       cert->issue_organization_name = EM_SAFE_STRDUP(context->certDesc->info.issuer.organizationName);
+       cert->email_address = EM_SAFE_STRDUP(temp_save_name);
+       cert->subject_str = EM_SAFE_STRDUP(context->certDesc->info.issuerStr);          
+       cert->filepath = EM_SAFE_STRDUP(filepath);                              
+
+       if (emstorage_add_certificate(cert, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_add_certificate failed");
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_delete_file(public_cert_path, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_delete_file failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       
+       emstorage_free_certificate(&cert, 1, NULL);
+
+       cert_svc_cert_context_final(context);
+
+       if (err_code != NULL) {
+               *err_code = err;
+       }
+
+       EM_DEBUG_FUNC_END();
+
+       return ret;
+
+}
+
+INTERNAL_FUNC int emcore_delete_public_certificate(char *email_address, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_certificate_tbl_t *certificate = NULL;
+
+       if (email_address == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_certificate_by_email_address(email_address, &certificate, false, 0, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_certificate failed");
+               goto FINISH_OFF;
+       }
+
+       if (remove(certificate->filepath) < 0) {
+               EM_DEBUG_EXCEPTION("remove failed : [%s]", certificate->filepath);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_delete_certificate(certificate->certificate_id, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_delete_certificate failed");
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+FINISH_OFF:
+
+       if (certificate != NULL)
+               emstorage_free_certificate(&certificate, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_verify_signature(char *p7s_file_path, char *mime_entity, int *validity, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("path : [%s], mime_entity : [%s]", p7s_file_path, mime_entity);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int t_validity = 0;
+       int flags = PKCS7_NOVERIFY;
+
+       BIO *bio_p7s = NULL;
+
+       BIO *bio_indata = NULL;
+
+       PKCS7 *pkcs7_p7s = NULL;
+
+       /* Initialize */
+       OpenSSL_add_all_algorithms();
+
+       /* Open p7s file */
+       bio_p7s = BIO_new_file(p7s_file_path, INMODE);
+       if (!bio_p7s) {
+               EM_DEBUG_EXCEPTION("File open failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Open input data file */
+       bio_indata = BIO_new_file(mime_entity, INMODE);
+       if (!bio_p7s) {
+               EM_DEBUG_EXCEPTION("File open failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Load the p7s file */
+       pkcs7_p7s = d2i_PKCS7_bio(bio_p7s, NULL);
+       if (!pkcs7_p7s) {
+               EM_DEBUG_EXCEPTION("d2i_PKCS7_bio failed");
+               err = EMAIL_ERROR_LOAD_CERTIFICATE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!PKCS7_verify(pkcs7_p7s, NULL, NULL, bio_indata, NULL, flags)) {
+               EM_DEBUG_EXCEPTION("PKCS7_verify failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       t_validity = 1;
+
+       ret = true;
+
+FINISH_OFF:
+
+       EVP_cleanup();
+
+       if (pkcs7_p7s)
+               PKCS7_free(pkcs7_p7s);
+
+       if (bio_p7s)
+               BIO_free(bio_p7s);
+
+       if (bio_indata)
+               BIO_free(bio_indata);
+
+       if (validity)
+               *validity = t_validity;
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_verify_certificate(char *certificate, int *validity, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int p_validity = 0;
+
+       CERT_CONTEXT *context = NULL;
+       
+       context = cert_svc_cert_context_init();
+
+       err = cert_svc_load_file_to_context(context, certificate);
+       if (err != CERT_SVC_ERR_NO_ERROR) {
+               EM_DEBUG_EXCEPTION("Certificate load failed");
+               goto FINISH_OFF;
+       }
+
+       err = cert_svc_verify_certificate(context, &p_validity);
+       if (err != CERT_SVC_ERR_NO_ERROR) {
+               EM_DEBUG_EXCEPTION("Certificate verify failed");
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (validity != NULL) 
+               *validity = p_validity;
+
+       if (err_code != NULL) {
+               *err_code = err;
+       }
+
+       cert_svc_cert_context_final(context);
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_free_certificate(email_certificate_t **certificate, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate [%p], count [%d]", certificate, count);
+       
+       if (count <= 0 || !certificate || !*certificate) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code)   
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       email_certificate_t *p_certificate = *certificate;
+       int i;
+       
+       for (i=0;i<count;i++) {
+               EM_SAFE_FREE(p_certificate[i].issue_organization_name);
+               EM_SAFE_FREE(p_certificate[i].email_address);
+               EM_SAFE_FREE(p_certificate[i].subject_str);
+               EM_SAFE_FREE(p_certificate[i].filepath);
+       }
+
+       EM_SAFE_FREE(p_certificate);
+       *certificate = NULL;
+
+       if (err_code)
+               *err_code = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
diff --git a/email-core/email-core-event.c b/email-core/email-core-event.c
new file mode 100755 (executable)
index 0000000..d42c755
--- /dev/null
@@ -0,0 +1,3698 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File :  email-core-event_data.h
+ * Desc :  Mail Engine Event
+ *
+ * Auth :
+ *
+ * History :
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#include <stdio.h>
+#include <glib.h>
+#include <malloc.h>
+#include <pthread.h>
+#include <vconf.h>
+#include <signal.h>
+#include <contacts.h>
+#include "c-client.h"
+#include "email-convert.h"
+#include "email-storage.h"
+#include "email-network.h"
+#include "email-device.h"
+#include "email-utilities.h"
+#include "email-daemon-auto-poll.h"
+#include "email-core-global.h"
+#include "email-core-account.h"
+#include "email-core-event.h"
+#include "email-core-utils.h"
+#include "email-core-mailbox.h"
+#include "email-core-imap-mailbox.h"
+#include "email-core-mail.h"
+#include "email-core-mailbox-sync.h"
+#include "email-core-smtp.h"
+#include "email-core-utils.h"
+#include "email-core-sound.h"
+#include "email-core-signal.h"
+#include "email-debug-log.h"
+
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+/*[h.gahlaut] - All static variable declaration for partial body download thread are done here */
+
+#define TOTAL_PARTIAL_BODY_EVENTS 100
+
+static email_event_partial_body_thd g_partial_body_thd_event_que[TOTAL_PARTIAL_BODY_EVENTS];
+
+static int g_partial_body_thd_next_event_idx = 0;                      /* Index of Next Event to be processed in the queue*/
+static int g_partial_body_thd_loop = 1;                                                /* Variable to make a continuos while loop */
+static int g_partial_body_thd_queue_empty = true;                      /* Variable to determine if event queue is empty.True means empty*/
+static int g_partial_body_thd_queue_full = false;                      /* Variable to determine if event queue is full. True means full*/
+static int g_pb_thd_local_activity_continue = true;                    /* Variable to control local activity sync */
+int g_pbd_thd_state = false;                                                           /* false :  thread is sleeping , true :  thread is working */
+
+static pthread_mutex_t _partial_body_thd_event_queue_lock = PTHREAD_MUTEX_INITIALIZER; /* Mutex to protect event queue */
+static pthread_cond_t  _partial_body_thd_cond = PTHREAD_COND_INITIALIZER;                              /* Condition variable on which partial body thread is waiting  */
+thread_t g_partial_body_thd ;                                                          /* Determines if thread is created or not. Non Null means thread is created */
+
+email_event_partial_body_thd g_partial_body_bulk_dwd_que[BULK_PARTIAL_BODY_DOWNLOAD_COUNT];
+static int g_partial_body_bulk_dwd_next_event_idx = 0;         /* Index of Next Event to be processed in the queue*/
+static int g_partial_body_bulk_dwd_queue_empty = true;
+
+static pthread_mutex_t _state_variables_lock;
+
+/*[h.gahlaut] - All static function declaration for partial body download thread are done here */
+
+static int emcore_retrieve_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code);
+static int emcore_copy_partial_body_thd_event(email_event_partial_body_thd *src, email_event_partial_body_thd *dest, int *error_code);
+static void emcore_pb_thd_set_local_activity_continue(int flag);
+static int emcore_set_pbd_thd_state(int flag);
+static int emcore_clear_bulk_pbd_que(int *err_code);
+int emcore_mail_partial_body_download(email_event_partial_body_thd *pbd_event, int *error_code);
+
+#endif
+
+#ifdef ENABLE_IMAP_IDLE_THREAD
+extern int g_imap_idle_thread_alive;
+extern int imap_idle_thread;
+#endif /* ENABLE_IMAP_IDLE_THREAD */
+INTERNAL_FUNC int g_client_count = 0;
+INTERNAL_FUNC int g_client_run = 0 ;
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+INTERNAL_FUNC int g_local_activity_run = 0;
+INTERNAL_FUNC int g_save_local_activity_run = 0;
+#endif
+
+
+#define EVENT_QUEUE_MAX 32
+
+typedef struct EVENT_CALLBACK_ELEM
+{
+       email_event_callback callback;
+       void *event_data;
+       struct EVENT_CALLBACK_ELEM *next;
+} EVENT_CALLBACK_LIST;
+
+static pthread_mutex_t _event_available_lock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t  _event_available_signal = PTHREAD_COND_INITIALIZER;
+static pthread_mutex_t *_event_callback_table_lock = NULL;
+static pthread_mutex_t *_event_queue_lock = NULL;
+static EVENT_CALLBACK_LIST *_event_callback_table[EMAIL_ACTION_NUM];           /*  array of singly-linked list for event callbacks */
+
+void *thread_func_branch_command(void *arg);
+
+static email_event_t g_event_que[EVENT_QUEUE_MAX];
+
+int send_thread_run = 0;
+int recv_thread_run = 0;
+
+static pthread_mutex_t _send_event_available_lock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t *_send_event_queue_lock = NULL;  /*  MUST BE "recursive" */
+static pthread_cond_t  _send_event_available_signal = PTHREAD_COND_INITIALIZER;
+static thread_t g_send_srv_thread;
+static thread_t g_srv_thread;
+
+static email_event_t g_send_event_que[EVENT_QUEUE_MAX];
+static int g_send_event_que_idx = 1;
+static int g_send_event_loop = 1;
+static int g_send_active_que = 0;
+static int g_event_que_idx = 1;
+static int g_event_loop = 1;
+static int g_active_que = 0;
+static int g_sending_busy_cnt = 0;
+static int g_receiving_busy_cnt = 0;
+
+
+INTERNAL_FUNC int emcore_get_current_thread_type()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       thread_t thread_id = THREAD_SELF();
+       int thread_type = -1;
+
+       if (thread_id == g_srv_thread)
+               thread_type = _SERVICE_THREAD_TYPE_RECEIVING;
+       else if (thread_id == g_send_srv_thread)
+               thread_type = _SERVICE_THREAD_TYPE_SENDING;
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+       else if (thread_id == g_partial_body_thd)
+               thread_type = _SERVICE_THREAD_TYPE_PBD;
+#endif
+       EM_DEBUG_FUNC_END("thread_type [%d]", thread_type);
+       return thread_type;
+}
+
+static int is_gdk_lock_needed()
+{
+       if (g_event_loop)  {
+               return (THREAD_SELF() == g_srv_thread);
+       }
+       return false;
+}
+
+INTERNAL_FUNC int emcore_get_pending_event(email_action_t action, int account_id, int mail_id, email_event_status_type_t *status)
+{
+       EM_DEBUG_FUNC_BEGIN("action[%d], account_id[%d], mail_id[%d]", action, account_id, mail_id);
+
+       int found = false;
+       int i;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       for (i = 1; i < EVENT_QUEUE_MAX; i++)  {
+               switch (g_event_que[i].type)  {
+                       case EMAIL_EVENT_SEND_MAIL:
+                       case EMAIL_EVENT_SEND_MAIL_SAVED:
+                               if (action == EMAIL_ACTION_SEND_MAIL && account_id == g_event_que[i].account_id && mail_id == g_event_que[i].event_param_data_4) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_SYNC_HEADER:
+                               if (action == EMAIL_ACTION_SYNC_HEADER && account_id == g_event_que[i].account_id) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_SYNC_HEADER_OMA:
+                               if (action == EMAIL_ACTION_SYNC_HEADER_OMA && account_id == g_event_que[i].account_id) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_DOWNLOAD_BODY:
+                               if (action == EMAIL_ACTION_DOWNLOAD_BODY && account_id == g_event_que[i].account_id && mail_id == g_event_que[i].event_param_data_4) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+                       case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                               if (action == EMAIL_ACTION_SYNC_MAIL_FLAG_TO_SERVER && account_id == g_event_que[i].account_id && mail_id == g_event_que[i].event_param_data_4) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+                       case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
+                               if (action == EMAIL_ACTION_SYNC_FLAGS_FIELD_TO_SERVER && account_id == g_event_que[i].account_id && mail_id == g_event_que[i].event_param_data_4) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+                       case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                               if (action == EMAIL_ACTION_DOWNLOAD_ATTACHMENT && account_id == g_event_que[i].account_id && mail_id == g_event_que[i].event_param_data_4) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+                       case EMAIL_EVENT_DELETE_MAIL:
+                       case EMAIL_EVENT_DELETE_MAIL_ALL:
+                               if (action == EMAIL_ACTION_DELETE_MAIL && account_id == g_event_que[i].account_id) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_CREATE_MAILBOX:
+                               if (action == EMAIL_ACTION_CREATE_MAILBOX && account_id == g_event_que[i].account_id) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_DELETE_MAILBOX:
+                               if (action == EMAIL_ACTION_DELETE_MAILBOX && account_id == g_event_que[i].account_id) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_MOVE_MAIL:
+                               if (action == EMAIL_ACTION_MOVE_MAIL && account_id == g_event_que[i].account_id && mail_id == g_event_que[i].event_param_data_4) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                               if (action == EMAIL_ACTION_VALIDATE_ACCOUNT && account_id == g_event_que[i].account_id) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT:
+                               if (action == EMAIL_ACTION_VALIDATE_AND_UPDATE_ACCOUNT && account_id == 0) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT:
+                               if (action == EMAIL_ACTION_VALIDATE_AND_CREATE_ACCOUNT && account_id == 0) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_UPDATE_MAIL:
+                               if (action == EMAIL_ACTION_UPDATE_MAIL)  {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                               if (action == EMAIL_ACTION_SET_MAIL_SLOT_SIZE)  {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
+                               if (action == EMAIL_ACTION_EXPUNGE_MAILS_DELETED_FLAGGED)  {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_SEARCH_ON_SERVER:
+                               if (action == EMAIL_ACTION_SEARCH_ON_SERVER && account_id == g_event_que[i].account_id) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                               if (action == EMAIL_ACTION_MOVE_MAILBOX && account_id == g_event_que[i].account_id) {
+                                       found = true;
+                                       goto EXIT;
+                               }
+                               break;
+
+                       default:
+                               break;
+               }
+       }
+
+EXIT:
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       if (found) {
+               if (status)
+                       *status = g_event_que[i].status;
+
+               return i;
+       }
+
+       return FAILURE;
+}
+
+INTERNAL_FUNC void emcore_get_event_queue_status(int *on_sending, int *on_receiving)
+{
+       if (on_sending != NULL)
+               *on_sending = g_sending_busy_cnt;
+
+       if (on_receiving != NULL)
+               *on_receiving = g_receiving_busy_cnt;
+}
+
+static void _sending_busy_ref(void)
+{
+       g_sending_busy_cnt++;
+}
+
+static void _sending_busy_unref(void)
+{
+       g_sending_busy_cnt--;
+}
+
+static void _receiving_busy_ref(void)
+{
+       g_receiving_busy_cnt++;
+}
+
+static void _receiving_busy_unref(void)
+{
+       g_receiving_busy_cnt--;
+}
+
+static void waiting_status_notify(email_event_t *event_data, int queue_idx)
+{
+       EM_DEBUG_FUNC_BEGIN("event_data[%p], queue_idx[%d]", event_data, queue_idx);
+
+       int account_id = event_data->account_id;
+       int mail_id = event_data->event_param_data_4;           /*  NOT ALWAYS */
+
+       switch (event_data->type)  {
+               case EMAIL_EVENT_SEND_MAIL:
+                       emcore_execute_event_callback(EMAIL_ACTION_SEND_MAIL, 0, 0, EMAIL_SEND_WAITING, account_id, mail_id, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_SYNC_HEADER:
+                       emcore_execute_event_callback(EMAIL_ACTION_SYNC_HEADER, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_SYNC_HEADER_OMA:
+                       emcore_execute_event_callback(EMAIL_ACTION_SYNC_HEADER_OMA, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_DOWNLOAD_BODY:
+                       emcore_execute_event_callback(EMAIL_ACTION_DOWNLOAD_BODY, 0, 0, EMAIL_DOWNLOAD_WAITING, account_id, mail_id, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+               case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                       emcore_execute_event_callback(EMAIL_ACTION_SYNC_MAIL_FLAG_TO_SERVER, 0, 0, EMAIL_SYNC_WAITING, account_id, mail_id, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+#endif
+
+               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                       emcore_execute_event_callback(EMAIL_ACTION_DOWNLOAD_ATTACHMENT, 0, 0, EMAIL_DOWNLOAD_WAITING, account_id, mail_id, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_DELETE_MAIL:
+               case EMAIL_EVENT_DELETE_MAIL_ALL:
+                       emcore_execute_event_callback(EMAIL_ACTION_DELETE_MAIL, 0, 0, EMAIL_DELETE_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT:
+                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_AND_CREATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_MOVE_MAIL:
+                       emcore_execute_event_callback(EMAIL_ACTION_MOVE_MAIL, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_CREATE_MAILBOX:
+                       emcore_execute_event_callback(EMAIL_ACTION_CREATE_MAILBOX, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT:
+                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_AND_UPDATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_UPDATE_MAIL:
+                       break;
+
+               case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                       emcore_execute_event_callback(EMAIL_ACTION_SET_MAIL_SLOT_SIZE, 0, 0, EMAIL_SET_SLOT_SIZE_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
+                       emcore_execute_event_callback(EMAIL_ACTION_EXPUNGE_MAILS_DELETED_FLAGGED, 0, 0, EMAIL_EXPUNGE_MAILS_DELETED_FLAGGED_WAITING, account_id, event_data->event_param_data_4, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_SEARCH_ON_SERVER:
+                       emcore_execute_event_callback(EMAIL_ACTION_SEARCH_ON_SERVER, 0, 0, EMAIL_SYNC_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                       /* emcore_execute_event_callback(EMAIL_ACTION_CREATE_MAILBOX, 0, 0, EMAIL_LIST_WAITING, account_id, 0, queue_idx, EMAIL_ERROR_NONE); */
+                       break;
+
+               default:
+                       break;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+static void fail_status_notify(email_event_t *event_data, int error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int account_id, mail_id;
+
+       if(!event_data) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return;
+       }
+       account_id = event_data->account_id;
+       mail_id  = event_data->event_param_data_4;
+
+       EM_DEBUG_LOG("account_id[%d], mail_id[%d], error[%d]", account_id, mail_id, error);
+
+       switch (event_data->type)  {
+               case EMAIL_EVENT_SEND_MAIL:
+                       /* case EMAIL_EVENT_SEND_MAIL_SAVED:  */
+                       /* emcore_execute_event_callback(EMAIL_ACTION_SEND_MAIL, 0, 0, EMAIL_SEND_FAIL, account_id, mail_id, -1, error); */
+                       emcore_show_user_message(mail_id, EMAIL_ACTION_SEND_MAIL, error);
+                       break;
+
+               case EMAIL_EVENT_SYNC_HEADER:
+                       emcore_execute_event_callback(EMAIL_ACTION_SYNC_HEADER, 0, 0, EMAIL_LIST_FAIL, account_id, 0, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_SYNC_HEADER, error);
+                       break;
+
+               case EMAIL_EVENT_DOWNLOAD_BODY:
+                       emcore_execute_event_callback(EMAIL_ACTION_DOWNLOAD_BODY, 0, 0, EMAIL_DOWNLOAD_FAIL, account_id, mail_id, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_DOWNLOAD_BODY, error);
+                       break;
+
+               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                       emcore_execute_event_callback(EMAIL_ACTION_DOWNLOAD_ATTACHMENT, 0, 0, EMAIL_DOWNLOAD_FAIL, account_id, mail_id, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_DOWNLOAD_ATTACHMENT, error);
+                       break;
+
+               case EMAIL_EVENT_DELETE_MAIL:
+               case EMAIL_EVENT_DELETE_MAIL_ALL:
+                       emcore_execute_event_callback(EMAIL_ACTION_DELETE_MAIL, 0, 0, EMAIL_DELETE_FAIL, account_id, 0, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_DELETE_MAIL, error);
+                       break;
+
+               case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_FAIL, account_id, 0, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_VALIDATE_ACCOUNT, error);
+                       break;
+
+               case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT:
+                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_AND_CREATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_FAIL, account_id, 0, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_VALIDATE_AND_CREATE_ACCOUNT, error);
+                       break;
+
+               case EMAIL_EVENT_CREATE_MAILBOX:
+                       emcore_execute_event_callback(EMAIL_ACTION_CREATE_MAILBOX, 0, 0, EMAIL_LIST_FAIL, account_id, 0, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_CREATE_MAILBOX, error);
+                       break;
+
+               case EMAIL_EVENT_DELETE_MAILBOX:
+                       emcore_execute_event_callback(EMAIL_ACTION_DELETE_MAILBOX, 0, 0, EMAIL_LIST_FAIL, account_id, 0, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_DELETE_MAILBOX, error);
+                       break;
+
+               case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT:
+                       emcore_execute_event_callback(EMAIL_ACTION_VALIDATE_AND_UPDATE_ACCOUNT, 0, 0, EMAIL_VALIDATE_ACCOUNT_FAIL, account_id, 0, -1, error);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_VALIDATE_AND_UPDATE_ACCOUNT, error);
+                       break;
+
+               case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                       emcore_execute_event_callback(EMAIL_ACTION_SET_MAIL_SLOT_SIZE, 0, 0, EMAIL_SET_SLOT_SIZE_FAIL, account_id, 0, -1, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_SEARCH_ON_SERVER:
+                       emcore_execute_event_callback(EMAIL_ACTION_SEARCH_ON_SERVER, 0, 0, EMAIL_SEARCH_ON_SERVER_FAIL, account_id, 0, -1, EMAIL_ERROR_NONE);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_SEARCH_ON_SERVER, error);
+                       break;
+
+               case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                       emcore_execute_event_callback(EMAIL_ACTION_MOVE_MAILBOX, 0, 0, EMAIL_MOVE_MAILBOX_ON_IMAP_SERVER_FAIL, account_id, 0, -1, EMAIL_ERROR_NONE);
+                       emcore_show_user_message(account_id, EMAIL_ACTION_SEARCH_ON_SERVER, error);
+                       break;
+
+               case EMAIL_EVENT_UPDATE_MAIL:
+                       emcore_execute_event_callback(EMAIL_ACTION_UPDATE_MAIL, 0, 0, EMAIL_UPDATE_MAIL_FAIL, account_id, 0, -1, EMAIL_ERROR_NONE);
+                       break;
+
+               case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
+                       emcore_execute_event_callback(EMAIL_ACTION_EXPUNGE_MAILS_DELETED_FLAGGED, 0, 0, EMAIL_EXPUNGE_MAILS_DELETED_FLAGGED_FAIL, account_id, event_data->event_param_data_4, -1, EMAIL_ERROR_NONE);
+                       break;
+
+               default:
+                       break;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+
+static void emcore_initialize_event_callback_table()
+{
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+
+       int i;
+
+       for (i = 0; i < EMAIL_ACTION_NUM; i++)
+               _event_callback_table[i] = NULL;
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+}
+
+int emcore_register_event_callback(email_action_t action, email_event_callback callback, void *event_data)
+{
+       EM_DEBUG_FUNC_BEGIN("action[%d], callback[%p], event_data[%p]", action, callback, event_data);
+
+       if (callback == NULL)
+               return false;
+
+       int ret = false;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+
+       EVENT_CALLBACK_LIST *node = _event_callback_table[action];
+
+       while (node != NULL) {
+               if (node->callback == callback && node->event_data == event_data)               /*  already registered */
+                       goto EXIT;
+
+               node = node->next;
+       }
+
+       /*  not found, so keep going */
+
+       node = em_malloc(sizeof(EVENT_CALLBACK_LIST));
+
+       if (node == NULL)               /*  not enough memory */
+               goto EXIT;
+
+       node->callback = callback;
+       node->event_data = event_data;
+       node->next = _event_callback_table[action];
+
+       _event_callback_table[action] = node;
+
+       ret = true;
+
+EXIT :
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emcore_unregister_event_callback(email_action_t action, email_event_callback callback)
+{
+       EM_DEBUG_FUNC_BEGIN("action[%d], callback[%p]", action, callback);
+
+       if (callback == NULL)
+               return false;
+
+       int ret = false;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+
+       EVENT_CALLBACK_LIST *prev = NULL;
+       EVENT_CALLBACK_LIST *node = _event_callback_table[action];
+
+       while (node != NULL) {
+               if (node->callback == callback) {
+                       if (prev != NULL)
+                               prev->next = node->next;
+                       else
+                               _event_callback_table[action] = node->next;
+
+                       free(node);
+
+                       ret = true;
+                       break;
+               }
+
+               prev = node;
+               node = node->next;
+       }
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+void emcore_execute_event_callback(email_action_t action, int total, int done, int status, int account_id, int mail_id, int handle, int error)
+{
+       EM_DEBUG_FUNC_BEGIN("action[%d], total[%d], done[%d], status[%d], account_id[%d], mail_id[%d], handle[%d], error[%d]", action, total, done, status, account_id, mail_id, handle, error);
+
+       int lock_needed = 0;
+       lock_needed = is_gdk_lock_needed();
+
+       if (lock_needed)  {
+               /*  Todo  :  g_thread_yield */
+       }
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+
+       EVENT_CALLBACK_LIST *node = _event_callback_table[action];
+
+       while (node != NULL)  {
+               if (node->callback != NULL)
+                       node->callback(total, done, status, account_id, mail_id, (handle == -1 ? emcore_get_active_queue_idx()  :  handle), node->event_data, error);
+               node = node->next;
+       }
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+
+       if (lock_needed)  {
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+/* insert a event to event queue */
+INTERNAL_FUNC int emcore_insert_event(email_event_t *event_data, int *handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("event_data[%p], handle[%p], err_code[%p]", event_data, handle, err_code);
+
+       if (!event_data)  {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       if (!g_srv_thread)  {
+               EM_DEBUG_EXCEPTION("email-service is not ready");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_LOAD_ENGINE_FAILURE;
+               return false;
+       }
+
+       int ret = true;
+       int error = EMAIL_ERROR_NONE;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       if (!g_event_que[g_event_que_idx].type)  {      /*  if current buffer has not event, insert event data to current buffer  */
+               EM_DEBUG_LOG("Current buffer has not a event. [%d]", g_event_que_idx);
+               memcpy(g_event_que+g_event_que_idx, event_data, sizeof(email_event_t));
+               g_event_que[g_event_que_idx].status = EMAIL_EVENT_STATUS_WAIT;
+               waiting_status_notify(event_data, g_event_que_idx);
+               if (handle)
+                       *handle = g_event_que_idx;
+       }
+       else  { /*  if current buffer has event, find the empty buffer */
+               EM_DEBUG_LOG("Current buffer has a event. [%d]", g_event_que_idx);
+               int i, j = g_event_que_idx + 1;
+
+               for (i = 1; i < EVENT_QUEUE_MAX; i++, j++)  {
+                       if (j >= EVENT_QUEUE_MAX)
+                               j = 1;
+
+                       if (!g_event_que[j].type)
+                                       break;
+               }
+
+               if (i < EVENT_QUEUE_MAX)  {
+                       EM_DEBUG_LOG("I found available buffer. [%d]", g_event_que + j);
+                       memcpy(g_event_que+j, event_data, sizeof(email_event_t));
+                       g_event_que[j].status = EMAIL_EVENT_STATUS_WAIT;
+                       waiting_status_notify(event_data, j);
+
+                       if (handle)
+                               *handle = j;
+               }
+               else  {
+                       EM_DEBUG_EXCEPTION("event que is full...");
+                       error = EMAIL_ERROR_EVENT_QUEUE_FULL;
+                       ret = false;
+               }
+       }
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       if (ret == true)  {
+               event_data->event_param_data_1 = NULL;          /*  MUST BE - to prevent double-free */
+
+               switch (event_data->type)  {
+                       case EMAIL_EVENT_SEND_MAIL:
+                       case EMAIL_EVENT_SEND_MAIL_SAVED:
+                               _sending_busy_ref();
+                               break;
+
+                       case EMAIL_EVENT_SYNC_HEADER:
+                       case EMAIL_EVENT_DOWNLOAD_BODY:
+                       case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                       case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                       case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
+                       case EMAIL_EVENT_ISSUE_IDLE:
+                       case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
+                       case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                       case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT:
+                       case EMAIL_EVENT_SAVE_MAIL:
+                       case EMAIL_EVENT_MOVE_MAIL:
+                       case EMAIL_EVENT_DELETE_MAIL:
+                       case EMAIL_EVENT_DELETE_MAIL_ALL:
+                       case EMAIL_EVENT_SYNC_HEADER_OMA:
+                       case EMAIL_EVENT_CREATE_MAILBOX:
+                       case EMAIL_EVENT_DELETE_MAILBOX:
+                       case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT:
+                       case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                       case EMAIL_EVENT_UPDATE_MAIL:
+                       case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
+                       case EMAIL_EVENT_SEARCH_ON_SERVER:
+                       case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                               _receiving_busy_ref();
+                               break;
+                       default:
+                               break;
+               }
+
+               ENTER_CRITICAL_SECTION(_event_available_lock);
+               WAKE_CONDITION_VARIABLE(_event_available_signal);
+               LEAVE_CRITICAL_SECTION(_event_available_lock);
+       }
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+       {
+               int is_local_activity_event_inserted = false;
+
+               if (false == emcore_partial_body_thd_local_activity_sync(&is_local_activity_event_inserted, &error))
+                       EM_DEBUG_EXCEPTION("emcore_partial_body_thd_local_activity_sync failed [%d]", error);
+               else {
+                       if (true == is_local_activity_event_inserted)
+                               emcore_pb_thd_set_local_activity_continue(false);
+               }
+       }
+#endif
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_LOG("Finish with [%d]", ret);
+       return ret;
+}
+
+/* get a event from event_data queue */
+static int emcore_retrieve_event(email_event_t *event_data, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("event_data[%p], err_code[%p]", event_data, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       /*  get a event_data if this queue is not empty */
+       if (g_event_que[g_event_que_idx].type)  {
+               memcpy(event_data, g_event_que+g_event_que_idx, sizeof(email_event_t));
+
+               if (event_data->status != EMAIL_EVENT_STATUS_WAIT)  {   /*  EMAIL_EVENT_STATUS_CANCELED */
+                       memset(g_event_que+g_event_que_idx, 0x00, sizeof(email_event_t));
+                       g_active_que = 0;
+               }
+               else  {
+                       EM_DEBUG_LINE;
+                       g_event_que[g_event_que_idx].status = EMAIL_EVENT_STATUS_STARTED;
+                       g_active_que = g_event_que_idx;
+                       ret = true;
+               }
+
+               if (++g_event_que_idx >= EVENT_QUEUE_MAX)
+                       g_event_que_idx = 1;
+
+               EM_DEBUG_LOG("g_event_que[%d].type [%d]", g_active_que, g_event_que[g_active_que].type);
+       }
+       else  {
+               g_active_que = 0;
+               error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+       }
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/* check that event_data loop is continuous */
+static int emcore_event_loop_continue()
+{
+    return g_event_loop;
+}
+
+
+
+INTERNAL_FUNC int emcore_insert_event_for_sending_mails(email_event_t *event_data, int *handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("event_data[%p], handle[%p], err_code[%p]", event_data, handle, err_code);
+
+       if (!event_data)  {
+               EM_DEBUG_EXCEPTION("\t event_data[%p], handle[%p]", event_data, handle);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = true;
+       int error = EMAIL_ERROR_NONE;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+
+       if (!g_send_event_que[g_send_event_que_idx].type)  {
+               /* if current buffer has not event_data, insert event_data data to current buffer */
+               EM_DEBUG_LOG("Current buffer has not a event_data. [%d]", g_send_event_que_idx);
+               memcpy(g_send_event_que+g_send_event_que_idx, event_data, sizeof(email_event_t));
+
+               g_send_event_que[g_send_event_que_idx].status = EMAIL_EVENT_STATUS_WAIT;
+
+               if (handle)
+                       *handle = g_send_event_que_idx;
+       }
+       else  {
+               /* if current buffer has event_data, find the empty buffer */
+               EM_DEBUG_LOG("Current buffer has a event_data. [%d]", g_send_event_que_idx);
+               int i, j = g_send_event_que_idx + 1;
+
+               for (i = 1; i < EVENT_QUEUE_MAX; i++, j++)  {
+                       if (j >= EVENT_QUEUE_MAX)
+                               j = 1;
+
+                       if (!g_send_event_que[j].type)
+                                       break;
+                       }
+
+               if (i < EVENT_QUEUE_MAX)  {
+                       EM_DEBUG_LOG("I found available buffer. [%d]", j);
+                       memcpy(g_send_event_que+j, event_data, sizeof(email_event_t));
+                       g_send_event_que[j].status = EMAIL_EVENT_STATUS_WAIT;
+                       if (handle) *handle = j;
+               }
+               else  {
+                       EM_DEBUG_EXCEPTION("event_data queue is full...");
+                       error = EMAIL_ERROR_EVENT_QUEUE_FULL;
+                       ret = false;
+               }
+       }
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+
+       if (ret == true)  {
+               ENTER_CRITICAL_SECTION(_send_event_available_lock);
+               WAKE_CONDITION_VARIABLE(_send_event_available_signal);
+               LEAVE_CRITICAL_SECTION(_send_event_available_lock);
+       }
+
+       if (handle)
+       EM_DEBUG_LOG("emcore_insert_event_for_sending_mails-handle[%d]", *handle);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       /* EM_DEBUG_FUNC_BEGIN(); */
+       return ret;
+}
+
+
+static int emcore_retrieve_send_event(email_event_t *event_data, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+/* get a event_data if this queue is not empty */
+       if (g_send_event_que[g_send_event_que_idx].type)  {
+               memcpy(event_data, g_send_event_que+g_send_event_que_idx, sizeof(email_event_t));
+
+               if (event_data->status != EMAIL_EVENT_STATUS_WAIT) {
+                       memset(g_send_event_que+g_send_event_que_idx, 0x00, sizeof(email_event_t));
+                       g_send_active_que = 0;
+               }
+               else  {
+                       g_send_event_que[g_send_event_que_idx].status = EMAIL_EVENT_STATUS_STARTED;
+                       EM_DEBUG_LOG("g_send_event_que_idx[%d]", g_send_event_que_idx);
+                       g_send_active_que = g_send_event_que_idx;
+
+                       ret = true;
+               }
+
+               if (++g_send_event_que_idx >= EVENT_QUEUE_MAX)
+                       g_send_event_que_idx = 1;
+
+                       EM_DEBUG_LOG("\t g_send_event_que[%d].type = %d", g_send_active_que, g_send_event_que[g_send_active_que].type);
+       }
+       else  {
+                       EM_DEBUG_LOG("\t send event_data queue is empty...");
+                       g_send_active_que = 0;
+                       error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+       }
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       return ret;
+}
+
+
+void* thread_func_branch_command_for_sending_mails(void *arg)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       email_event_t event_data;
+       email_session_t *session = NULL;
+
+       if (!emstorage_open(&err))  {
+               EM_DEBUG_EXCEPTION("\t emstorage_open falied - %d", err);
+               return NULL;
+       }
+
+       while (g_send_event_loop) {
+               if (!emcore_get_empty_session(&session))
+                       EM_DEBUG_EXCEPTION("\t SEND THREAD emcore_get_empty_session failed...");
+
+               if (!emcore_retrieve_send_event(&event_data, NULL))  {
+                       EM_DEBUG_LOG(">>>> waiting for send event_data>>>>>>>>>");
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+                       if (send_thread_run && g_save_local_activity_run) {
+                               emstorage_account_tbl_t *account_list = NULL;
+                               int count = 0, i;
+                               if (!emstorage_get_account_list(&count, &account_list, true, true, &err)) {
+                                       EM_DEBUG_LOG("\t emstorage_get_account_list failed - %d", err);
+                               }
+                               else {
+                                       for (i = 0; i < count; i++) {
+                                               if (emcore_save_local_activity_sync(account_list[i].account_id, &err)) {
+                                                       EM_DEBUG_LOG("Found local activity...!");
+                                                       EM_DEBUG_LOG("Resetting g_save_local_activity_run ");
+                                                       g_save_local_activity_run = 0;
+                                                       emcore_clear_session(session);
+                                               }
+                                       }
+
+                                       emstorage_free_account(&account_list, count, &err);
+
+                                       if (!g_save_local_activity_run) {
+                                               continue;
+                                       }
+                               }
+                       }
+#endif
+                       send_thread_run = 0;
+
+                       ENTER_CRITICAL_SECTION(_send_event_available_lock);
+                       SLEEP_CONDITION_VARIABLE(_send_event_available_signal, _send_event_available_lock);
+                       LEAVE_CRITICAL_SECTION(_send_event_available_lock);
+               }
+               else {
+                       EM_DEBUG_LOG(">>>>>>>>>>>>>>Got SEND event_data>>>>>>>>>>>>>>>>");
+                       send_thread_run = 1;
+                       g_client_run = 1;
+
+                       if (!emnetwork_check_network_status( &err))  {
+                               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+
+                               emcore_show_user_message(event_data.event_param_data_4, EMAIL_ACTION_SEND_MAIL, err);
+                               if (!emcore_notify_network_event(NOTI_SEND_FAIL, event_data.account_id, NULL , event_data.event_param_data_4, err))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_FAIL] Failed >>>> ");
+                               goto FINISH_OFF;
+                       }
+
+                       switch (event_data.type)  {
+
+                               case EMAIL_EVENT_SEND_MAIL:
+                                       emdevice_set_dimming_on_off(false, NULL);
+
+                                       if (!emcore_send_mail(event_data.account_id, event_data.event_param_data_5, event_data.event_param_data_4, &err))
+                                               EM_DEBUG_EXCEPTION("emcore_send_mail failed [%d]", err);
+
+                                       emdevice_set_dimming_on_off(true, NULL);
+                                       break;
+
+                               case EMAIL_EVENT_SEND_MAIL_SAVED:  /* send mails to been saved in off-line mode */
+                                       emdevice_set_dimming_on_off(false, NULL);
+
+                                       if (!emcore_send_saved_mail(event_data.account_id, event_data.event_param_data_3, &err))
+                                               EM_DEBUG_EXCEPTION("emcore_send_saved_mail failed - %d", err);
+
+                                       emdevice_set_dimming_on_off(true, NULL);
+                                       break;
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+
+                               case EMAIL_EVENT_LOCAL_ACTIVITY: {
+                                       emdevice_set_dimming_on_off(false, NULL);
+                                       emstorage_activity_tbl_t *local_activity = NULL;
+                                       int activity_id_count = 0;
+                                       int activity_chunk_count = 0;
+                                       int *activity_id_list = NULL;
+                                       int i = 0;
+
+                                       if (false == emstorage_get_activity_id_list(event_data.account_id, &activity_id_list, &activity_id_count, ACTIVITY_SAVEMAIL, ACTIVITY_DELETEMAIL_SEND, true, &err)) {
+                                               EM_DEBUG_EXCEPTION("emstorage_get_activity_id_list failed [%d]", err);
+                                       }
+                                       else {
+                                               for (i = 0; i < activity_id_count; ++i) {
+                                                       if ((false == emstorage_get_activity(event_data.account_id, activity_id_list[i], &local_activity, &activity_chunk_count, true,  &err)) || (NULL == local_activity) || (0 == activity_chunk_count)) {
+                                                               EM_DEBUG_EXCEPTION(" emstorage_get_activity Failed [ %d] or local_activity is NULL [%p] or activity_chunk_count is 0[%d]", err, local_activity, activity_chunk_count);
+                                                       }
+                                                       else {
+                                                               EM_DEBUG_LOG("Found local activity type - %d", local_activity[0].activity_type);
+                                                               switch (local_activity[0].activity_type) {
+                                                                       case ACTIVITY_SAVEMAIL:  {
+                                                                               if (!emcore_sync_mail_from_client_to_server(event_data.account_id, local_activity[0].mail_id, &err)) {
+                                                                                       EM_DEBUG_EXCEPTION("emcore_sync_mail_from_client_to_server failed - %d ", err);
+                                                                               }
+                                                                       }
+                                                                       break;
+
+                                                                       case ACTIVITY_DELETEMAIL_SEND:                          /* New Activity Type Added for Race Condition and Crash Fix */ {
+                                                                               if (!emcore_delete_mail(local_activity[0].account_id,
+                                                                                                                               &local_activity[0].mail_id,
+                                                                                                                               EMAIL_DELETE_FOR_SEND_THREAD,
+                                                                                                                               true,
+                                                                                                                               EMAIL_DELETED_BY_COMMAND,
+                                                                                                                               false,
+                                                                                                                               &err))  {
+                                                                                       EM_DEBUG_LOG("\t emcore_delete_mail failed - %d", err);
+                                                                               }
+                                                                       }
+                                                                       break;
+
+                                                                       default:  {
+                                                                               EM_DEBUG_LOG(">>>> No such Local Activity Handled by this thread [ %d ] >>> ", local_activity[0].activity_type);
+                                                                       }
+                                                                       break;
+                                                               }
+
+                                                               emstorage_free_local_activity(&local_activity, activity_chunk_count, NULL);
+
+                                                               if (g_save_local_activity_run == 1) {
+                                                                       EM_DEBUG_LOG(" Network event_data found.. Local sync Stopped..! ");
+                                                                       break;
+                                                               }
+                                                       }
+
+                                               }
+                                               if (false == emstorage_free_activity_id_list(activity_id_list, &err)) {
+                                                       EM_DEBUG_LOG("emstorage_free_activity_id_list failed");
+                                               }
+                                       }
+
+                                       emdevice_set_dimming_on_off(true, NULL);
+                               }
+                               break;
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+                               default:
+                                       EM_DEBUG_LOG("Others not supported by Send Thread..! [%d]", event_data.type);
+                                       break;
+                       }
+
+                       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+                       memset(g_send_event_que+g_send_active_que, 0x00, sizeof(email_event_t));
+                       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+
+FINISH_OFF:
+                       ;
+               }
+               emcore_clear_session(session);
+       }
+
+       if (!emstorage_close(&err))
+               EM_DEBUG_EXCEPTION("emstorage_close falied [%d]", err);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return NULL;
+}
+
+
+int event_handler_EMAIL_EVENT_SYNC_HEADER(int input_account_id, int input_mailbox_id, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_mailbox_id [%d], handle_to_be_published [%d], error[%p]", input_account_id, input_mailbox_id, handle_to_be_published, error);
+
+       int err = EMAIL_ERROR_NONE, sync_type = 0, ret = false;
+       int mailbox_count = 0, account_count = 0;
+       int counter, account_index;
+       int unread = 0, total_unread = 0;
+       emcore_uid_list *uid_list = NULL;
+       emstorage_account_tbl_t *account_tbl_array = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl_target = NULL, *mailbox_tbl_spam = NULL, *mailbox_tbl_list = NULL;
+#ifndef __FEATURE_KEEP_CONNECTION__
+       MAILSTREAM *stream = NULL;
+#endif
+       char mailbox_id_param_string[10] = {0,};
+       char *input_mailbox_id_str = NULL;
+
+       if (input_mailbox_id == 0)
+               sync_type = EMAIL_SYNC_ALL_MAILBOX;
+       else {
+               if (!emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl_target) || !mailbox_tbl_target) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       if(mailbox_tbl_target)
+               SNPRINTF(mailbox_id_param_string, 10, "%d", mailbox_tbl_target->mailbox_id);
+
+       input_mailbox_id_str = (input_mailbox_id == 0)? NULL: mailbox_id_param_string;
+
+       if (!emcore_notify_network_event(NOTI_DOWNLOAD_START, input_account_id, input_mailbox_id_str, handle_to_be_published, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_DOWNLOAD_START] Failed >>>> ");
+
+       if (!emnetwork_check_network_status(&err)) {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+
+               if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, input_account_id, input_mailbox_id_str, handle_to_be_published, err))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
+       }
+       else {
+               if (sync_type != EMAIL_SYNC_ALL_MAILBOX) {      /* Sync only particular mailbox */
+
+                       if ((err = emcore_update_sync_status_of_account(input_account_id, SET_TYPE_SET, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
+                               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+
+                       if (!emstorage_get_mailbox_by_mailbox_type(input_account_id, EMAIL_MAILBOX_TYPE_SPAMBOX, &mailbox_tbl_spam, false, &err)) {
+                               EM_DEBUG_LOG("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+                       }
+
+                       if (!emcore_sync_header(mailbox_tbl_target, mailbox_tbl_spam, NULL, &uid_list, &unread, &err)) {
+                               EM_DEBUG_EXCEPTION("emcore_sync_header failed [%d]", err);
+                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, mailbox_tbl_target->account_id, mailbox_id_param_string, handle_to_be_published, err))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed >>>> ");
+                       }
+                       else {
+                               EM_DEBUG_LOG("emcore_sync_header succeeded [%d]", err);
+                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_FINISH, mailbox_tbl_target->account_id, mailbox_id_param_string, handle_to_be_published, 0))
+                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_FINISH] Failed >>>> ");
+                       }
+
+                       total_unread += unread;
+
+                       if (total_unread > 0 && (err = emcore_update_sync_status_of_account(input_account_id, SET_TYPE_UNION, SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
+                               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+
+                       if (!emcore_finalize_sync(input_account_id, &err))
+                               EM_DEBUG_EXCEPTION("emcore_finalize_sync failed [%d]", err);
+               }
+               else /*  All Foder */ {
+                       EM_DEBUG_LOG(">>>> SYNC ALL MAILBOX ");
+                       /*  Sync of all mailbox */
+
+                       if (input_account_id == ALL_ACCOUNT) {
+                               if ((err = emcore_update_sync_status_of_account(ALL_ACCOUNT, SET_TYPE_SET, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
+                                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+
+                               if (!emstorage_get_account_list(&account_count, &account_tbl_array , true, false, &err)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [ %d ] ", err);
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, input_account_id, NULL,  handle_to_be_published, err))
+                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
+                                       goto FINISH_OFF;
+                               }
+                       }
+                       else {
+                               EM_DEBUG_LOG("Sync all mailbox of an account[%d].", input_account_id);
+
+                               if ((err = emcore_update_sync_status_of_account(input_account_id, SET_TYPE_SET, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
+                                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+
+                               if (!emstorage_get_account_by_id(input_account_id, EMAIL_ACC_GET_OPT_DEFAULT, &account_tbl_array, true, &err)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [ %d ] ", err);
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, input_account_id, input_mailbox_id_str, handle_to_be_published, err))
+                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
+                                       goto FINISH_OFF;
+                               }
+                               account_count = 1;
+                       }
+
+                       for (account_index = 0 ; account_index < account_count; account_index++) {
+                               if (account_tbl_array[account_index].incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+                                       EM_DEBUG_LOG("account[%d] is for ActiveSync. Skip  ", account_index);
+                                       continue;
+                               }
+
+                               if (!emstorage_get_mailbox_list(account_tbl_array[account_index].account_id, 0, EMAIL_MAILBOX_SORT_BY_TYPE_ASC, &mailbox_count, &mailbox_tbl_list, true, &err) || mailbox_count <= 0) {
+                                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox failed [%d]", err);
+
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, account_tbl_array[account_index].account_id, input_mailbox_id_str, handle_to_be_published, err))
+                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
+
+                                       continue;
+                               }
+
+                               EM_DEBUG_LOG("emcore_get_mailbox_list_to_be_sync returns [%d] mailboxes", mailbox_count);
+
+                               if(mailbox_tbl_spam) {
+                                       if (!emstorage_free_mailbox(&mailbox_tbl_spam, 1, &err)) {
+                                               EM_DEBUG_EXCEPTION("emstorage_free_mailbox failed [%d]", err);
+                                       }
+                                       mailbox_tbl_spam = NULL;
+                               }
+
+                               if (!emstorage_get_mailbox_by_mailbox_type(account_tbl_array[account_index].account_id, EMAIL_MAILBOX_TYPE_SPAMBOX, &mailbox_tbl_spam, false, &err)) {
+                                       EM_DEBUG_LOG("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+                               }
+
+                               if (mailbox_count > 0) {
+#ifndef __FEATURE_KEEP_CONNECTION__
+                                       if (account_tbl_array[account_index].incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+                                               memset(mailbox_id_param_string, 0, 10);
+                                               SNPRINTF(mailbox_id_param_string, 10, "%d", mailbox_tbl_list[0].mailbox_id);
+                                               if (!emcore_connect_to_remote_mailbox(account_tbl_array[account_index].account_id, mailbox_tbl_list[0].mailbox_id, (void **)&stream, &err))  {
+                                                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+                                                       if (err == EMAIL_ERROR_LOGIN_FAILURE)
+                                                               EM_DEBUG_EXCEPTION("EMAIL_ERROR_LOGIN_FAILURE ");
+                                                       /* continue; */
+                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, account_tbl_array[account_index].account_id, mailbox_id_param_string,  handle_to_be_published, err))
+                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed >>>> ");
+                                                       continue;
+                                               }
+                                               EM_DEBUG_LOG("emcore_connect_to_remote_mailbox returns [%d] : ", err);
+                                       }
+                                       else
+                                               stream = NULL;
+#endif
+                               }
+
+                               for (counter = 0; counter < mailbox_count; counter++) {
+
+                                       EM_DEBUG_LOG("maiblox_name [%s], mailbox_id [%d], mailbox_type [%d]", mailbox_tbl_list[counter].mailbox_name, mailbox_tbl_list[counter].mailbox_id, mailbox_tbl_list[counter].mailbox_type);
+
+                                       if ( mailbox_tbl_list[counter].mailbox_type == EMAIL_MAILBOX_TYPE_ALL_EMAILS
+                                                       || mailbox_tbl_list[counter].mailbox_type == EMAIL_MAILBOX_TYPE_TRASH
+                                               /*|| mailbox_tbl_list[counter].mailbox_type == EMAIL_MAILBOX_TYPE_SPAMBOX */)
+                                               EM_DEBUG_LOG("Skipped for all emails or trash");
+                                       else if (!mailbox_tbl_list[counter].local_yn) {
+                                               EM_DEBUG_LOG("[%s] Syncing...", mailbox_tbl_list[counter].mailbox_name);
+#ifdef __FEATURE_KEEP_CONNECTION__
+                                               if (!emcore_sync_header((mailbox_tbl_list + counter) , mailbox_tbl_spam, NULL, &uid_list, &unread, &err)) {
+#else /*  __FEATURE_KEEP_CONNECTION__ */
+                                               if (!emcore_sync_header((mailbox_tbl_list + counter) , mailbox_tbl_spam, (void *)stream, &uid_list, &unread, &err)) {
+#endif /*  __FEATURE_KEEP_CONNECTION__ */
+                                                       EM_DEBUG_EXCEPTION("emcore_sync_header for %s(mailbox_id = %d) failed [%d]", mailbox_tbl_list[counter].mailbox_name, mailbox_tbl_list[counter].mailbox_id, err);
+
+#ifndef __FEATURE_KEEP_CONNECTION__
+                                                       if (err == EMAIL_ERROR_CONNECTION_BROKEN || err == EMAIL_ERROR_NO_SUCH_HOST || err == EMAIL_ERROR_SOCKET_FAILURE)
+                                                               stream = NULL;    /*  Don't retry to connect for broken connection. It might cause crash.  */
+#endif /*  __FEATURE_KEEP_CONNECTION__ */
+                                                       memset(mailbox_id_param_string, 0, 10);
+                                                       SNPRINTF(mailbox_id_param_string, 10, "%d", mailbox_tbl_list[counter].mailbox_id);
+                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, account_tbl_array[account_index].account_id, mailbox_id_param_string,  handle_to_be_published, err))
+                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FAIL] Failed >>>> ");
+
+                                                       break;
+                                               }
+                                       }
+                                       total_unread  += unread;
+                               }
+
+                               EM_DEBUG_LOG("Sync for account_id(%d) is completed....!", account_tbl_array[account_index].account_id);
+                               if ((err == EMAIL_ERROR_NONE) && !emcore_notify_network_event(NOTI_DOWNLOAD_FINISH, account_tbl_array[account_index].account_id, NULL, handle_to_be_published, 0))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_FINISH] Failed >>>> ");
+
+                               if ((total_unread > 0) && (err = emcore_update_sync_status_of_account(account_tbl_array[account_index].account_id, SET_TYPE_UNION, SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
+                                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+
+                               if (!emcore_finalize_sync(account_tbl_array[account_index].account_id, &err))
+                                       EM_DEBUG_EXCEPTION("emcore_finalize_sync failed [%d]", err);
+#ifndef __FEATURE_KEEP_CONNECTION__
+                               if (stream)  {
+                                       emcore_close_mailbox(0, stream);
+                                       stream = NULL;
+                               }
+#endif
+                               if (mailbox_tbl_list) {
+                                       emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
+                                       mailbox_tbl_list = NULL;
+                                       mailbox_count = 0;
+                               }
+                       }
+               }
+
+               ret = true;
+
+FINISH_OFF:
+
+#ifndef __FEATURE_KEEP_CONNECTION__
+               if (stream)
+                       emcore_close_mailbox(0, stream);
+#endif
+               if(mailbox_tbl_target)
+                       emstorage_free_mailbox(&mailbox_tbl_target, 1, NULL);
+
+               if (mailbox_tbl_list)
+                       emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
+
+               if (account_tbl_array)
+                       emstorage_free_account(&account_tbl_array, account_count, NULL);
+       }
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int event_handler_EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT(email_account_t *account, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("account [%p]", account);
+       int err, ret = false;
+
+       if(!account) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("incoming_server_address  :  %s", account->incoming_server_address);
+
+       if (!emnetwork_check_network_status(&err)) {
+               emcore_delete_account_from_unvalidated_account_list(account->account_id);
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL, account->account_id, NULL,  handle_to_be_published, err))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FAIL] Failed >>>> ");
+               goto FINISH_OFF;
+       }
+       else {
+               EM_DEBUG_LOG("incoming_server_address : %s", account->incoming_server_address);
+
+               if (!emcore_validate_account_with_account_info(account, &err)) {
+                       emcore_delete_account_from_unvalidated_account_list(account->account_id);
+                       EM_DEBUG_EXCEPTION("emcore_validate_account_with_account_info failed err :  %d", err);
+                       if (err == EMAIL_ERROR_CANCELLED) {
+                               EM_DEBUG_EXCEPTION(" notify  :  NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL ");
+                               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL, account->account_id, NULL,  handle_to_be_published, err))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL] Failed");
+                               goto FINISH_OFF;
+                       }
+                       else
+                               goto FINISH_OFF;
+               }
+               else {
+                       emcore_delete_account_from_unvalidated_account_list(account->account_id);
+
+                       if (emcore_create_account(account, &err) == false)       {
+                               EM_DEBUG_EXCEPTION(" emdaemon_create_account failed - %d", err);
+                               goto FINISH_OFF;
+                       }
+
+                       emcore_init_account_reference();
+
+                       EM_DEBUG_LOG("incoming_server_type [%d]", account->incoming_server_type);
+
+                       if ((EMAIL_SERVER_TYPE_IMAP4 == account->incoming_server_type)) {
+                               if (!emcore_sync_mailbox_list(account->account_id, "", handle_to_be_published, &err))  {
+                                       EM_DEBUG_EXCEPTION("emcore_get_mailbox_list_to_be_sync failed [%d]", err);
+                                       /*  delete account whose mailbox couldn't be obtained from server */
+                                       emcore_delete_account(account->account_id, NULL);
+                                       goto FINISH_OFF;
+                               }
+                       }
+
+                       EM_DEBUG_LOG("validating and creating an account are succeeded for account id  [%d]  err [%d]", account->account_id, err);
+                       if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_FINISH, account->account_id, NULL,  handle_to_be_published, err))
+                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FINISH] Success");
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == false && err != EMAIL_ERROR_CANCELLED && account) {
+               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL, account->account_id, NULL,  handle_to_be_published, err))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL] Failed");
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int event_handler_EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT(int account_id, email_account_t *new_account_info, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], new_account_info [%p]", account_id, new_account_info);
+       int err, ret = false;
+       emstorage_account_tbl_t *old_account_tbl = NULL, *new_account_tbl = NULL;
+
+       if (!new_account_info) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emnetwork_check_network_status(&err))  {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+
+               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FAIL, new_account_info->account_id, NULL,  handle_to_be_published, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FAIL] Failed >>>> ");
+               goto FINISH_OFF;
+       }
+       else  {
+               EM_DEBUG_LOG("incoming_server_address: (%s)", new_account_info->incoming_server_address);
+
+               if (!emcore_validate_account_with_account_info(new_account_info, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_validate_account_with_account_info() failed err :  %d", err);
+                       if (err == EMAIL_ERROR_CANCELLED) {
+                               EM_DEBUG_EXCEPTION(" notify  :  NOTI_VALIDATE_AND_CREATE_ACCOUNT_CANCEL ");
+                               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_UPDATE_ACCOUNT_CANCEL, new_account_info->account_id, NULL,  handle_to_be_published, err))
+                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_AND_UPDATE_ACCOUNT_CANCEL] Failed");
+                               goto FINISH_OFF;
+                       }
+                       else {
+                               goto FINISH_OFF;
+                       }
+               }
+               else {
+                       if (!emstorage_get_account_by_id(account_id, WITHOUT_OPTION, &old_account_tbl, true, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [%d]", err);
+                               /* goto FINISH_OFF; */
+                       }
+
+                       new_account_tbl = em_malloc(sizeof(emstorage_account_tbl_t));
+                       if (!new_account_tbl) {
+                               EM_DEBUG_EXCEPTION("allocation failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       em_convert_account_to_account_tbl(new_account_info, new_account_tbl);
+
+                       if (emstorage_update_account(account_id, new_account_tbl, true, &err)) {
+                               emcore_init_account_reference();
+                       }
+
+                       EM_DEBUG_LOG("validating and updating an account are succeeded for account id [%d], err [%d]", new_account_info->account_id, err);
+                       if (!emcore_notify_network_event(NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FINISH, new_account_info->account_id, NULL,  handle_to_be_published, err))
+                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FINISH] Success");
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (old_account_tbl)
+               emstorage_free_account(&old_account_tbl, 1, NULL);
+       if (new_account_tbl)
+               emstorage_free_account(&new_account_tbl, 1, NULL);
+
+       if (ret == false && err != EMAIL_ERROR_CANCELLED && new_account_info) {
+               if (!emcore_notify_network_event(NOTI_VALIDATE_AND_UPDATE_ACCOUNT_FAIL, new_account_info->account_id, NULL,  handle_to_be_published, err))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_AND_CREATE_ACCOUNT_FAIL] Failed");
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int event_handler_EMAIL_EVENT_SET_MAIL_SLOT_SIZE(int account_id, int mailbox_id, int new_slot_size, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       emcore_set_mail_slot_size(account_id, mailbox_id, new_slot_size, error);
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+static int event_handler_EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED(int input_account_id, int input_mailbox_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_mailbox_id [%d]", input_account_id, input_mailbox_id);
+       int err = EMAIL_ERROR_NONE;
+
+       if ( (err = emcore_expunge_mails_deleted_flagged_from_remote_server(input_account_id, input_mailbox_id)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_expunge_mails_deleted_flagged_from_remote_server failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( (err = emcore_expunge_mails_deleted_flagged_from_local_storage(input_mailbox_id)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_expunge_mails_deleted_flagged_from_local_storage failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+int event_handler_EMAIL_EVENT_LOCAL_ACTIVITY(int account_id, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       email_mailbox_t mailbox;
+       emstorage_activity_tbl_t *local_activity = NULL;
+       int activity_id_count = 0;
+       int activity_chunk_count = 0;
+       int *activity_id_list = NULL;
+       int i = 0;
+
+       if (!emnetwork_check_network_status(&err))
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+       else {
+               if (false == emstorage_get_activity_id_list(account_id, &activity_id_list, &activity_id_count, ACTIVITY_DELETEMAIL, ACTIVITY_COPYMAIL, true, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_activity_id_list failed [%d]", err);
+               }
+               else {
+                       for (i = 0; i < activity_id_count; ++i) {
+                               if ((false == emstorage_get_activity(account_id , activity_id_list[i], &local_activity, &activity_chunk_count, true,  &err)) || (NULL == local_activity) || (0 == activity_chunk_count))
+                                       EM_DEBUG_EXCEPTION(" emstorage_get_activity Failed [ %d] or local_activity is NULL [%p] or activity_chunk_count is 0[%d]", err, local_activity, activity_chunk_count);
+                               else {
+                                       EM_DEBUG_LOG("Found local activity type - %d", local_activity[0].activity_type);
+                                       switch (local_activity[0].activity_type) {
+                                               case ACTIVITY_MODIFYFLAG:  {
+                                                       if (emcore_sync_flag_with_server(local_activity[0].mail_id , &err))  {
+                                                               if (!emcore_delete_activity(&local_activity[0], &err))
+                                                                       EM_DEBUG_EXCEPTION(">>>>>>Local Activity [ACTIVITY_MODIFYFLAG] [%d] ", err);
+                                                       }
+                                               }
+                                               break;
+
+                                               case ACTIVITY_DELETEMAIL:
+                                               case ACTIVITY_MOVEMAIL:
+                                               case ACTIVITY_MODIFYSEENFLAG:
+                                               case ACTIVITY_COPYMAIL:  {
+
+                                                       int j = 0, k = 0;
+                                                       int total_mail_ids = activity_chunk_count;
+
+                                                       int *mail_id_list = NULL;
+
+                                                       mail_id_list = (int *)em_malloc(sizeof(int) * total_mail_ids);
+
+                                                       if (NULL == mail_id_list) {
+                                                               EM_DEBUG_EXCEPTION("malloc failed... ");
+                                                               break;
+                                                       }
+
+                                                       do {
+
+                                                               for (j = 0; j < BULK_OPERATION_COUNT && (k < total_mail_ids); ++j, ++k)
+                                                                       mail_id_list[j] = local_activity[k].mail_id;
+
+                                                               switch (local_activity[k-1].activity_type) {
+                                                                       case ACTIVITY_DELETEMAIL:  {
+                                                                               if (!emcore_delete_mail(local_activity[k-1].account_id,
+                                                                                                                               mail_id_list,
+                                                                                                                               j,
+                                                                                                                               EMAIL_DELETE_LOCAL_AND_SERVER,
+                                                                                                                               EMAIL_DELETED_BY_COMMAND,
+                                                                                                                               false,
+                                                                                                                               &err))
+                                                                                       EM_DEBUG_LOG("\t emcore_delete_mail failed - %d", err);
+                                                                       }
+                                                                       break;
+
+                                                                       case ACTIVITY_MOVEMAIL:  {
+                                                                               if (!emcore_move_mail_on_server_ex(local_activity[k-1].account_id ,
+                                                                                                                                                  local_activity[k-1].src_mbox,
+                                                                                                                                                  mail_id_list,
+                                                                                                                                                  j,
+                                                                                                                                                  local_activity[k-1].dest_mbox,
+                                                                                                                                                  &err))
+                                                                                       EM_DEBUG_LOG("\t emcore_move_mail_on_server_ex failed - %d", err);
+                                                                       }
+                                                                       break;
+                                                                       case ACTIVITY_MODIFYSEENFLAG:  {
+                                                                               int seen_flag = atoi(local_activity[0].src_mbox);
+                                                                               if (!emcore_sync_seen_flag_with_server_ex(mail_id_list, j , seen_flag , &err)) /* local_activity[0].src_mbox points to the seen flag */
+                                                                                       EM_DEBUG_EXCEPTION("\t emcore_sync_seen_flag_with_server_ex failed - %d", err);
+                                                                       }
+                                                                       break;
+                                                               }
+
+                                                       } while (k < total_mail_ids);
+
+                                                       EM_SAFE_FREE(mail_id_list);
+                                               }
+
+                                               break;
+
+                                               default:
+                                                       EM_DEBUG_LOG(">>>> No such Local Activity Handled by this thread [ %d ] >>> ", local_activity[0].activity_type);
+                                               break;
+                                       }
+
+                                       emstorage_free_local_activity(&local_activity, activity_chunk_count, NULL);
+
+                                       if (g_local_activity_run == 1) {
+                                               EM_DEBUG_LOG(" Network event_data found.. Local sync Stopped..! ");
+                                               break;
+                                       }
+                               }
+                       }
+               }
+       }
+       if (activity_id_list) {
+               if (false == emstorage_free_activity_id_list(activity_id_list, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_free_activity_id_list failed");
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+
+       return true;
+}
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+
+int event_handler_EMAIL_EVENT_DOWNLOAD_BODY(int account_id, int mail_id, int option, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       email_mailbox_t mailbox;
+
+       memset(&mailbox, 0x00, sizeof(mailbox));
+       mailbox.account_id = account_id;
+
+       if (!emnetwork_check_network_status(&err))  {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+
+               emcore_notify_network_event(NOTI_DOWNLOAD_BODY_FAIL, mail_id, NULL, handle_to_be_published, err);
+       }
+       else  {
+               if (!emcore_download_body_multi_sections_bulk(NULL,
+                       mailbox.account_id,
+                       mail_id,
+                       option >> 1,            /*  0 :  silent, 1 :  verbose */
+                       option & 0x01,          /*  0 :  without attachments, 1 :  with attachments */
+                       NO_LIMITATION,
+                       handle_to_be_published,
+                       &err))
+                       EM_DEBUG_EXCEPTION("emcore_download_body_multi_sections_bulk failed - %d", err);
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_DOWNLOAD_ATTACHMENT(int account_id, int mail_id, int attachment_no, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_LOG("attachment_no is %d", attachment_no);
+
+       if (!emnetwork_check_network_status(&err))  {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FAIL, mail_id, NULL, attachment_no, err);
+       }
+       else  {
+
+#ifdef __ATTACHMENT_OPTI__
+               if (!emcore_download_attachment_bulk(account_id, mail_id, attachment_no, &err))
+                       EM_DEBUG_EXCEPTION("\t emcore_download_attachment failed [%d]", err);
+#else
+               if (!emcore_download_attachment(account_id, mail_id, attachment_no, &err))
+                       EM_DEBUG_EXCEPTION("\t emcore_download_attachment failed [%d]", err);
+#endif
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER(int mail_ids[], int num, email_flags_field_type field_type, int value, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emnetwork_check_network_status(&err))
+               EM_DEBUG_EXCEPTION("dnet_init failed [%d]", err);
+       else if (!emcore_sync_flags_field_with_server(mail_ids, num, field_type, value, &err))
+               EM_DEBUG_EXCEPTION("emcore_sync_flags_field_with_server failed [%d]", err);
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_VALIDATE_ACCOUNT(int account_id, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emnetwork_check_network_status(&err))  {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+
+               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_FAIL, account_id, NULL,  handle_to_be_published, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FAIL] Failed >>>>");
+       }
+       else  {
+
+               if (!emcore_validate_account(account_id, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_validate_account failed account id  :  %d  err :  %d", account_id, err);
+
+                       if (err == EMAIL_ERROR_CANCELLED) {
+                               EM_DEBUG_EXCEPTION("notify  :  NOTI_VALIDATE_ACCOUNT_CANCEL ");
+                               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_CANCEL, account_id, NULL,  handle_to_be_published, err))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_CANCEL] Failed >>>> ");
+                       }
+                       else {
+                               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_FAIL, account_id, NULL,  handle_to_be_published, err))
+                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FAIL] Failed >>>> ");
+                       }
+               }
+               else {
+                       email_account_t *account_ref = NULL;
+                       account_ref = emcore_get_account_reference(account_id);
+
+                       if (account_ref) {
+                               EM_DEBUG_LOG("account_ref->incoming_server_type[%d]", account_ref->incoming_server_type);
+                               if ( EMAIL_SERVER_TYPE_IMAP4 == account_ref->incoming_server_type ) {
+                                       if (!emcore_check_thread_status())
+                                               err = EMAIL_ERROR_CANCELLED;
+                                       else if (!emcore_sync_mailbox_list(account_id, "", handle_to_be_published, &err))
+                                               EM_DEBUG_EXCEPTION("\t emcore_get_mailbox_list_to_be_sync falied - %d", err);
+                               }
+
+                               if (err > 0) {
+                                       EM_DEBUG_EXCEPTION("emcore_validate_account succeeded account id  :  %d  err :  %d", account_id, err);
+                                       if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_FINISH, account_id, NULL,  handle_to_be_published, err))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_FINISH] Success >>>>");
+                               }
+
+                               emcore_free_account(account_ref);
+                               EM_SAFE_FREE(account_ref);
+                       }
+               }
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_UPDATE_MAIL(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas, int handle_to_be_published)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count[%d], input_meeting_request[%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+       int err = EMAIL_ERROR_NONE;
+
+       if ( (err = emcore_update_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas)) != EMAIL_ERROR_NONE)
+               EM_DEBUG_EXCEPTION("emcore_update_mail failed [%d]", err);
+
+       if(input_mail_data)
+               emcore_free_mail_data_list(&input_mail_data, 1);
+
+       if(input_attachment_data_list)
+               emcore_free_attachment_data(&input_attachment_data_list, input_attachment_count, NULL);
+
+       if(input_meeting_request)
+               emstorage_free_meeting_request(input_meeting_request);
+
+       EM_DEBUG_FUNC_END("err [%d", err);
+       return err;
+}
+int event_handler_EMAIL_EVENT_SAVE_MAIL(int input_account_id, int input_mail_id, int input_handle_to_be_published)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_mail_id [%d] input_handle_to_be_published [%d]", input_account_id, input_mail_id, input_handle_to_be_published);
+       int err = EMAIL_ERROR_NONE;
+
+       err = emcore_sync_mail_from_client_to_server(input_mail_id);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+int event_handler_EMAIL_EVENT_MOVE_MAIL(int account_id, int *mail_ids, int mail_id_count, int dest_mailbox_id, int src_mailbox_id, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE, ret = false;
+       email_account_t *account_ref = NULL;
+
+       if (!(account_ref = emcore_get_account_reference(account_id))) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /* Move mail local */
+       /*
+       if (!emcore_mail_move(mail_ids, mail_id_count, dest_mailbox.mailbox_name, EMAIL_MOVED_BY_COMMAND, 0, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_mail_move failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       */
+
+       if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+               /* Move mail on server */
+               if (!emnetwork_check_network_status(&err))
+                       EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               else {
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+                       if (!emcore_move_mail_on_server_ex(account_id , src_mailbox_id, mail_ids, mail_id_count, dest_mailbox_id, &err))
+                               EM_DEBUG_EXCEPTION("emcore_move_mail_on_server_ex failed - %d", err);
+#else
+                       if (!emcore_move_mail_on_server(account_id , src_mailbox_id, mail_ids, mail_id_count, dest_mailbox_id, &err))
+                               EM_DEBUG_EXCEPTION("\t emcore_move_mail_on_server failed - %d", err);
+#endif
+               }
+       }
+
+       ret = true;
+FINISH_OFF:
+       EM_SAFE_FREE(mail_ids); /*prevent 33693*/
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int event_handler_EMAIL_EVENT_DELETE_MAILBOX(int mailbox_id, int on_server, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_id [%d], on_server [%d], handle_to_be_published [%d], error [%p]",  mailbox_id, on_server, handle_to_be_published, error);
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emnetwork_check_network_status(&err))
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+       else  {
+               if (!emcore_delete_mailbox(mailbox_id, on_server, &err))
+                       EM_DEBUG_LOG("emcore_delete failed - %d", err);
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_CREATE_MAILBOX(int account_id, char *mailbox_name, char *mailbox_alias, int mailbox_type, int on_server, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       email_mailbox_t mailbox;
+
+       memset(&mailbox, 0x00, sizeof(mailbox));
+
+       mailbox.account_id = account_id;
+       mailbox.mailbox_name = mailbox_name;
+       mailbox.alias = mailbox_alias;
+       mailbox.mailbox_type = mailbox_type;
+
+       if (!emnetwork_check_network_status(&err))  {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+       }
+       else  {
+               if (!emcore_create_mailbox(&mailbox, on_server, &err))
+                       EM_DEBUG_EXCEPTION("emcore_create failed - %d", err);
+       }
+
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER(int mail_id, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id [%d], error [%p]", mail_id, error);
+
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emnetwork_check_network_status(&err))
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+       else {
+               if (!emcore_sync_flag_with_server(mail_id, &err))
+                       EM_DEBUG_EXCEPTION("emcore_sync_flag_with_server failed [%d]", err);
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+               else {
+                       emstorage_activity_tbl_t new_activity;
+                       memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
+                       new_activity.activity_type = ACTIVITY_MODIFYFLAG;
+                       new_activity.account_id    = event_data.account_id;
+                       new_activity.mail_id       = event_data.event_param_data_4;
+                       new_activity.dest_mbox     = NULL;
+                       new_activity.server_mailid = NULL;
+                       new_activity.src_mbox      = NULL;
+
+                       if (!emcore_delete_activity(&new_activity, &err))
+                               EM_DEBUG_EXCEPTION(">>>>>>Local Activity [ACTIVITY_MODIFYFLAG] [%d] ", err);
+               }
+#endif /*  __FEATURE_LOCAL_ACTIVITY__ */
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_DELETE_MAIL_ALL(int input_account_id, int input_mailbox_id, int input_from_server, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_mailbox_id [%d], input_from_server [%d], error [%p]", input_account_id, input_mailbox_id, input_from_server, error);
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emcore_delete_all_mails_of_mailbox(input_account_id, input_mailbox_id, input_from_server, &err))
+               EM_DEBUG_EXCEPTION("emcore_delete_all_mails_of_mailbox failed [%d]", err);
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_DELETE_MAIL(int account_id, int *mail_id_list, int mail_id_count, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int ret = false;
+       email_account_t *account_ref = NULL;
+
+       if (!(account_ref = emcore_get_account_reference(account_id))) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_delete_mail(account_id, mail_id_list, mail_id_count, EMAIL_DELETE_FROM_SERVER, EMAIL_DELETED_BY_COMMAND, false, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_delete_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+FINISH_OFF:
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int event_hanlder_EMAIL_EVENT_SYNC_HEADER_OMA(int account_id, char *maibox_name, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emnetwork_check_network_status(&err))  {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               if (!emcore_notify_network_event(NOTI_DOWNLOAD_FAIL, account_id, maibox_name,  0, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed");
+       }
+       else  {
+               EM_DEBUG_LOG("Sync of all mailbox");
+               if (!emcore_sync_mailbox_list(account_id, "", handle_to_be_published, &err))
+                       EM_DEBUG_EXCEPTION("emcore_sync_mailbox_list failed [%d]", err);
+       }
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int event_handler_EMAIL_EVENT_SEARCH_ON_SERVER(int account_id, int mailbox_id, char *criteria, int handle_to_be_published, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id : [%d], mailbox_id : [%d], criteria : [%s]", account_id, mailbox_id, criteria);
+
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       int mail_id = 0;
+       int thread_id = 0;
+       char temp_uid_string[20] = {0,};
+
+       emcore_uid_list uid_elem;
+       emstorage_mailbox_tbl_t *search_mailbox = NULL;
+       emstorage_mail_tbl_t *new_mail_tbl_data = NULL;
+
+       MAILSTREAM *stream = NULL;
+       MESSAGECACHE *mail_cache_element = NULL;
+       ENVELOPE *env = NULL;
+       emstorage_mailbox_tbl_t* local_mailbox = NULL;
+       char mailbox_id_param_string[10] = {0,};
+
+       if (account_id < 0 || mailbox_id == 0) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ( (err = emstorage_get_mailbox_by_id(mailbox_id, &local_mailbox)) != EMAIL_ERROR_NONE || !local_mailbox) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(mailbox_id_param_string, 10, "%d", local_mailbox->mailbox_id);
+
+       if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_START, account_id, mailbox_id_param_string, handle_to_be_published, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_START] failed >>>>");
+
+       if (!emnetwork_check_network_status(&err)) {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string,  0, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed");
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_connect_to_remote_mailbox(account_id, mailbox_id, (void **)&stream, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed");
+               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
+               goto FINISH_OFF;
+       }
+
+       if (!mail_search_full(stream, NIL, mail_criteria(criteria), SE_FREE)) {
+               EM_DEBUG_EXCEPTION("mail_search failed");
+               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
+               goto FINISH_OFF;
+       }
+
+       for (i = 1; i <= stream->nmsgs; ++i) {
+               mail_cache_element = mail_elt(stream, i);
+               if (mail_cache_element->searched) {
+                       env = mail_fetchstructure_full(stream, i, NULL, FT_PEEK);
+
+                       memset(&uid_elem, 0x00, sizeof(uid_elem));
+
+                       uid_elem.msgno = mail_cache_element->msgno;
+                       SNPRINTF(temp_uid_string, 20, "%4lu", mail_cache_element->private.uid);
+                       uid_elem.uid = temp_uid_string;
+                       uid_elem.flag.seen = mail_cache_element->seen;
+
+                       if (!emcore_make_mail_tbl_data_from_envelope(stream, env, &uid_elem, &new_mail_tbl_data, &err) || !new_mail_tbl_data) {
+                               EM_DEBUG_EXCEPTION("emcore_make_mail_tbl_data_from_envelope failed [%d]", err);
+                               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
+                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
+                               goto FINISH_OFF;
+                       }
+
+                       search_mailbox = em_malloc(sizeof(emstorage_mailbox_tbl_t));
+                       if (search_mailbox == NULL) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
+                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
+                               goto FINISH_OFF;
+                       }
+
+                       search_mailbox->account_id = account_id;
+                       search_mailbox->mailbox_id = mailbox_id;
+                       search_mailbox->mailbox_name = EM_SAFE_STRDUP(EMAIL_SEARCH_RESULT_MAILBOX_NAME);
+                       search_mailbox->mailbox_type = EMAIL_MAILBOX_TYPE_SEARCH_RESULT;
+
+                       if ((err = emcore_add_mail_to_mailbox(search_mailbox, new_mail_tbl_data, &mail_id, &thread_id)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emcore_add_mail_to_mailbox failed [%d]", err);
+                               if (!emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FAIL, account_id, mailbox_id_param_string, handle_to_be_published, err))
+                                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEARCH_ON_SERVER_FAIL] Failed >>>>");
+                               goto FINISH_OFF;
+                       }
+                       memset(mailbox_id_param_string, 0, 10);
+                       SNPRINTF(mailbox_id_param_string, 10, "%d", search_mailbox->mailbox_id);
+                       if (!emcore_notify_storage_event(NOTI_MAIL_ADD, account_id, mail_id, mailbox_id_param_string, thread_id)) {
+                               EM_DEBUG_EXCEPTION("emcore_notify_storage_event [NOTI_MAIL_ADD] failed");
+                       }
+
+                       if (new_mail_tbl_data) {
+                               emstorage_free_mail(&new_mail_tbl_data, 1, NULL);
+                               new_mail_tbl_data = NULL;
+                       }
+               }
+       }
+
+       if (err == EMAIL_ERROR_NONE && !emcore_notify_network_event(NOTI_SEARCH_ON_SERVER_FINISH, account_id, NULL, handle_to_be_published, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_SEARCH_ON_SERVER_FINISH] Failed >>>>>");
+
+FINISH_OFF:
+
+       if (search_mailbox != NULL)
+               emstorage_free_mailbox(&search_mailbox, 1, NULL);
+
+       if (new_mail_tbl_data)
+               emstorage_free_mail(&new_mail_tbl_data, 1, NULL);
+
+       if (local_mailbox)
+               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+static int event_handler_EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER(int input_account_id, int input_mailbox_id, char *input_old_mailbox_path, char *input_new_mailbox_path, char *input_new_mailbox_alias, int handle_to_be_published)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_mailbox_id [%d], input_old_mailbox_path %s], input_new_mailbox_path [%s], input_new_mailbox_alias [%s], handle_to_be_published [%d]", input_account_id, input_mailbox_id, input_old_mailbox_path, input_new_mailbox_path, input_new_mailbox_alias, handle_to_be_published);
+       int err = EMAIL_ERROR_NONE;
+
+       if ((err = emcore_move_mailbox_on_imap_server(input_account_id, input_old_mailbox_path, input_new_mailbox_path)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_move_mailbox_on_imap_server failed [%d]", err);
+       }
+
+       if (err == EMAIL_ERROR_NONE) {
+               if(!emcore_notify_network_event(NOTI_RENAME_MAILBOX_FINISH, input_mailbox_id, input_new_mailbox_path, handle_to_be_published, 0))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_RENAME_MAILBOX_FINISH] failed");
+
+               if ((err = emstorage_rename_mailbox(input_mailbox_id, input_new_mailbox_path, input_new_mailbox_alias, true)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emstorage_rename_mailbox failed [%d]", err);
+               }
+       }
+       else if (!emcore_notify_network_event(NOTI_RENAME_MAILBOX_FAIL, input_mailbox_id, input_new_mailbox_path, handle_to_be_published, 0)) {
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_RENAME_MAILBOX_FAIL] failed");
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+void* thread_func_branch_command(void *arg)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       int is_storage_full = false;
+       int noti_id = 0;
+       email_event_t event_data;
+       email_session_t *session = NULL;
+       emstorage_account_tbl_t *account_tbl = NULL;
+       int handle_to_be_published = 0;
+
+       if (!emstorage_open(&err))  {
+               EM_DEBUG_EXCEPTION("emstorage_open falied [%d]", err);
+               return false;
+       }
+
+       /* check that event_data loop is continuous */
+       while (emcore_event_loop_continue())  {
+               if (!emcore_get_empty_session(&session))
+                       EM_DEBUG_EXCEPTION("emcore_get_empty_session failed...");
+
+               /* get a event_data from event_data queue */
+               if (!emcore_retrieve_event(&event_data, NULL))  {       /*  no event_data pending */
+                       EM_DEBUG_LOG("For handle g_event_que[g_event_que_idx].type [%d], g_event_que_idx [%d]", g_event_que[g_event_que_idx].type, g_event_que_idx);
+#ifdef ENABLE_IMAP_IDLE_THREAD
+                       if ( !emnetwork_check_network_status(&err))  {
+                               EM_DEBUG_LOG(">>>> Data Networking ON ");
+                               if (g_client_run) {
+                                       if (g_imap_idle_thread_alive) {
+                                               /* emcore_kill_imap_idle_thread(NULL); */
+                                               /* emcore_create_imap_idle_thread(NULL); */
+                                       }
+                                       else {
+                                               if (!send_thread_run)
+                                                       emcore_create_imap_idle_thread(event_data.account_id, NULL);
+                                       }
+                               }
+                       }
+#endif /*  ENABLE_IMAP_IDLE_THREAD */
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+                       /*  Local activity sync */
+                       if (g_client_run && g_local_activity_run) {
+                               emstorage_account_tbl_t *account_list = NULL;
+                               int count = 0, i;
+                               if (!emstorage_get_account_list(&count, &account_list, true, true, &err))
+                                       EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
+                               else {
+                                       for (i = 0; i < count; i++) {
+                                               if (emcore_local_activity_sync(account_list[i].account_id, &err)) {
+                                                       EM_DEBUG_LOG("Found local activity...!");
+                                                       EM_DEBUG_LOG("Resetting g_local_activity_run ");
+                                                       g_local_activity_run = 0;
+                                                       emcore_clear_session(session);
+                                               }
+                                       }
+
+                                       emstorage_free_account(&account_list, count, &err);
+
+                                       if (!g_local_activity_run)
+                                               continue;
+                               }
+                       }
+#endif
+
+                       recv_thread_run = 0;
+
+                       ENTER_CRITICAL_SECTION(_event_available_lock);
+                       SLEEP_CONDITION_VARIABLE(_event_available_signal, _event_available_lock);
+                       EM_DEBUG_LOG("Wake up by _event_available_signal");
+                       LEAVE_CRITICAL_SECTION(_event_available_lock);
+               }
+               else  {
+                       EM_DEBUG_LOG(">>>>>>>>>>>>>>> Got event_data !!! <<<<<<<<<<<<<<<");
+                       EM_DEBUG_LOG("For handle g_event_que_idx - %d", g_event_que_idx);
+
+                       if (g_event_que_idx == 1)
+                               handle_to_be_published = 31;
+                       else
+                               handle_to_be_published = g_event_que_idx - 1 ;
+
+                       EM_DEBUG_LOG("Handle to be Published  [%d]", handle_to_be_published);
+                       recv_thread_run = 1;
+                       g_client_run = 1;
+
+                       /*  Handling storage full */
+                       is_storage_full = false;
+                       if (event_data.type == EMAIL_EVENT_SYNC_HEADER || event_data.type == EMAIL_EVENT_SYNC_HEADER_OMA ||
+                               event_data.type == EMAIL_EVENT_DOWNLOAD_BODY || event_data.type == EMAIL_EVENT_DOWNLOAD_ATTACHMENT) {
+                               if (emcore_is_storage_full(&err) == true) {
+                                       EM_DEBUG_EXCEPTION("Storage is full");
+                                       switch (event_data.type) {
+                                               case EMAIL_EVENT_SYNC_HEADER:
+                                               case EMAIL_EVENT_SYNC_HEADER_OMA:
+                                                       noti_id = NOTI_DOWNLOAD_FAIL;
+                                                       break;
+                                               case EMAIL_EVENT_DOWNLOAD_BODY:
+                                                       noti_id = NOTI_DOWNLOAD_BODY_FAIL;
+                                                       break;
+                                               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                                                       noti_id = NOTI_DOWNLOAD_ATTACH_FAIL;
+                                                       break;
+                                               default:
+                                                       break;
+                                       }
+
+                                       if (!emcore_notify_network_event(noti_id, event_data.account_id, NULL,  handle_to_be_published, err))
+                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_FAIL] Failed >>>> ");
+                                       is_storage_full = true;
+                               }
+                       }
+
+                       emdevice_set_dimming_on_off(false, NULL);
+
+                       if (event_data.account_id > 0) {
+                               if (!emstorage_get_account_by_id(event_data.account_id, EMAIL_ACC_GET_OPT_DEFAULT, &account_tbl, false, &err)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id [%d]", err);
+                               }
+                       }
+
+                       if (account_tbl)
+                               EM_DEBUG_LOG("account_id : [%d], sync_disabled : [%d]", event_data.account_id, account_tbl->sync_disabled);
+
+                       if (!account_tbl || account_tbl->sync_disabled == 0) {
+                               switch (event_data.type)  {
+                                       case EMAIL_EVENT_SYNC_IMAP_MAILBOX:  /*  get imap mailbox list  */
+                                               if (!emcore_sync_mailbox_list(event_data.account_id, event_data.event_param_data_3, handle_to_be_published, &err))
+                                                       EM_DEBUG_EXCEPTION("emcore_sync_mailbox_list failed [%d]", err);
+                                               EM_SAFE_FREE(event_data.event_param_data_3);
+                                               break;
+
+                                       case EMAIL_EVENT_SYNC_HEADER:  /*  synchronize mail header  */
+                                               if (is_storage_full == false)
+                                                       event_handler_EMAIL_EVENT_SYNC_HEADER(event_data.account_id, event_data.event_param_data_5, handle_to_be_published,  &err);
+                                               break;
+
+                                       case EMAIL_EVENT_SYNC_HEADER_OMA:  /*  synchronize mail header for OMA */
+                                               if (is_storage_full == false)
+                                                       event_hanlder_EMAIL_EVENT_SYNC_HEADER_OMA(event_data.account_id, event_data.event_param_data_1, handle_to_be_published, &err);
+                                               EM_SAFE_FREE(event_data.event_param_data_1);
+                                               break;
+
+                                       case EMAIL_EVENT_DOWNLOAD_BODY:  /*  download mail body  */
+                                               if (is_storage_full == false)
+                                                       event_handler_EMAIL_EVENT_DOWNLOAD_BODY(event_data.account_id, (int)event_data.event_param_data_4, (int)event_data.event_param_data_3, handle_to_be_published, &err);
+                                               event_data.event_param_data_3 = NULL;           /*  MUST BE */
+                                               break;
+
+                                       case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:  /*  download attachment */
+                                               if (is_storage_full == false)
+                                                       event_handler_EMAIL_EVENT_DOWNLOAD_ATTACHMENT(event_data.account_id, (int)event_data.event_param_data_4, event_data.event_param_data_5, handle_to_be_published, &err);
+                                               break;
+
+                                       case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:  /*  Sync flags field */
+                                               event_handler_EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER((int*)event_data.event_param_data_3, event_data.event_param_data_4 , event_data.event_param_data_5, event_data.event_param_data_6, &err);
+                                               EM_SAFE_FREE(event_data.event_param_data_3);
+                                               break;
+
+                                       case EMAIL_EVENT_DELETE_MAIL:  /*  delete mails */
+                                               event_handler_EMAIL_EVENT_DELETE_MAIL(event_data.account_id, (int*)event_data.event_param_data_3, event_data.event_param_data_4, &err);
+                                               EM_SAFE_FREE(event_data.event_param_data_3);
+                                               break;
+
+                                       case EMAIL_EVENT_DELETE_MAIL_ALL:  /*  delete all mails */
+                                               event_handler_EMAIL_EVENT_DELETE_MAIL_ALL(event_data.account_id, event_data.event_param_data_4, (int)event_data.event_param_data_5, &err);
+                                               break;
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+                                       case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                                               event_handler_EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER((int)event_data.event_param_data_4, &err);
+                                               break;
+#endif
+
+                                       case EMAIL_EVENT_CREATE_MAILBOX:
+                                               event_handler_EMAIL_EVENT_CREATE_MAILBOX(event_data.account_id, event_data.event_param_data_1, event_data.event_param_data_2, GPOINTER_TO_INT(event_data.event_param_data_3), event_data.event_param_data_4, handle_to_be_published, &err);
+                                               EM_SAFE_FREE(event_data.event_param_data_1);
+                                               EM_SAFE_FREE(event_data.event_param_data_2);
+                                               break;
+
+                                       case EMAIL_EVENT_DELETE_MAILBOX:
+                                               event_handler_EMAIL_EVENT_DELETE_MAILBOX(event_data.event_param_data_4, event_data.event_param_data_4, handle_to_be_published, &err);
+                                               break;
+
+                                       case EMAIL_EVENT_SAVE_MAIL:
+                                               err = event_handler_EMAIL_EVENT_SAVE_MAIL(event_data.account_id, event_data.event_param_data_4, handle_to_be_published);
+                                               break;
+
+                                       case EMAIL_EVENT_MOVE_MAIL:
+                                               event_handler_EMAIL_EVENT_MOVE_MAIL(event_data.account_id, (int  *)event_data.event_param_data_3, event_data.event_param_data_4, event_data.event_param_data_5, event_data.event_param_data_8, handle_to_be_published, &err);
+                                               event_data.event_param_data_3 = NULL; /*prevent 33693*/
+                                               break;
+
+                                       case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                                               event_handler_EMAIL_EVENT_VALIDATE_ACCOUNT(event_data.account_id, handle_to_be_published, &err);
+                                               break;
+
+                                       case EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT: {
+/*                                             event_handler_EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT(emcore_get_account_from_unvalidated_account_list(), handle_to_be_published, &err);*/
+                                                       email_account_t *account = (email_account_t *)event_data.event_param_data_1;
+                                                       event_handler_EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT(account, handle_to_be_published, &err);
+                                                       if(account) {
+                                                               emcore_free_account(account);
+                                                               EM_SAFE_FREE(account);
+                                                       }
+                                               }
+                                               break;
+
+                                       case EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT: {
+                                                       email_account_t *account = (email_account_t *)event_data.event_param_data_1;
+                                                       event_handler_EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT(event_data.account_id, account, handle_to_be_published, &err);
+                                                       emcore_free_account(account);
+                                                       EM_SAFE_FREE(account);
+                                               }
+                                               break;
+
+                                       case EMAIL_EVENT_UPDATE_MAIL:
+                                               event_handler_EMAIL_EVENT_UPDATE_MAIL((email_mail_data_t*)event_data.event_param_data_1, (email_attachment_data_t*)event_data.event_param_data_2, event_data.event_param_data_4, (email_meeting_request_t*)event_data.event_param_data_3, event_data.event_param_data_5, handle_to_be_published);
+
+                                               event_data.event_param_data_1 = NULL;
+                                               event_data.event_param_data_2 = NULL;
+                                               event_data.event_param_data_3 = NULL;
+                                               break;
+
+                                       case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                                               event_handler_EMAIL_EVENT_SET_MAIL_SLOT_SIZE(event_data.account_id, event_data.event_param_data_4, event_data.event_param_data_5, handle_to_be_published, &err);
+                                               break;
+
+                                       case EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED:
+                                               err = event_handler_EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED(event_data.account_id, event_data.event_param_data_4);
+                                               break;
+
+       #ifdef __FEATURE_LOCAL_ACTIVITY__
+                                       case EMAIL_EVENT_LOCAL_ACTIVITY:
+                                               event_handler_EMAIL_EVENT_LOCAL_ACTIVITY(event_data.account_id, &err);
+                                               break;
+       #endif /* __FEATURE_LOCAL_ACTIVITY__*/
+
+                                       case EMAIL_EVENT_SEARCH_ON_SERVER:
+                                               event_handler_EMAIL_EVENT_SEARCH_ON_SERVER(event_data.account_id, event_data.event_param_data_4, (char *)event_data.event_param_data_1, handle_to_be_published, &err);
+                                               EM_SAFE_FREE(event_data.event_param_data_1);
+                                               break;
+
+                                       case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                                               err = event_handler_EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER(event_data.account_id, event_data.event_param_data_4, (char*)event_data.event_param_data_1, (char*)event_data.event_param_data_2, (char*)event_data.event_param_data_3, handle_to_be_published);
+                                               EM_SAFE_FREE(event_data.event_param_data_1);
+                                               EM_SAFE_FREE(event_data.event_param_data_2);
+                                               EM_SAFE_FREE(event_data.event_param_data_3);
+                                               break;
+
+                                       default:
+                                               break;
+                               }
+                       }
+
+                       if (account_tbl) {
+                               emstorage_free_account(&account_tbl, 1, NULL);
+                               account_tbl = NULL;
+                       }
+
+                       if (!emcore_notify_response_to_api(event_data.type, handle_to_be_published, err))
+                               EM_DEBUG_EXCEPTION("emcore_notify_response_to_api failed");
+
+                       emdevice_set_dimming_on_off(true, NULL);
+                       em_flush_memory();
+
+                       switch (event_data.type)  {
+                               case EMAIL_EVENT_SEND_MAIL:
+                               case EMAIL_EVENT_SEND_MAIL_SAVED:
+                                       _sending_busy_unref();
+                                       break;
+
+                               case EMAIL_EVENT_SYNC_HEADER:
+                               case EMAIL_EVENT_SYNC_HEADER_OMA:
+                               case EMAIL_EVENT_DOWNLOAD_BODY:
+                               case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                               case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                               case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
+                               case EMAIL_EVENT_DELETE_MAIL:
+                               case EMAIL_EVENT_DELETE_MAIL_ALL:
+                               case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                               case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
+                               case EMAIL_EVENT_SAVE_MAIL:
+                               case EMAIL_EVENT_MOVE_MAIL:
+                               case EMAIL_EVENT_CREATE_MAILBOX:
+                               case EMAIL_EVENT_DELETE_MAILBOX:
+                               case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                               case EMAIL_EVENT_SEARCH_ON_SERVER:
+                               case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                                       _receiving_busy_unref();
+                                       break;
+
+                               default:
+                                       break;
+                       }
+
+                       event_data.type = 0;
+
+                       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+                       memset(g_event_que+g_active_que, 0x00, sizeof(email_event_t));
+                       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+               }
+
+               emcore_clear_session(session);
+       }
+
+       if (!emstorage_close(&err))
+               EM_DEBUG_EXCEPTION("emstorage_close falied [%d]", err);
+
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+/*Send event_data loop*/
+INTERNAL_FUNC int emcore_start_event_loop_for_sending_mails(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int thread_error = -1;
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+       memset(&g_send_event_que, 0x00, sizeof(g_send_event_que));
+
+       if (g_send_srv_thread)  {
+               EM_DEBUG_EXCEPTION("\t send service thread is already running...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return true;
+       }
+
+       g_send_event_que_idx = 1;
+       g_send_event_loop = 1;
+       g_send_active_que = 0;
+
+       /* initialize lock */
+       /*  INITIALIZE_CRITICAL_SECTION(_send_event_available_lock); */
+       INITIALIZE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+       INITIALIZE_CONDITION_VARIABLE(_send_event_available_signal);
+
+       /* create thread */
+       THREAD_CREATE_JOINABLE(g_send_srv_thread, thread_func_branch_command_for_sending_mails, thread_error);
+
+       if (thread_error != 0) {
+               EM_DEBUG_EXCEPTION("cannot make thread...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return FAILURE;
+       }
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+/* finish api event_data loop */
+INTERNAL_FUNC int emcore_send_event_loop_stop(int *err_code)
+{
+    EM_DEBUG_FUNC_BEGIN();
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+       if (!g_send_srv_thread)          {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return false;
+       }
+
+    /* stop event_data loop */
+    g_send_event_loop = 0;
+
+       emcore_cancel_send_mail_thread(g_send_active_que, NULL, err_code);
+       ENTER_CRITICAL_SECTION(_send_event_available_lock);
+       WAKE_CONDITION_VARIABLE(_send_event_available_signal);          /*  MUST BE HERE */
+       LEAVE_CRITICAL_SECTION(_send_event_available_lock);
+
+       /* wait for thread finished */
+       THREAD_JOIN(g_send_srv_thread);
+
+       g_send_srv_thread = 0;
+
+       DELETE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+       DELETE_CRITICAL_SECTION(_send_event_available_lock);
+       DELETE_CONDITION_VARIABLE(_send_event_available_signal);
+
+       g_send_event_que_idx = 1;
+       g_send_active_que = 0;
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+    return true;
+}
+
+/* start api event_data loop */
+INTERNAL_FUNC int emcore_start_event_loop(int *err_code)
+{
+    EM_DEBUG_FUNC_BEGIN();
+       int thread_error;
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+    memset(&g_event_que, 0x00, sizeof(g_event_que));
+
+       if (g_srv_thread) {
+               EM_DEBUG_EXCEPTION("service thread is already running...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return true;
+       }
+
+       g_event_que_idx = 1;
+       g_event_loop = 1;
+       g_active_que = 0;
+
+    /* initialize lock */
+       INITIALIZE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+       INITIALIZE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+
+       emcore_initialize_event_callback_table();
+
+    /* create thread */
+       THREAD_CREATE(g_srv_thread, thread_func_branch_command, NULL, thread_error);
+
+       if (thread_error != 0) {
+        EM_DEBUG_EXCEPTION("cannot create thread");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
+        return FAILURE;
+    }
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+    return false;
+}
+
+/* finish api event_data loop */
+INTERNAL_FUNC int emcore_stop_event_loop(int *err_code)
+{
+    EM_DEBUG_FUNC_BEGIN();
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+       if (!g_srv_thread)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return false;
+       }
+
+    /* stop event_data loop */
+    g_event_loop = 0;
+
+       /*      pthread_kill(g_srv_thread, SIGINT); */
+       emcore_cancel_thread(g_active_que, NULL, err_code);
+
+       ENTER_CRITICAL_SECTION(_event_available_lock);
+       WAKE_CONDITION_VARIABLE(_event_available_signal);
+       LEAVE_CRITICAL_SECTION(_event_available_lock);
+
+       /* wait for thread finished */
+       THREAD_JOIN(g_srv_thread);
+
+       g_srv_thread = 0;
+
+       DELETE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+       DELETE_CRITICAL_SECTION(_event_available_lock);
+       DELETE_CONDITION_VARIABLE(_event_available_signal);
+       DELETE_RECURSIVE_CRITICAL_SECTION(_event_callback_table_lock);
+
+       g_event_que_idx = 1;
+       g_active_que = 0;
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+       EM_DEBUG_FUNC_END();
+    return true;
+}
+
+
+int emcore_get_active_queue_idx()
+{
+       return g_send_active_que;
+}
+
+/* check thread status
+* 0 : stop job 1 : continue job
+*/
+INTERNAL_FUNC int emcore_check_thread_status()
+{
+       if (g_active_que <= 0)
+               return true;
+
+       return (g_event_que[g_active_que].status == EMAIL_EVENT_STATUS_STARTED);
+}
+
+/* cancel a job  */
+INTERNAL_FUNC int emcore_cancel_thread(int handle, void *arg, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("handle[%d], arg[%p], err_code[%p]", handle, arg, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (handle <= 0 || handle > (EVENT_QUEUE_MAX - 1))  {
+               EM_DEBUG_EXCEPTION("handle[%d], arg[%p]", handle, arg);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       EM_DEBUG_LOG("status[%d], type[%d], handle[%d]", g_event_que[handle].status, g_event_que[handle].type, handle);
+
+       if (g_event_que[handle].status == EMAIL_EVENT_STATUS_WAIT)  {
+               fail_status_notify(&g_event_que[handle], EMAIL_ERROR_CANCELLED);
+
+               switch (g_event_que[handle].type)  {
+                       case EMAIL_EVENT_SEND_MAIL:
+                       case EMAIL_EVENT_SEND_MAIL_SAVED:
+                               EM_DEBUG_LOG("EMAIL_EVENT_SEND_MAIL or EMAIL_EVENT_SEND_MAIL_SAVED");
+                               _sending_busy_unref();
+                               if (!emcore_notify_network_event(NOTI_SEND_CANCEL, g_event_que[handle].account_id, NULL , g_event_que[handle].event_param_data_4, err))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>> ");
+                               break;
+                       case EMAIL_EVENT_DOWNLOAD_BODY:
+                               EM_DEBUG_LOG("EMAIL_EVENT_DOWNLOAD_BODY");
+                               _receiving_busy_unref();
+                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_CANCEL, g_event_que[handle].account_id, NULL , g_event_que[handle].event_param_data_4, err))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>> ");
+                               break;
+
+                       case EMAIL_EVENT_SYNC_HEADER:
+                       case EMAIL_EVENT_SYNC_HEADER_OMA:
+                       case EMAIL_EVENT_DOWNLOAD_ATTACHMENT:
+                       case EMAIL_EVENT_SYNC_MAIL_FLAG_TO_SERVER:
+                       case EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER:
+                               EM_DEBUG_LOG("EMAIL_EVENT_SYNC_HEADER, EMAIL_EVENT_DOWNLOAD_ATTACHMENT");
+                               _receiving_busy_unref();
+                               break;
+
+                       case EMAIL_EVENT_VALIDATE_ACCOUNT:
+                               EM_DEBUG_LOG(" validate account waiting  :  cancel acc id  :  %d", g_event_que[handle].account_id);
+                               _receiving_busy_unref();
+                               if (!emcore_notify_network_event(NOTI_VALIDATE_ACCOUNT_CANCEL, g_event_que[handle].account_id, NULL , g_event_que[handle].event_param_data_4, err))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_VALIDATE_ACCOUNT_CANCEL] Failed >>>> ");
+                               break;
+
+                       case EMAIL_EVENT_DELETE_MAIL:
+                       case EMAIL_EVENT_DELETE_MAIL_ALL:
+                       case EMAIL_EVENT_SYNC_IMAP_MAILBOX:
+                       case EMAIL_EVENT_SAVE_MAIL:
+                       case EMAIL_EVENT_MOVE_MAIL:
+                       case EMAIL_EVENT_CREATE_MAILBOX:
+                       case EMAIL_EVENT_DELETE_MAILBOX:
+                       case EMAIL_EVENT_SET_MAIL_SLOT_SIZE:
+                       case EMAIL_EVENT_SEARCH_ON_SERVER:
+                       case EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER:
+                               EM_DEBUG_LOG("EMAIL_EVENT_DELETE_MAIL, EMAIL_EVENT_SYNC_IMAP_MAILBOX");
+                               _receiving_busy_unref();
+                               break;
+                       default:
+                               break;
+               }
+       }
+
+       memset(g_event_que+handle, 0x00, sizeof(email_event_t));
+       g_event_que[handle].status = EMAIL_EVENT_STATUS_CANCELED;
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_event_queue_lock);
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+/* check thread status
+* 0 : stop job 1 : continue job
+*/
+int emcore_check_send_mail_thread_status()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (g_send_active_que <= 0)
+               return true;
+       EM_DEBUG_LOG("g_send_event_que[g_send_active_que[%d]].status[%d]", g_send_active_que, g_send_event_que[g_send_active_que].status);
+       EM_DEBUG_FUNC_END();
+       return (g_send_event_que[g_send_active_que].status == EMAIL_EVENT_STATUS_STARTED);
+}
+
+INTERNAL_FUNC int emcore_cancel_all_threads_of_an_account(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error_code = EMAIL_ERROR_NONE;
+       int i, event_count = EVENT_QUEUE_MAX, exit_flag = 0, sleep_count = 0;
+
+       for (i = 0 ; i < event_count; i++) {
+               if (g_event_que[i].type && g_event_que[i].status != EMAIL_EVENT_STATUS_UNUSED) {
+                       EM_DEBUG_LOG("There is a live thread. %d", i);
+                       if (g_event_que[i].account_id == account_id || g_event_que[i].account_id == ALL_ACCOUNT) {
+                               EM_DEBUG_LOG("And it is for account %d", g_event_que[i].account_id);
+                               emcore_cancel_thread(i, NULL, &error_code);
+                       }
+               }
+       }
+
+       while (exit_flag == 0 && sleep_count < 30) {
+               EM_DEBUG_LOG("Sleeping...");
+               usleep(100000);
+               EM_DEBUG_LOG("Wake up!");
+               sleep_count++;
+               exit_flag = 1;
+               for (i = 0 ; i < event_count; i++) {
+                       if (g_event_que[i].type && g_event_que[i].status != EMAIL_EVENT_STATUS_UNUSED) {
+                               EM_DEBUG_LOG("There is still a live thread. %d", i);
+                               if (g_event_que[i].account_id == account_id || g_event_que[i].account_id == ALL_ACCOUNT) {
+                                       EM_DEBUG_LOG("And it is for account %d. So, I should sleep for a while.", g_event_que[i].account_id);
+                                       exit_flag = 0;
+                               }
+                       }
+               }
+       }
+
+       EM_DEBUG_LOG("Sleep count %d", sleep_count);
+
+       if (sleep_count >= 30)
+               error_code = EMAIL_ERROR_CANNOT_STOP_THREAD;
+       else
+               error_code = EMAIL_ERROR_NONE;
+       EM_DEBUG_FUNC_END();
+       return error_code;
+}
+
+
+/* cancel send mail job  */
+INTERNAL_FUNC int emcore_cancel_send_mail_thread(int handle, void *arg, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("handle[%d], arg[%p], err_code[%p]", handle, arg, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (handle <= 0 || handle > (EVENT_QUEUE_MAX - 1))  {
+               EM_DEBUG_EXCEPTION("handle[%d], arg[%p]", handle, arg);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ENTER_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+
+       EM_DEBUG_LOG("event_data.status[%d], handle[%d]", g_send_event_que[handle].status, handle);
+
+       if (g_send_event_que[handle].status == EMAIL_EVENT_STATUS_WAIT)  {
+               fail_status_notify(&g_send_event_que[handle], EMAIL_ERROR_CANCELLED);
+
+               switch (g_send_event_que[handle].type)  {
+                       case EMAIL_EVENT_SEND_MAIL:
+                       case EMAIL_EVENT_SEND_MAIL_SAVED:
+                               _sending_busy_unref();
+                               g_send_event_que[handle].status = EMAIL_EVENT_STATUS_CANCELED;
+                               if (!emcore_notify_network_event(NOTI_SEND_CANCEL, g_send_event_que[handle].account_id, NULL , g_send_event_que[handle].event_param_data_4, err))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_CANCEL] Failed >>>> ");
+                               break;
+                       default:
+                               break;
+               }
+       }
+
+       EM_DEBUG_LOG("send_mail_cancel");
+       memset(g_send_event_que+handle, 0x00, sizeof(email_event_t));
+       g_send_event_que[handle].status = EMAIL_EVENT_STATUS_CANCELED;
+
+       EM_DEBUG_LOG("event_data.status[%d], handle[%d]", g_send_event_que[handle].status, handle);
+
+
+       LEAVE_RECURSIVE_CRITICAL_SECTION(_send_event_queue_lock);
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_get_receiving_event_queue(email_event_t **event_queue, int *event_active_queue, int *err)
+{
+       if (event_queue == NULL || event_active_queue == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM event_queue[%p] event_active_queue[%p]", event_queue, event_active_queue);
+
+               if (err)
+                       *err = EMAIL_ERROR_INVALID_PARAM;
+
+               return false;
+       }
+
+       *event_queue = g_event_que;
+       *event_active_queue = g_active_que;
+
+       return true;
+}
+
+INTERNAL_FUNC int emcore_free_event(email_event_t *event_data)
+{
+       EM_DEBUG_FUNC_BEGIN("event_data [%p]", event_data);
+
+       if(event_data) {
+               EM_SAFE_FREE(event_data->event_param_data_1);
+               EM_SAFE_FREE(event_data->event_param_data_2);
+               EM_SAFE_FREE(event_data->event_param_data_3);
+       }
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+INTERNAL_FUNC unsigned int emcore_get_receiving_thd_id()
+{
+       return (unsigned int)g_srv_thread;
+}
+#endif /*  __FEATURE_KEEP_CONNECTION__ */
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+INTERNAL_FUNC int emcore_get_pbd_thd_state()
+{
+       int pbd_thd_state = false;
+       ENTER_CRITICAL_SECTION(_state_variables_lock);
+       pbd_thd_state = g_pbd_thd_state;
+       LEAVE_CRITICAL_SECTION(_state_variables_lock);
+       return pbd_thd_state;
+}
+
+static int emcore_set_pbd_thd_state(int flag)
+{
+       ENTER_CRITICAL_SECTION(_state_variables_lock);
+       g_pbd_thd_state = flag;
+       LEAVE_CRITICAL_SECTION(_state_variables_lock);
+
+       return g_pbd_thd_state;
+}
+
+INTERNAL_FUNC unsigned int emcore_get_partial_body_thd_id()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_END();
+       return (unsigned int)g_partial_body_thd;
+}
+
+static int emcore_clear_bulk_pbd_que(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = true;
+       int error = EMAIL_ERROR_NONE;
+       int i = 0;
+
+       for (i = 0; i < BULK_PARTIAL_BODY_DOWNLOAD_COUNT; ++i) {
+               if (g_partial_body_bulk_dwd_que[i].event_type) {
+                       if (false == emcore_free_partial_body_thd_event(g_partial_body_bulk_dwd_que + i, &error))                                        {
+                               EM_DEBUG_EXCEPTION("emcore_free_partial_body_thd_event_cell failed [%d]", error);
+                               ret = false;
+                               break;
+                       }
+               }
+       }
+
+       if (NULL != err_code)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+static void emcore_pb_thd_set_local_activity_continue(int flag)
+{
+       EM_DEBUG_FUNC_BEGIN("flag [%d]", flag);
+
+       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       g_pb_thd_local_activity_continue = flag;
+
+       if (true == flag) {
+               WAKE_CONDITION_VARIABLE(_partial_body_thd_cond);
+       }
+
+       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+       EM_DEBUG_FUNC_END();
+}
+
+static
+int emcore_pb_thd_can_local_activity_continue()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+
+       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       ret = g_pb_thd_local_activity_continue;
+
+       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+       EM_DEBUG_FUNC_END();
+       return ret;
+
+}
+
+INTERNAL_FUNC int emcore_clear_partial_body_thd_event_que(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = true;
+       int error = EMAIL_ERROR_NONE;
+       int i = 0;
+
+       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       if (true == g_partial_body_thd_queue_empty) {
+               EM_DEBUG_LOG(" Partial Body Thread Event Queue Already empty ");
+       }
+       else {
+               for (i = 0; i < TOTAL_PARTIAL_BODY_EVENTS; ++i) {
+                       if (g_partial_body_thd_event_que[i].event_type) {
+                               if (false == emcore_free_partial_body_thd_event(g_partial_body_thd_event_que + i, &error))                                       {
+                                       EM_DEBUG_EXCEPTION("emcore_free_partial_body_thd_event_cell failed [%d]", error);
+                                       ret = false;
+                                       break;
+                               }
+                       }
+               }
+
+               g_partial_body_thd_queue_empty = true;
+               g_partial_body_thd_queue_full = false;
+       }
+       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       if (NULL != err_code)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_is_partial_body_thd_que_empty()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+
+       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       ret = g_partial_body_thd_queue_empty;
+
+       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+INTERNAL_FUNC int emcore_is_partial_body_thd_que_full()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+
+       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       ret = g_partial_body_thd_queue_full;
+
+       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+/*
+Himanshu[h.gahalut] :  If either src pointer or dest pointer points to a cell of global partial body thread event_data queue,
+then emcore_copy_partial_body_thd_event API should only be called from a portion of code which is protected
+through _partial_body_thd_event_queue_lock mutex.
+
+No mutex is used inside this API so that we can also use it to copy partial body events which are not a part of global event_data queue
+
+Precautions :
+
+_partial_body_thd_event_queue_lock mutex should never be used inside this API otherwise it will be a deadlock.
+Also never call any function from this API which uses _partial_body_thd_event_queue_lock mutex.
+
+*/
+
+static int emcore_copy_partial_body_thd_event(email_event_partial_body_thd *src, email_event_partial_body_thd *dest, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+
+       if (NULL == src || NULL == dest) {
+               EM_DEBUG_LOG(" Invalid Parameter src [%p] dest [%p]", src, dest);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       dest->account_id = src->account_id;
+       dest->mail_id = src->mail_id;
+       dest->server_mail_id = src->server_mail_id;
+       dest->activity_id = src->activity_id;
+       dest->mailbox_id = src->mailbox_id;
+       dest->mailbox_name = EM_SAFE_STRDUP(src->mailbox_name);
+       dest->activity_type = src->activity_type;
+       dest->event_type = src->event_type;
+
+       EM_DEBUG_LOG("dest->account_id[%d], dest->mail_id[%d], dest->server_mail_id [%lu]", dest->account_id, dest->mail_id , dest->server_mail_id);
+
+       ret = true;
+
+       FINISH_OFF:
+
+       if (NULL != error_code)
+               *error_code = error;
+
+       return ret;
+
+}
+
+/*
+Himanshu[h.gahalut] :  If emcore_free_partial_body_thd_event_cell API is used to free a cell of partial body thread event_data queue,
+it should only be called from a portion of code which is protected through _partial_body_thd_event_queue_lock mutex.
+
+No mutex is used inside this API so that we can also use it to free partial body events which are not a part of global event_data queue
+
+Precautions :
+
+_partial_body_thd_event_queue_lock mutex should never be used inside this API otherwise it will be a deadlock.
+Also never call any function from this API which uses _partial_body_thd_event_queue_lock mutex.
+
+*/
+
+INTERNAL_FUNC int emcore_free_partial_body_thd_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (NULL == partial_body_thd_event) {
+               *error_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       email_event_partial_body_thd *pbd_event = partial_body_thd_event;
+
+       /*Free character pointers in event_data cell */
+       EM_SAFE_FREE(pbd_event->mailbox_name);
+       memset(pbd_event, 0x00, sizeof(email_event_partial_body_thd));
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+INTERNAL_FUNC int emcore_insert_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (NULL == partial_body_thd_event)  {
+               EM_DEBUG_EXCEPTION("\t partial_body_thd_event [%p] ", partial_body_thd_event);
+
+               if (error_code != NULL) {
+                       *error_code = EMAIL_ERROR_INVALID_PARAM;
+               }
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int empty_cell_index = -1;
+       int index = 0;
+       int count = 0;
+
+       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       /* find a cell in queue which is empty */
+
+       for (count = 0, index =  g_partial_body_thd_next_event_idx; count < TOTAL_PARTIAL_BODY_EVENTS;) {
+               if  (g_partial_body_thd_event_que[index].event_type) {
+                       ++index;
+                       ++count;
+
+                       if (index == TOTAL_PARTIAL_BODY_EVENTS) {
+                               index = 0;
+                       }
+               }
+               else {
+                       /*Found empty Cell*/
+
+                       empty_cell_index =       index;
+                       break;
+               }
+       }
+
+       if (-1 != empty_cell_index) {
+               if (false == emcore_copy_partial_body_thd_event(partial_body_thd_event, g_partial_body_thd_event_que+empty_cell_index , &error)) {
+                       EM_DEBUG_LOG("emcore_copy_partial_body_thd_event failed [%d]", error);
+               }
+               else {
+                       g_partial_body_thd_queue_empty = false;
+
+                       if (count == (TOTAL_PARTIAL_BODY_EVENTS - 1)) {
+                               /*This is the last event_data inserted in queue after its insertion, queue is full */
+                               g_partial_body_thd_queue_full = true;
+
+                       }
+
+                       WAKE_CONDITION_VARIABLE(_partial_body_thd_cond);
+
+                       ret = true;
+               }
+       }
+       else {
+               EM_DEBUG_LOG(" partial body thread event_data queue is full ");
+               error = EMAIL_ERROR_EVENT_QUEUE_FULL;
+
+               g_partial_body_thd_queue_full = true;
+               g_partial_body_thd_queue_empty = false;
+
+       }
+
+       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       if (NULL != error_code) {
+               *error_code = error;
+       }
+
+       return ret;
+
+}
+
+/* h.gahlaut :  Return true only if event_data is retrieved successfully */
+
+static int emcore_retrieve_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int index = 0;
+
+       /* Lock Mutex to protect event_data queue and associated global variables variables*/
+
+       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       index = g_partial_body_thd_next_event_idx;
+
+       if (0 == g_partial_body_thd_event_que[index].event_type) {
+               error = EMAIL_ERROR_EVENT_QUEUE_EMPTY;
+               g_partial_body_thd_queue_empty = true;
+               g_partial_body_thd_queue_full = false;
+       }
+       else {
+               /*Copy the event_data from queue to return it and free the event_data in queue */
+               if (false == emcore_copy_partial_body_thd_event(g_partial_body_thd_event_que + index, partial_body_thd_event, &error))
+                       EM_DEBUG_EXCEPTION("emcore_copy_partial_body_thd_event failed [%d]", error);
+               else {
+                       if (false == emcore_free_partial_body_thd_event(g_partial_body_thd_event_que + index, &error))
+                               EM_DEBUG_EXCEPTION("emcore_free_partial_body_thd_event_cell failed [%d]", error);
+                       else {
+
+                               g_partial_body_thd_queue_full = false;
+                               g_partial_body_thd_next_event_idx = ++index;
+
+                               if (g_partial_body_thd_next_event_idx == TOTAL_PARTIAL_BODY_EVENTS)
+                                       g_partial_body_thd_next_event_idx = 0;
+
+                               /* If the event_data retrieved was the only event_data present in queue,
+                               we need to set g_partial_body_thd_queue_empty to true
+                               */
+
+                               if (0 == g_partial_body_thd_event_que[g_partial_body_thd_next_event_idx].event_type) {
+                                       g_partial_body_thd_queue_empty = true;
+                               }
+
+                               ret = true;
+                       }
+               }
+       }
+
+       /* Unlock Mutex */
+
+       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+       if (error_code)
+               *error_code = error;
+
+       return ret;
+
+}
+
+gpointer partial_body_download_thread(gpointer data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       email_session_t *session = NULL;
+       email_event_partial_body_thd partial_body_thd_event;
+
+       EM_DEBUG_LOG(" ************ PB THREAD ID IS ALIVE. ID IS [%d] ********************" , THREAD_SELF());
+
+       /* Open connection with DB */
+
+       if (false == emstorage_open(&err))  {
+               EM_DEBUG_EXCEPTION("emstorage_open failed [%d]", err);
+               return false;
+       }
+
+       /* Start the continuous loop */
+
+       while (g_partial_body_thd_loop) {
+               /*  Get an empty session  */
+               /*  TODO :  Mutex should be used in session APIs */
+
+               if (false == emcore_get_empty_session(&session))
+                       EM_DEBUG_EXCEPTION("emcore_get_empty_session failed...");
+               else {  /* Get and Event from the Partial Body thread Event Queue */
+                       memset(&partial_body_thd_event, 0x00, sizeof(email_event_partial_body_thd));
+
+                       if (false == emcore_retrieve_partial_body_thread_event(&partial_body_thd_event, &err)) {
+                               if (EMAIL_ERROR_EVENT_QUEUE_EMPTY != err)
+                                       EM_DEBUG_EXCEPTION("emcore_retrieve_partial_body_thread_event failed [%d]", err);
+                               else {
+                                       EM_DEBUG_LOG(" partial body thread event_data queue is empty.");
+
+                                       /*  Flush the que before starting local activity sync to clear the events in queue which are less than 10 in count  */
+                                       if (!g_partial_body_bulk_dwd_queue_empty) {
+                                               partial_body_thd_event.event_type = 0;
+                                               partial_body_thd_event.account_id = g_partial_body_bulk_dwd_que[0].account_id;
+                                               partial_body_thd_event.mailbox_id = g_partial_body_bulk_dwd_que[0].mailbox_id;
+                                               partial_body_thd_event.mailbox_name = EM_SAFE_STRDUP(g_partial_body_bulk_dwd_que[0].mailbox_name);
+
+                                               if (false == emcore_mail_partial_body_download(&partial_body_thd_event, &err))
+                                                       EM_DEBUG_EXCEPTION("emcore_mail_partial_body_download from event_data queue failed [%d]", err);
+
+                                               emcore_pb_thd_set_local_activity_continue(true);
+                                       }
+
+                                       if (true == emcore_pb_thd_can_local_activity_continue()) {
+                                               /*Check for local Activities */
+                                               int is_local_activity_event_inserted = false;
+
+                                               if (false == emcore_partial_body_thd_local_activity_sync(&is_local_activity_event_inserted, &err)) {
+                                                       EM_DEBUG_EXCEPTION("emcore_partial_body_thd_local_activity_sync failed [%d]", err);
+                                               }
+                                               else {
+                                                       if (true == is_local_activity_event_inserted) {
+                                                               emcore_pb_thd_set_local_activity_continue(false);
+
+                                                               emcore_clear_session(session);
+                                                               continue;
+                                                       }
+                                               }
+                                       }
+
+                                       EM_DEBUG_LOG(" Partial Body Thread is going to sleep");
+
+                                       emcore_set_pbd_thd_state(false);
+
+                                       ENTER_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+                                       SLEEP_CONDITION_VARIABLE(_partial_body_thd_cond, _partial_body_thd_event_queue_lock);
+                                       LEAVE_CRITICAL_SECTION(_partial_body_thd_event_queue_lock);
+
+                                       EM_DEBUG_LOG(" Partial Body Thread wakes up ");
+
+                                       emcore_set_pbd_thd_state(true);
+                               }
+
+                       }
+                       else {
+                               EM_DEBUG_LOG(" Event Received from Partial Body Event Queue ");
+
+                               /* Since all events are network operations dnet init and sleep control is
+                               done before entering switch block*/
+
+                               emdevice_set_dimming_on_off(false, NULL);
+
+                               if (!emnetwork_check_network_status( &err))  {
+                                       EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);;
+                               }
+                               else {
+                                       /*  Process events  */
+                                       EM_DEBUG_LOG("partial_body_thd_event.account_id[%d]", partial_body_thd_event.account_id);
+
+                                       switch (partial_body_thd_event.event_type) {
+                                               case EMAIL_EVENT_BULK_PARTIAL_BODY_DOWNLOAD:  {
+                                                       if (false == emcore_mail_partial_body_download(&partial_body_thd_event, &err)) {
+                                                               EM_DEBUG_EXCEPTION("emcore_mail_partial_body_download from event_data queue failed [%d]", err);
+                                                       }
+                                                       break;
+                                               }
+                                               case EMAIL_EVENT_LOCAL_ACTIVITY_SYNC_BULK_PBD:  {
+                                                       partial_body_thd_event.event_type = 0;
+
+                                                       /* Both the checks below make sure that before starting local activity there is no new/pending event_data in
+                                                       *   g_partial_body_thd_event_que and g_partial_body_bulk_dwd_que */
+                                                       if (false == emcore_is_partial_body_thd_que_empty())
+                                                               break;
+                                                       if (!g_partial_body_bulk_dwd_queue_empty)
+                                                               break;
+
+                                                       if (false == emcore_mail_partial_body_download(&partial_body_thd_event, &err))
+                                                               EM_DEBUG_EXCEPTION("emcore_mail_partial_body_download from activity table failed [%d]", err);
+                                                       break;
+                                               }
+                                               default:
+                                                       EM_DEBUG_EXCEPTION(" Warning :  Default case entered. This should not happen ");
+                                                       break;
+                                       }
+                               }
+
+                               if (false == emcore_free_partial_body_thd_event(&partial_body_thd_event, &err))
+                                       EM_DEBUG_EXCEPTION("emcore_free_partial_body_thd_event_cell failed [%d]", err);
+
+                               emdevice_set_dimming_on_off(true, NULL);
+                      }
+
+                      emcore_clear_session(session);
+              }
+       }
+
+       /* If something is added to end thread in future for any case then if thread is holding any resources
+       define a function emcore_partial_body_thd_loop_stop to release resources and call it
+       here to end thread */
+       return SUCCESS;
+}
+
+INTERNAL_FUNC int emcore_start_thread_for_downloading_partial_body(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int i = 0, thread_error = -1;
+
+       /* Clear Partial Body Event Queue*/
+       memset(&g_partial_body_thd_event_que, 0x00, sizeof(g_partial_body_thd_event_que));
+
+       for (i = 0; i < TOTAL_PARTIAL_BODY_EVENTS; ++i) {
+               g_partial_body_thd_event_que[i].mailbox_name = NULL;
+        g_partial_body_thd_event_que[i].mailbox_id = 0;
+    }
+
+       if (g_partial_body_thd)  {
+               EM_DEBUG_EXCEPTION("partial body thread is already running...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+
+               return true;
+       }
+
+       g_partial_body_thd_next_event_idx = 0;
+       g_partial_body_thd_loop = 1;
+       g_partial_body_thd_queue_empty = true;
+       g_partial_body_thd_queue_full = false;
+
+       INITIALIZE_CONDITION_VARIABLE(_partial_body_thd_cond);
+
+       /* create thread */
+       /* THREAD_CREATE_JOINABLE(g_partial_body_thd, partial_body_download_thread, thread_error); */
+       THREAD_CREATE(g_partial_body_thd, partial_body_download_thread, NULL, thread_error);
+
+       if (thread_error != 0) {
+               EM_DEBUG_EXCEPTION("cannot make thread...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               return FAILURE;
+       }
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+       return false;
+
+}
+
+/*Function to flush the bulk partial body download queue [santosh.br@samsung.com]*/
+static int emcore_partial_body_bulk_flush(int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+       MAILSTREAM *stream = NULL;
+       void *tmp_stream = NULL;
+
+       if (!emcore_connect_to_remote_mailbox(g_partial_body_bulk_dwd_que[0].account_id, g_partial_body_bulk_dwd_que[0].mailbox_id, (void **)&tmp_stream, &error) || (NULL == tmp_stream)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", error);
+               goto FINISH_OFF;
+       }
+       stream = (MAILSTREAM *)tmp_stream;
+
+       /*  Call bulk download here */
+       if (false == emcore_download_bulk_partial_mail_body(stream, g_partial_body_bulk_dwd_que, g_partial_body_bulk_dwd_next_event_idx, &error)) {
+               EM_DEBUG_EXCEPTION(" emcore_download_bulk_partial_mail_body failed.. [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+FINISH_OFF:
+
+       emcore_close_mailbox(0, stream);
+       stream = NULL;
+
+       g_partial_body_bulk_dwd_next_event_idx = 0;
+       g_partial_body_bulk_dwd_queue_empty = true;
+
+       if (false == emcore_clear_bulk_pbd_que(&error))
+               EM_DEBUG_EXCEPTION("emcore_clear_bulk_pbd_que failed [%d]", error);
+
+       if (NULL != error_code)
+               *error_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+/* Function to pass UID list and Data for bulk partial body download [santosh.br@samsung.com]/[h.gahlaut@samsung.com] */
+INTERNAL_FUNC int emcore_mail_partial_body_download(email_event_partial_body_thd *pbd_event, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error = EMAIL_ERROR_NONE;
+       int num_activity = 0;
+       int ret = false;
+       int count = 0;
+       int i = 0, m = 0;
+       MAILSTREAM *stream = NULL;
+       void *tmp_stream = NULL;
+       email_event_partial_body_thd *activity_data_list = NULL;
+       int *mailbox_list = NULL;
+
+       if (NULL == pbd_event)
+    {
+           EM_DEBUG_EXCEPTION("Invalid Parameter pbd_event [%p] ", pbd_event);
+
+           error = EMAIL_ERROR_INVALID_PARAM;
+           goto FINISH_OFF;
+    }
+
+       /*Check if the event_data is to flush the event_data que array */
+       if (EMAIL_EVENT_BULK_PARTIAL_BODY_DOWNLOAD == pbd_event->event_type) {
+               EM_DEBUG_LOG("pbd_event->event_type is EMAIL_EVENT_BULK_PARTIAL_BODY_DOWNLOAD");
+               /*Check if the mailbox name and account id for this event_data is same as the mailbox name and account id for earlier events saved in download que array
+               then append this event_data also to download que array */
+               if ((0 != g_partial_body_bulk_dwd_que[0].mailbox_id) && g_partial_body_bulk_dwd_que[0].mailbox_id == pbd_event->mailbox_id && \
+                       (g_partial_body_bulk_dwd_que[0].account_id == pbd_event->account_id)) {
+                       EM_DEBUG_LOG("Event is for the same mailbox and same account as the already present events in download que");
+                       EM_DEBUG_LOG("Check if the download que reached its limit. If yes then first flush the que.");
+                       if (g_partial_body_bulk_dwd_next_event_idx == BULK_PARTIAL_BODY_DOWNLOAD_COUNT) {
+                               if (false == emcore_partial_body_bulk_flush(&error)) {
+                                       EM_DEBUG_EXCEPTION("Partial Body thread emcore_partial_body_bulk_flush failed - %d", error);
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+               else  {
+                       EM_DEBUG_LOG("Event is not for the same mailbox and same account as the already present events in download que");
+                       EM_DEBUG_LOG("Flush the current que if not empty");
+                       EM_DEBUG_LOG("g_partial_body_bulk_dwd_queue_empty [%d]", g_partial_body_bulk_dwd_queue_empty);
+                       if (!g_partial_body_bulk_dwd_queue_empty) {
+                               if (false == emcore_partial_body_bulk_flush(&error)) {
+                                       EM_DEBUG_EXCEPTION("Partial Body thread emcore_partial_body_bulk_flush failed - %d", error);
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+               /*Add the event_data to the download que array */
+               if (false == emcore_copy_partial_body_thd_event(pbd_event, g_partial_body_bulk_dwd_que+(g_partial_body_bulk_dwd_next_event_idx), &error))
+                       EM_DEBUG_EXCEPTION("\t Partial Body thread emcore_copy_partial_body_thd_event failed - %d", error);
+               else {
+                       g_partial_body_bulk_dwd_queue_empty = false;
+                       g_partial_body_bulk_dwd_next_event_idx++;
+                       EM_DEBUG_LOG("g_partial_body_bulk_dwd_next_event_idx [%d]", g_partial_body_bulk_dwd_next_event_idx);
+               }
+       }
+       else if (pbd_event->activity_type) {
+               int *account_list = NULL;
+               int account_count = 0;
+
+               EM_DEBUG_LOG("Event is coming from local activity.");
+               /* Get all the accounts for which local activities are pending */
+               if (false == emstorage_get_pbd_account_list(&account_list, &account_count, false, &error)) {
+                               EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_list failed.. [%d]", error);
+                               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+                               goto FINISH_OFF;
+               }
+
+               for (m = 0; m < account_count; ++m) {
+                       /* Get the mailbox list for the account to start bulk partial body fetch for mails in each mailbox of accounts one by one*/
+                       if (false == emstorage_get_pbd_mailbox_list(account_list[m], &mailbox_list, &count, false, &error)) {
+                                       EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_list failed.. [%d]", error);
+                                       error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+                                       goto FINISH_OFF;
+                       }
+
+                       for (i = 0; i < count; i++) {
+                               int k = 0;
+                               int activity_count = 0;
+
+                               if (!emcore_connect_to_remote_mailbox(account_list[m], mailbox_list[i], (void **)&tmp_stream, &error))  {
+                                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", error);
+                                       stream = NULL;
+                                       goto FINISH_OFF;
+                               }
+
+                               stream = (MAILSTREAM *)tmp_stream;
+
+                               if (false == emstorage_get_mailbox_pbd_activity_count(account_list[m], mailbox_list[i], &activity_count, false, &error)) {
+                                       EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_pbd_activity_count failed.. [%d]", error);
+                                       continue;
+                               }
+
+                               if (activity_count > 0) {
+                                       int temp_error = EMAIL_ERROR_NONE;
+                                       int j = 0;
+                                       int iter = 0;
+                                       int remainder = 0;
+                                       int num = BULK_PARTIAL_BODY_DOWNLOAD_COUNT;
+                                       int index = 0;
+
+                                       if (false == emstorage_get_pbd_activity_data(account_list[j], mailbox_list[i], &activity_data_list, &num_activity,  false, &error))
+                                               EM_DEBUG_EXCEPTION(" emstorage_get_pbd_activity_data failed.. [%d]", error);
+
+                                       if (NULL == activity_data_list) {
+                                               EM_DEBUG_EXCEPTION(" activity_data_list is null..");
+                                               continue;
+                                       }
+
+                                       remainder = num_activity%BULK_PARTIAL_BODY_DOWNLOAD_COUNT;
+                                       iter = num_activity/BULK_PARTIAL_BODY_DOWNLOAD_COUNT + ((num_activity%BULK_PARTIAL_BODY_DOWNLOAD_COUNT) ? 1  :  0);
+
+                                       for (j = 0; j < iter; j++) {
+                                               if ((iter == (j+1)) && (remainder != 0))
+                                                       num = remainder;
+
+                                               /*Call bulk download here */
+                                               if (false == emcore_download_bulk_partial_mail_body(stream, activity_data_list+index, num, &error)) {
+                                                       EM_DEBUG_EXCEPTION(" emcore_download_bulk_partial_mail_body failed.. [%d]", error);
+                                                       temp_error = EMAIL_ERROR_NO_RESPONSE;
+                                               }
+
+                                               for (k = 0; k < num; k++) {
+                                                       if (activity_data_list[index + k].activity_type)
+                                                               emcore_free_partial_body_thd_event(activity_data_list + index + k, &error);
+                                                       else
+                                                               break;
+                                               }
+                                               index += num;
+
+                                               if (false == emcore_is_partial_body_thd_que_empty()) {
+                                                       ret = true;
+                                                       goto FINISH_OFF;                /* Stop Local Activity Sync */
+                                               }
+                                               if (EMAIL_ERROR_NO_RESPONSE == temp_error) {
+                                                       temp_error = EMAIL_ERROR_NONE;
+                                                       break;
+                                               }
+                                       }
+                               }
+                       }
+                       emcore_close_mailbox(0, stream);
+                       stream = NULL;
+                       tmp_stream = NULL;
+               }
+
+               /* After completing one cycle of local activity sync ,
+               local activity continue variable should be set to false. */
+
+               emcore_pb_thd_set_local_activity_continue(false);
+       }
+       else /* Event-type is 0 which means Event is to flush the que when no more events are present in g_partial_body_thd_event_que */ {
+               /*Check if events have arrived in g_partial_body_thd_event_que */
+               if (false == emcore_is_partial_body_thd_que_empty()) {
+                       EM_DEBUG_LOG("emcore_is_partial_body_thd_que_empty retured true");
+                       ret = true;
+                       goto FINISH_OFF;                /* Stop Local Activity Sync */
+               }
+               if (false == emcore_partial_body_bulk_flush(&error)) {
+                       EM_DEBUG_EXCEPTION("\t Partial Body thread emcore_partial_body_bulk_flush failed - %d", error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(mailbox_list);
+
+       if (activity_data_list) {
+               for (i = 0; i < num_activity; i++) {
+                       if (activity_data_list[i].activity_type)
+                               emcore_free_partial_body_thd_event(activity_data_list + i, &error);
+                       else
+                               break;
+               }
+       }
+
+       emcore_close_mailbox(0, stream);
+       stream = NULL;
+
+       if (NULL != error_code)
+               *error_code = error;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+#endif /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
diff --git a/email-core/email-core-global.c b/email-core/email-core-global.c
new file mode 100755 (executable)
index 0000000..a65d04c
--- /dev/null
@@ -0,0 +1,162 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File :  email-core-global.c
+ * Desc :  Mail Engine Global
+ *
+ * Auth :  Kyuho Jo 
+ *
+ * History : 
+ *    2010.08.25  :  created
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "email-core-global.h"
+#include "email-debug-log.h"
+#include "email-types.h"
+#include "email-utilities.h"
+#include "email-core-account.h"
+
+static email_account_list_t *g_unvalidated_account_list = NULL;
+static pthread_mutex_t _unvalidated_account_lock = PTHREAD_MUTEX_INITIALIZER;
+
+extern int pthread_mutexattr_settype (pthread_mutexattr_t *__attr, int __kind) __THROW __nonnull ((1));
+
+INTERNAL_FUNC int emcore_get_account_from_unvalidated_account_list(int input_unvalidated_account_id, email_account_t **oupput_account)
+{
+       EM_DEBUG_FUNC_BEGIN("input_unvalidated_account_id[%d], oupput_account[%p]", input_unvalidated_account_id, oupput_account);
+       email_account_list_t *account_node = NULL;
+       int err = EMAIL_ERROR_NONE;
+
+       if(oupput_account == NULL) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               goto FINISH_OFF;
+       }
+
+       *oupput_account = NULL;
+
+       ENTER_CRITICAL_SECTION(_unvalidated_account_lock);
+       account_node = g_unvalidated_account_list;
+       while(account_node) {
+               if(account_node->account->account_id == input_unvalidated_account_id) {
+                       emcore_duplicate_account(account_node->account, oupput_account, NULL);
+                       break;
+               }
+               account_node = account_node->next;
+       }
+       LEAVE_CRITICAL_SECTION(_unvalidated_account_lock);
+
+       if(*oupput_account == NULL)
+               err = EMAIL_ERROR_DATA_NOT_FOUND;
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_add_account_to_unvalidated_account_list(email_account_t *input_new_account)
+{
+       EM_DEBUG_FUNC_BEGIN("input_new_account[%p]", input_new_account);
+       email_account_list_t **account_node = NULL;
+       email_account_list_t *new_account_node = NULL;
+       int new_account_id = -1;
+       int err = EMAIL_ERROR_NONE;
+
+       if(input_new_account == NULL) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               goto FINISH_OFF;
+       }
+
+       new_account_node = em_malloc(sizeof(email_account_list_t));
+
+       if(new_account_node == NULL) {
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               goto FINISH_OFF;
+       }
+
+       new_account_node->account = input_new_account;
+       new_account_node->next = NULL;
+
+       ENTER_CRITICAL_SECTION(_unvalidated_account_lock);
+       account_node = &g_unvalidated_account_list;
+
+       while(*account_node) {
+               if((*account_node)->account->account_id < new_account_id) {
+                       new_account_id = (*account_node)->account->account_id - 1;
+               }
+               account_node = &((*account_node)->next);
+       }
+
+       input_new_account->account_id = new_account_id;
+       *account_node = new_account_node;
+       LEAVE_CRITICAL_SECTION(_unvalidated_account_lock);
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_delete_account_from_unvalidated_account_list(int input_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id[%d]", input_account_id);
+       email_account_list_t *account_node = NULL, *prev_node = NULL;
+       email_account_t *found_account = NULL;
+       int err = EMAIL_ERROR_NONE;
+
+       ENTER_CRITICAL_SECTION(_unvalidated_account_lock);
+       account_node = g_unvalidated_account_list;
+
+       while(account_node) {
+               if(account_node->account->account_id == input_account_id) {
+                       found_account = account_node->account;
+                       if(prev_node)
+                               prev_node->next = account_node->next;
+                       else
+                               g_unvalidated_account_list = account_node->next;
+                       break;
+               }
+               prev_node = account_node;
+               account_node = account_node->next;
+       }
+
+       if(found_account) {
+               emcore_free_account(found_account);
+               EM_SAFE_FREE(found_account);
+               EM_SAFE_FREE(account_node);
+       } else {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_DATA_NOT_FOUND");
+               err = EMAIL_ERROR_DATA_NOT_FOUND;
+       }
+       LEAVE_CRITICAL_SECTION(_unvalidated_account_lock);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+
diff --git a/email-core/email-core-imap-idle.c b/email-core/email-core-imap-idle.c
new file mode 100755 (executable)
index 0000000..441a5ad
--- /dev/null
@@ -0,0 +1,522 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+/**
+ *
+ * This file contains functionality related to IMAP IDLE.
+ * to interact with email-service.
+ * @file               em_core-imap-idle.c
+ * @author     
+ * @version    0.1
+ * @brief              This file contains functionality to provide IMAP IDLE support in email-service. 
+ */
+
+#include <email-internal-types.h>
+
+#ifdef __FEATURE_IMAP_IDLE__
+#include <glib.h>
+#include <openssl/ssl.h>
+#include "c-client.h"
+#include "lnx_inc.h"
+#include "email-core-imap-idle.h"
+#include "email-debug-log.h"
+#include "email-storage.h" 
+#include "email-network.h"
+#include "email-core-utils.h"
+#include "email-core-mailbox.h"
+#include "email-core-event.h"
+#include "email-core-account.h"
+
+
+/*Definitions copied temporarily from ssl_unix.c */
+#define SSLBUFLEN 8192
+
+typedef struct ssl_stream {
+  TCPSTREAM *tcpstream; /* TCP stream */
+  SSL_CTX *context;     /* SSL context */
+  SSL *con;             /* SSL connection */
+  int ictr;             /* input counter */
+  char *iptr;           /* input pointer */
+  char ibuf[SSLBUFLEN]; /* input buffer */
+} SSLSTREAM;
+/*Definitions copied temporarily from ssl_unix.c - end*/
+
+thread_t imap_idle_thread;
+int g_imap_idle_thread_alive = 0;
+
+void* emcore_imap_idle_run(void* thread_user_data);
+static int emcore_imap_idle_parse_response_stream(email_mailbox_t *mailbox, int *err_code);
+static int emcore_imap_idle_connect_and_idle_on_mailbox(email_mailbox_t *mailbox, int *err_code);
+
+int emcore_create_imap_idle_thread(int account_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], err_code [%p]", account_id, err_code);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int thread_error;
+
+       g_imap_idle_thread_alive = 1;
+       THREAD_CREATE(imap_idle_thread, emcore_imap_idle_run, NULL, thread_error);
+
+       if (thread_error != 0) {
+               EM_DEBUG_EXCEPTION("cannot make IMAP IDLE thread...");
+               err = EMAIL_ERROR_UNKNOWN;
+               g_imap_idle_thread_alive = 0;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/*
+Need to identify various scenarios where thread needs to be killed
+1. After the timer set to 10 min expires.
+2. When No SIM, thread is created and emnetwork_check_network_status() fails.
+*/
+int emcore_kill_imap_idle_thread(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("err_code [%p]", err_code);
+       int ret = true;
+       int err = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_LOG("killing thread");
+
+       /* kill the thread */
+       EM_DEBUG_LOG("Before g_thread_exit");
+       g_imap_idle_thread_alive = 0;
+       EM_DEBUG_LOG("After g_thread_exit");
+
+       EM_DEBUG_LOG("Making imap idle NULL");
+       imap_idle_thread = 0;
+       EM_DEBUG_LOG("killed IMAP IDLE");
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int emcore_imap_idle_loop_start(email_mailbox_t *mailbox_list,  int num, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_list[%p], num[%d]", mailbox_list, num);
+       fd_set readfds;
+       int maxfd = 0;
+       int err = EMAIL_ERROR_NONE;
+       int counter = 0;
+       int select_result = 0;
+       int ret = false;
+       email_mailbox_t *temp = NULL;
+       struct timeval timeout;
+
+       EM_DEBUG_EXCEPTION(">>>>>>> emcore_imap_idle_loop_start start ");
+       if (!mailbox_list || !num) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* set timeout value to 10min */
+       timeout.tv_sec = 10 * 60;
+       timeout.tv_usec = 0;
+
+       /* IMAP IDLE LOOP */
+       while (1){
+               EM_DEBUG_EXCEPTION(">>>>>>>>>>>IDLING>>>>>>>>>>>>");
+               FD_ZERO(&readfds);
+               temp = mailbox_list;
+               for (counter = 0; counter < num; counter++) {
+                       FD_SET(temp->hold_connection, &readfds);
+                       if (temp->hold_connection > maxfd)
+                               maxfd = temp->hold_connection; 
+                       temp = temp->next;
+               }
+               maxfd++;
+               temp = mailbox_list;
+               
+               select_result = select(maxfd, &readfds, NULL, NULL, &timeout);
+
+               if (select_result > 0) /* Data coming on some socket */ {
+                       EM_DEBUG_EXCEPTION(">>>> Data Coming from Socket ");
+                       for (counter = 0; counter < num; counter++) {
+                               if (temp && FD_ISSET(temp->hold_connection, &readfds)) {
+                                       if (!emcore_imap_idle_parse_response_stream(temp, &err)) {
+                                               EM_DEBUG_EXCEPTION(">>>> emcore_imap_idle_loop_start 6 ");
+                                               emcore_close_mailbox(temp->account_id, temp->mail_stream);
+                                               EM_DEBUG_EXCEPTION(">>>> emcore_imap_idle_loop_start 7 ");
+                                               goto FINISH_OFF;
+                                       }
+                                       break; /* break for now - check if it is possible to get data on two sockets - shasikala.p */
+                               }
+                               temp = temp->next;
+                       }
+               }
+
+               else if (select_result == 0) /* Timeout occurred */ {
+                       EM_DEBUG_EXCEPTION(">>>> emcore_imap_idle_loop_start 8 ");
+                       IMAPLOCAL *imap_local = NULL;
+                       char cmd[128], tag[32];
+                       char *p = NULL;
+                       /* send DONE Command */
+                       /* free all data here */
+                       for (counter = 0; counter < num; counter++) {
+                               EM_DEBUG_LOG(">>>> emcore_imap_idle_loop_start 9 ");
+                               if (temp && temp->mail_stream) {
+                                       imap_local = ((MAILSTREAM *)temp->mail_stream)->local;
+
+                                       sprintf(tag, "%08lx", 0xffffffff & (((MAILSTREAM *)temp->mail_stream)->gensym++));
+                                       sprintf(cmd, "%s DONE\015\012", tag);
+
+                                       if (!imap_local->netstream || !net_sout(imap_local->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+                                               EM_DEBUG_EXCEPTION("network error - failed to DONE on Mailbox - %s ", temp->name);
+                                       }
+                                       else {
+                                               while (imap_local->netstream) {
+                                               p = net_getline(imap_local->netstream);
+                                               EM_DEBUG_EXCEPTION("p =[%s]", p);
+                                                       emcore_close_mailbox(temp->account_id, temp->mail_stream);
+                                                       break;
+                                           }
+                                       }
+                               }
+                               temp = temp->next;
+                       }
+                       
+                       
+                       /* kill idle thread */
+                       emcore_kill_imap_idle_thread(&err);
+                       break;
+               }
+
+               else {
+                       /*
+                       might happen that a socket descriptor passed to select got closed
+                       check which got closed and make hold_connection 0
+                       */
+                       EM_DEBUG_EXCEPTION(">>>>>> socket descriptor error :  No Data ");
+                       break;
+               }
+
+               select_result = 0;
+       }
+
+       ret = true;
+
+       EM_DEBUG_LOG(">>>> emcore_imap_idle_loop_start 17  ");
+
+FINISH_OFF: 
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+void* emcore_imap_idle_run(void* thread_user_data)
+{
+       EM_DEBUG_FUNC_BEGIN("thread_user_data [%p]", thread_user_data);
+       char              *mailbox_list[3];
+       int                mailbox_num = 0;
+       int                err = EMAIL_ERROR_NONE;
+       int                flag = true;
+       int                num = 0;
+       int                counter = 0;
+       int                accountID = (int)thread_user_data;
+       email_mailbox_t     *mail_box_list = NULL;
+       email_mailbox_t     *curr_mailbox = NULL;
+       email_mailbox_t     *prev_mailbox = NULL;
+       emstorage_mailbox_tbl_t *local_mailbox = NULL;
+       email_session_t     *session = NULL;
+
+       if ( !emnetwork_check_network_status(&err)) {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       /* Connect to DB */
+       if (!emstorage_open(&err)) {
+               EM_DEBUG_EXCEPTION("emstorage_open falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_empty_session(&session))
+               EM_DEBUG_EXCEPTION("emcore_get_empty_session failed...");
+
+       /* get the list of mailbox name on which IDLE notifications are required. */
+       /* currently all INBOXES of all accounts need to be notified */
+       /* Dependent on GetMyIdentities for account names */
+
+       /* For testing - mailbox_num and mailbox_list are hardcoded here */
+       mailbox_num     = 1;
+       mailbox_list[0] = strdup("INBOX");
+
+       /* make a list of mailboxes IDLING */
+       for (counter = 0; counter < mailbox_num; counter++){
+               EM_DEBUG_EXCEPTION(">>>> emcore_imap_idle_run 4 ");
+               if (!emstorage_get_mailbox_by_name(accountID, 0,  mailbox_list[counter], &local_mailbox, true, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_name failed [%d]", err);
+               }
+               else {
+                       curr_mailbox             = em_malloc(sizeof(email_mailbox_t));
+                       curr_mailbox->account_id = local_mailbox->account_id;
+                       curr_mailbox->mailbox_name       = EM_SAFE_STRDUP(local_mailbox->mailbox_name);
+                       curr_mailbox->local      = local_mailbox->local_yn;
+                       if (!emcore_imap_idle_connect_and_idle_on_mailbox(curr_mailbox, &err)) {
+                               EM_DEBUG_EXCEPTION("emcore_imap_idle_connect_and_idle_on_mailbox failed [%d]", err);
+                               emcore_free_mailbox(curr_mailbox);
+                               EM_SAFE_FREE(curr_mailbox);
+                       }
+                       else {
+                               if (flag) {
+                                       mail_box_list = curr_mailbox;
+                                       prev_mailbox = curr_mailbox;
+                                       flag = false;
+                                       num++;
+                               }
+                               else {
+                                       prev_mailbox->next = curr_mailbox;
+                                       prev_mailbox = curr_mailbox;
+                                       num++;
+                               }
+                       }
+               }
+               if (local_mailbox != NULL)
+                       emstorage_free_mailbox(&local_mailbox, 1, NULL);
+       }
+
+       emcore_clear_session(session);
+       emcore_imap_idle_loop_start(mail_box_list, num, NULL);
+
+FINISH_OFF:
+
+       if (!emstorage_close(&err)) {
+               EM_DEBUG_EXCEPTION("emstorage_close falied [%d]", err);
+       }
+
+       EM_DEBUG_FUNC_END();
+       return NULL;
+}
+
+int emcore_imap_idle_insert_sync_event(email_mailbox_t *mailbox, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int handle;
+       
+       if (!mailbox || mailbox->account_id <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       email_event_t event_data = { 0 };
+
+       event_data.type               = EMAIL_EVENT_SYNC_HEADER;
+       event_data.event_param_data_1 = mailbox ? EM_SAFE_STRDUP(mailbox->mailbox_name)  :  NULL;
+       event_data.event_param_data_3 = NULL;
+       event_data.account_id         = mailbox->account_id;
+                       
+       if (!emcore_insert_event(&event_data, &handle, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/* connects to given mailbox. send idle and returns socket id */
+static int emcore_imap_idle_connect_and_idle_on_mailbox(email_mailbox_t *mailbox, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox [%p], err_code [%p]", mailbox, err_code);
+       void          *mail_stream = NULL;
+       char           cmd[128] = { 0, };
+       char           tag[32] = { 0, };
+       char          *p = NULL;
+       int            socket_id = 0;
+       int            ret = 0;
+       int            err = EMAIL_ERROR_NONE;
+       email_account_t *ref_account = NULL;
+       IMAPLOCAL     *imap_local = NULL;
+       NETSTREAM     *net_stream = NULL;
+       TCPSTREAM     *tcp_stream = NULL;
+
+       /* NULL param check */
+       if (!mailbox) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox->account_id);
+       if (!ref_account) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed. account_id[%d]", mailbox->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /* Open connection to mailbox */
+       if (!emcore_connect_to_remote_mailbox(mailbox->account_id, mailbox->mailbox_name, (void **)&mail_stream, &err) || !mail_stream) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       imap_local = ((MAILSTREAM *)mail_stream)->local;
+       net_stream = imap_local->netstream;
+       
+       /* check if ssl option is enabled on this account - shasikala.p */
+
+       if (ref_account->incoming_server_secure_connection){
+               SSLSTREAM *ssl_stream = net_stream->stream;
+               tcp_stream = ssl_stream->tcpstream;
+       }
+       else
+               tcp_stream = net_stream->stream;
+
+       /* Get Socket ID */
+       socket_id = ((TCPSTREAM *)tcp_stream)->tcpsi;
+
+       sprintf(tag, "%08lx", 0xffffffff & (((MAILSTREAM *)mail_stream)->gensym++));
+       sprintf(cmd, "%s IDLE\015\012", tag);
+
+       /* Send IDLE command */
+       if (!imap_local->netstream || !net_sout(imap_local->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+               EM_DEBUG_EXCEPTION("network error - failed to IDLE on Mailbox - %s ", mailbox->mailbox_name);
+               err = EMAIL_ERROR_IMAP4_IDLE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Get the response for IDLE command */
+       while (imap_local->netstream){
+               p = net_getline(imap_local->netstream);
+               EM_DEBUG_LOG("p =[%s]", p);
+               if (!strncmp(p, "+", 1)) {
+                       ret = 1;
+                       break;
+               }
+               else if (!strncmp(p, "*", 1)) {
+                       EM_SAFE_FREE(p);
+                       continue;
+               }
+               else {
+                       ret = 0;
+                       break;
+               }
+    }
+       EM_SAFE_FREE(p);
+
+FINISH_OFF: 
+       
+       if (ret) {
+               /* IMAP IDLE - SUCCESS */
+               mailbox->mail_stream     = mail_stream;
+               mailbox->hold_connection = socket_id; /* holds connection continuously on the given socket_id */
+       }
+       else if (mail_stream)
+               emcore_close_mailbox(mailbox->account_id, mail_stream);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+static int emcore_imap_idle_parse_response_stream(email_mailbox_t *mailbox, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox [%p], err_code [%p]", mailbox, err_code);
+       int err = EMAIL_ERROR_NONE;
+       char *p = NULL;
+       int ret = false;
+       IMAPLOCAL *imap_local = NULL;
+       
+       if (!mailbox || !mailbox->mail_stream) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       imap_local = ((MAILSTREAM *)mailbox->mail_stream)->local;
+
+       if (!imap_local){
+               EM_DEBUG_EXCEPTION("imap_local is NULL");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       while (imap_local->netstream){
+               p = net_getline(imap_local->netstream);
+               if (p && !strncmp(p, "*", 1)) {
+                       EM_DEBUG_LOG("p is [%s]", p);
+                       if (p+1 && p+2 && p+3 && p+4 && !strncmp(p+2, "BYE", 3)) {
+                               EM_DEBUG_LOG("BYE connection from server");
+                               EM_SAFE_FREE(p);
+                               goto FINISH_OFF;
+                       }
+                       else  { 
+                               if (!emcore_imap_idle_insert_sync_event(mailbox, &err))
+                                       EM_DEBUG_EXCEPTION("Syncing mailbox %s failed with err_code [%d]", mailbox->mailbox_name, err);
+                               EM_SAFE_FREE(p);        
+                               break;
+                       }
+               }
+               else if (p && (!strncmp(p, "+", 1))) {
+                       /* Bad response from server */
+                       EM_DEBUG_LOG("p is [%s]", p);
+                       EM_SAFE_FREE(p);
+                       break;
+               }
+               else {
+                       EM_DEBUG_LOG("In else part");
+                       break;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+#endif /*  __FEATURE_IMAP_IDLE__ */
diff --git a/email-core/email-core-imap-mailbox.c b/email-core/email-core-imap-mailbox.c
new file mode 100755 (executable)
index 0000000..62f37c3
--- /dev/null
@@ -0,0 +1,1136 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File :  email-core-imap_folder.c
+ * Desc :  Mail IMAP mailbox
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.01  :  created
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <vconf.h>
+#include "email-core-global.h"
+#include "email-core-utils.h"
+#include "c-client.h"
+#include "email-storage.h"
+#include "email-utilities.h"
+#include "email-network.h"
+#include "email-core-event.h"
+#include "email-core-mailbox.h"
+#include "email-core-imap-mailbox.h"
+#include "email-core-mailbox-sync.h"
+#include "email-core-account.h" 
+#include "email-core-signal.h"
+#include "lnx_inc.h"
+
+#include "email-debug-log.h"
+
+INTERNAL_FUNC int emcore_get_default_mail_slot_count(int input_account_id, int *output_count)
+{      
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] output_count[%p]", input_account_id, output_count);
+
+       int err = EMAIL_ERROR_NONE;
+       int default_mail_slot_count = 25;
+       email_account_t *account_ref = NULL;
+
+       if (output_count == NULL) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       account_ref = emcore_get_account_reference(input_account_id);
+       if (account_ref)
+               default_mail_slot_count = account_ref->default_mail_slot_size;
+
+FINISH_OFF: 
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+       
+       if (output_count)
+               *output_count = default_mail_slot_count;
+
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+
+INTERNAL_FUNC int emcore_remove_overflowed_mails(emstorage_mailbox_tbl_t *intput_mailbox_tbl, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("intput_mailbox_tbl[%p], err_code[%p]", intput_mailbox_tbl, err_code);
+
+       int ret = false; 
+       int *mail_id_list = NULL, mail_id_list_count = 0;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t *account_ref = NULL;
+       
+       if (!intput_mailbox_tbl || intput_mailbox_tbl->account_id < 1) {
+               if (intput_mailbox_tbl)
+               EM_DEBUG_EXCEPTION("Invalid Parameter. intput_mailbox_tbl->account_id [%d]", intput_mailbox_tbl->account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       account_ref = emcore_get_account_reference(intput_mailbox_tbl->account_id);
+       if (account_ref) {
+               if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+                       EM_DEBUG_LOG("ActiveSync Account didn't support mail slot");
+                       err = EMAIL_ERROR_NOT_SUPPORTED;
+                       goto FINISH_OFF;
+               }
+       }
+       
+       if (!emstorage_get_overflowed_mail_id_list(intput_mailbox_tbl->account_id, intput_mailbox_tbl->mailbox_id, intput_mailbox_tbl->mail_slot_size, &mail_id_list, &mail_id_list_count, true, &err)) {
+               if (err == EMAIL_ERROR_MAIL_NOT_FOUND) {
+                       EM_DEBUG_LOG("There are enough slot in intput_mailbox_tbl [%s]", intput_mailbox_tbl->mailbox_name);
+                       err = EMAIL_ERROR_NONE;
+                       ret = true;
+               }
+               else
+                       EM_DEBUG_EXCEPTION("emstorage_get_overflowed_mail_id_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mail_id_list) {
+               if (!emcore_delete_mail(intput_mailbox_tbl->account_id, mail_id_list, mail_id_list_count, EMAIL_DELETE_LOCALLY, EMAIL_DELETED_BY_OVERFLOW, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_delete_mail failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       
+       ret = true;
+FINISH_OFF: 
+       EM_SAFE_FREE(mail_id_list);
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_set_mail_slot_size(int account_id, int mailbox_id, int new_slot_size, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], mailbox_id[%d], err_code[%p]", account_id, mailbox_id, err_code);
+
+       int ret = false, err = EMAIL_ERROR_NONE; 
+       int i = 0;
+       int account_count = 100;
+       int mailbox_count = 0;
+       email_account_t *account_ref = NULL;
+       emstorage_account_tbl_t *account_tbl_list = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl_list = NULL;
+
+       if (account_id > ALL_ACCOUNT) {
+               account_ref = emcore_get_account_reference(account_id);
+               if (account_ref && account_ref->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+                       EM_DEBUG_LOG("ActiveSync account didn't support mail slot");
+                       ret = true;
+                       goto FINISH_OFF;
+               }
+               else if (!account_ref) {
+                       EM_DEBUG_EXCEPTION("emcore_get_account_reference failed");
+                       goto FINISH_OFF;
+               }
+               if (mailbox_id == 0) {
+                       if ( (err = emstorage_set_field_of_accounts_with_integer_value(account_id, "default_mail_slot_size", new_slot_size, true)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emstorage_set_field_of_accounts_with_integer_value failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+       else {
+               if (mailbox_id == 0) {
+                       if ( !emstorage_get_account_list(&account_count, &account_tbl_list, false, false, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+                       for ( i = 0; i < account_count; i++) {
+                               if ( (err = emstorage_set_field_of_accounts_with_integer_value(account_tbl_list[i].account_id, "default_mail_slot_size", new_slot_size, true)) != EMAIL_ERROR_NONE) {
+                                       EM_DEBUG_EXCEPTION("emstorage_set_field_of_accounts_with_integer_value failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+       }
+
+
+       if (!emstorage_set_mail_slot_size(account_id, mailbox_id, new_slot_size, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_set_mail_slot_size failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mailbox_id) {
+               mailbox_count = 1;
+               if (new_slot_size > 0) {
+                       mailbox_tbl_list = em_malloc(sizeof(emstorage_mailbox_tbl_t) * mailbox_count);
+                       if(!mailbox_tbl_list) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               goto FINISH_OFF;
+                       }
+                       mailbox_tbl_list->account_id = account_id;
+                       mailbox_tbl_list->mailbox_id = mailbox_id;
+                       mailbox_tbl_list->mail_slot_size = new_slot_size;     
+               }
+               else   {        /*  read information from DB */
+                       if ((err = emstorage_get_mailbox_by_id(mailbox_id, &mailbox_tbl_list)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+                       
+               }
+       }
+       else {
+               if (!emstorage_get_mailbox_list(account_id, EMAIL_MAILBOX_ALL, EMAIL_MAILBOX_SORT_BY_NAME_ASC, &mailbox_count, &mailbox_tbl_list, true, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       for (i = 0; i < mailbox_count; i++) {
+               if (!emcore_remove_overflowed_mails(mailbox_tbl_list + i, &err)) {
+                       if (err == EMAIL_ERROR_MAIL_NOT_FOUND || err == EMAIL_ERROR_NOT_SUPPORTED)
+                               err = EMAIL_ERROR_NONE;
+                       else
+                               EM_DEBUG_EXCEPTION("emcore_remove_overflowed_mails failed [%d]", err);
+               }
+       }
+
+       ret = true;
+       
+FINISH_OFF: 
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
+       if (account_tbl_list)
+               emstorage_free_account(&account_tbl_list, account_count, NULL);
+
+       if (mailbox_tbl_list)
+               emstorage_free_mailbox(&mailbox_tbl_list, mailbox_count, NULL);
+
+
+       if (err_code)
+               *err_code = err;
+       return ret;
+}
+
+static int emcore_get_mailbox_connection_path(int account_id, char *mailbox_name, char **path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], mailbox_name[%s], err_code[%p]", account_id, mailbox_name, err_code);
+       email_account_t *ref_account = NULL;
+       size_t path_len = 0;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       ref_account = emcore_get_account_reference(account_id);
+       if (!ref_account)        {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed");
+               goto FINISH_OFF;
+       }
+
+       path_len = EM_SAFE_STRLEN(ref_account->incoming_server_address) +
+                       (mailbox_name ? EM_SAFE_STRLEN(mailbox_name) : 0) + 50;
+
+       *path = em_malloc(path_len);/* EM_SAFE_STRLEN(ref_account->incoming_server_address) + */
+                                                               /* (mailbox_name ? EM_SAFE_STRLEN(mailbox_name) : 0) + 20); */
+       if (!*path) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(*path, 0x00, path_len);
+
+       /* 1. server address / server type */
+       if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) {
+               SNPRINTF(*path + 1, path_len-1, "%s:%d/pop", ref_account->incoming_server_address, ref_account->incoming_server_port_number);
+       } else {
+               SNPRINTF(*path + 1, path_len-1, "%s:%d/imap", ref_account->incoming_server_address, ref_account->incoming_server_port_number);
+       }
+
+       /* 2. set tls option if security connection */
+       /*if (ref_account->incoming_server_secure_connection) strncat(*path + 1, "/tls", path_len-(EM_SAFE_STRLEN(*path)-1));*/
+       if (ref_account->incoming_server_secure_connection & 0x01) {
+               strncat(*path + 1, "/ssl", path_len-(EM_SAFE_STRLEN(*path)-1));
+       }
+       if (ref_account->incoming_server_secure_connection & 0x02)
+               strncat(*path + 1, "/tls", path_len-(EM_SAFE_STRLEN(*path)-1));
+       else
+               strncat(*path + 1, "/notls", path_len-(EM_SAFE_STRLEN(*path)-1));
+
+       /*  3. re-format mailbox name (ex:"{mai.test.com:143/imap} or {mai.test.com:143/imap/tls}"} */
+       strncat(*path + 1, "}", path_len-EM_SAFE_STRLEN(*path)-1);
+       **path = '{';
+
+       if (mailbox_name) strncat(*path, mailbox_name, path_len-EM_SAFE_STRLEN(*path)-1);
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (!ret)
+               return 0;
+
+       return 1;
+}
+
+INTERNAL_FUNC int emcore_sync_mailbox_list(int account_id, char *mailbox_name, int handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_name[%p], handle[%d], err_code[%p]", account_id, mailbox_name, handle, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int status = EMAIL_DOWNLOAD_FAIL;
+       MAILSTREAM *stream = NULL;
+       email_internal_mailbox_t *mailbox_list = NULL;
+       email_account_t *ref_account = NULL;
+       void *tmp_stream = NULL;
+       char *mbox_path = NULL;
+       char *mailbox_name_for_mailbox_type = NULL;
+       int   i = 0, count = 0, counter = 0, mailbox_type_list[EMAIL_MAILBOX_TYPE_ALL_EMAILS + 1] = {-1, -1, -1, -1, -1, -1, -1, -1};
+       
+       if (!emcore_notify_network_event(NOTI_SYNC_IMAP_MAILBOX_LIST_START, account_id, 0, handle, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_SYNC_IMAP_MAILBOX_LIST_START] Failed >>>> ");
+
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       if (!emnetwork_check_network_status(&err)) {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       ref_account = emcore_get_account_reference(account_id);
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - %d", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+       
+       /* if not imap4 mail, return */
+       if ( ref_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               EM_DEBUG_EXCEPTION("unsupported account...");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+       
+       /*  get mail server path */
+       /*  mbox_path is not used. the below func might be unnecessary */
+       if (!emcore_get_mailbox_connection_path(account_id, NULL, &mbox_path, &err) || !mbox_path)  {
+               EM_DEBUG_EXCEPTION("emcore_get_mailbox_connection_path - %d", err);
+               goto FINISH_OFF;
+       }
+       
+       
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       stream = NULL;
+       if (!emcore_connect_to_remote_mailbox(account_id, 0, (void **)&tmp_stream, &err) || !tmp_stream)  {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed - %d", err);
+               
+               if (err == EMAIL_ERROR_CONNECTION_BROKEN)
+                       err = EMAIL_ERROR_CANCELLED;
+               else
+                       err = EMAIL_ERROR_CONNECTION_FAILURE;
+               
+               status = EMAIL_DOWNLOAD_CONNECTION_FAIL;
+               goto FINISH_OFF;
+       }
+       
+       EM_SAFE_FREE(mbox_path);
+       
+       stream = (MAILSTREAM *)tmp_stream;
+       
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       
+       /*  download mailbox list */
+       if (!emcore_download_mailbox_list(stream, mailbox_name, &mailbox_list, &count, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_download_mailbox_list failed - %d", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       
+       for (i = 0; i < count; i++) {
+               if (!emcore_check_thread_status())  {
+                       EM_DEBUG_LOG("emcore_check_thread_status - cancelled");
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+               if (mailbox_list[i].mailbox_name) {
+                       EM_DEBUG_LOG("mailbox name - %s", mailbox_list[i].mailbox_name);
+                       mailbox_list[i].mail_slot_size = ref_account->default_mail_slot_size;
+
+                       if(mailbox_list[i].mailbox_type == EMAIL_MAILBOX_TYPE_NONE)
+                               emcore_bind_mailbox_type(mailbox_list + i);
+
+                       if (mailbox_list[i].mailbox_type <= EMAIL_MAILBOX_TYPE_ALL_EMAILS) {    /* if result mailbox type is duplicated,  */
+                               if (mailbox_type_list[mailbox_list[i].mailbox_type] != -1) {
+                                       EM_DEBUG_LOG("Mailbox type [%d] of [%s] is duplicated", mailbox_list[i].mailbox_type, mailbox_list[i].mailbox_name);
+                                       mailbox_list[i].mailbox_type = EMAIL_MAILBOX_TYPE_USER_DEFINED; /* ignore latest one  */
+                               }
+                               else
+                                       mailbox_type_list[mailbox_list[i].mailbox_type] = i;
+                       }
+
+                       EM_DEBUG_LOG("mailbox type [%d]", mailbox_list[i].mailbox_type);
+                       if(!emcore_set_sync_imap_mailbox(mailbox_list + i, 1, &err)) {
+                               EM_DEBUG_EXCEPTION("emcore_set_sync_imap_mailbox failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+               }
+       }
+
+
+       for (counter = EMAIL_MAILBOX_TYPE_INBOX; counter <= EMAIL_MAILBOX_TYPE_OUTBOX; counter++) {
+               /* if (!emstorage_get_mailbox_name_by_mailbox_type(account_id, counter, &mailbox_name_for_mailbox_type, false, &err))  */
+               if (mailbox_type_list[counter] == -1) {
+                       /* EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed - %d", err); */
+                       /* if (EMAIL_ERROR_MAILBOX_NOT_FOUND == err)     */
+                       /* { */
+                               emstorage_mailbox_tbl_t mailbox_tbl;
+                               
+                               memset(&mailbox_tbl, 0x00, sizeof(mailbox_tbl));
+                               
+                               mailbox_tbl.account_id = account_id;
+                               mailbox_tbl.mailbox_id = 0;
+                               mailbox_tbl.local_yn = 1; 
+                               mailbox_tbl.mailbox_type = counter;
+                               mailbox_tbl.deleted_flag =  0;
+                               mailbox_tbl.modifiable_yn = 1; 
+                               mailbox_tbl.total_mail_count_on_server = 0;
+                               mailbox_tbl.mail_slot_size = ref_account->default_mail_slot_size;
+                               
+                               switch (counter) {
+                                       case EMAIL_MAILBOX_TYPE_SENTBOX:
+                                               mailbox_tbl.mailbox_name = EMAIL_SENTBOX_NAME;
+                                               mailbox_tbl.alias = EMAIL_SENTBOX_DISPLAY_NAME;
+                                               break;
+                                               
+                                       case EMAIL_MAILBOX_TYPE_TRASH:
+                                               mailbox_tbl.mailbox_name = EMAIL_TRASH_NAME;
+                                               mailbox_tbl.alias = EMAIL_TRASH_DISPLAY_NAME;
+                                               break;
+
+                                   case EMAIL_MAILBOX_TYPE_DRAFT:
+                                               mailbox_tbl.mailbox_name = EMAIL_DRAFTBOX_NAME;
+                                               mailbox_tbl.alias = EMAIL_DRAFTBOX_DISPLAY_NAME;
+                                               break;
+                                               
+                                       case EMAIL_MAILBOX_TYPE_SPAMBOX:
+                                               mailbox_tbl.mailbox_name = EMAIL_SPAMBOX_NAME;
+                                               mailbox_tbl.alias = EMAIL_SPAMBOX_DISPLAY_NAME;
+                                               break;
+                                               
+                                       case EMAIL_MAILBOX_TYPE_OUTBOX:
+                                               mailbox_tbl.mailbox_name = EMAIL_OUTBOX_NAME;
+                                               mailbox_tbl.alias = EMAIL_OUTBOX_DISPLAY_NAME;
+                                               break;
+
+                                       default: 
+                                               mailbox_tbl.mailbox_name = EMAIL_INBOX_NAME;
+                                               mailbox_tbl.alias = EMAIL_INBOX_DISPLAY_NAME;
+                                               break;
+                               }
+
+                               if (!emstorage_add_mailbox(&mailbox_tbl, true, &err)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_add_mailbox failed - %d", err);
+                                       goto FINISH_OFF;
+                               }
+                               
+                       /* }     */
+                       /* else */
+                       /* { */
+                       /*  */
+                       /*      goto FINISH_OFF; */
+                       /* } */
+                       
+               }
+               EM_SAFE_FREE(mailbox_name_for_mailbox_type);
+       }
+
+       emstorage_mailbox_tbl_t *local_mailbox_list = NULL;
+       int select_num = 0;
+       i = 0;
+       email_mailbox_t mailbox;
+
+       if (emstorage_get_mailbox_by_modifiable_yn(account_id, 0 /* modifiable_yn */, &select_num, &local_mailbox_list, true, &err)) {
+               if (local_mailbox_list) {
+                       for (i = 0; i < select_num; i++) {
+                               EM_DEBUG_LOG(">>> MailBox needs to be Deleted[ %s ] ", local_mailbox_list[i].mailbox_name);
+                               mailbox.account_id = local_mailbox_list[i].account_id;
+                               mailbox.mailbox_name = local_mailbox_list[i].mailbox_name;
+                               mailbox.mailbox_id = local_mailbox_list[i].mailbox_id;
+                               if (!emcore_delete_mailbox_all(&mailbox, &err)) {
+                                       EM_DEBUG_EXCEPTION(" emcore_delete_all of Mailbox [%s] Failed ", mailbox.mailbox_name);
+                                       emstorage_free_mailbox(&local_mailbox_list, select_num, NULL); 
+                                       local_mailbox_list = NULL;
+                                       goto FINISH_OFF;
+                               }
+                       }
+                       emstorage_free_mailbox(&local_mailbox_list, select_num, NULL); 
+                       local_mailbox_list = NULL;
+               }
+       }
+
+       if (!emstorage_set_all_mailbox_modifiable_yn(account_id, 0, true, &err)) {
+                       EM_DEBUG_EXCEPTION(" >>>> emstorage_set_all_mailbox_modifiable_yn Failed [ %d ]", err);
+                       goto FINISH_OFF;
+       }
+       
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       
+       for (i = 0; i < count; i++)
+               mailbox_list[i].account_id = account_id;
+       
+       
+       ret = true;
+       
+FINISH_OFF: 
+
+       if (err == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_network_event(NOTI_SYNC_IMAP_MAILBOX_LIST_FINISH, account_id, 0, handle, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_SYNC_IMAP_MAILBOX_LIST_FINISH] Failed >>>> ");
+       }
+       else {
+               if (!emcore_notify_network_event(NOTI_SYNC_IMAP_MAILBOX_LIST_FAIL, account_id, 0, handle, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [ NOTI_SYNC_IMAP_MAILBOX_LIST_FAIL] Failed >>>> ");
+       }
+       EM_SAFE_FREE(mailbox_name_for_mailbox_type);
+       EM_SAFE_FREE(mbox_path);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (stream) 
+               emcore_close_mailbox(account_id, stream);
+       
+       if (mailbox_list) 
+               emcore_free_internal_mailbox(&mailbox_list, count, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int emcore_download_mailbox_list(void *mail_stream, 
+                                                                               char *mailbox_name,
+                                                                               email_internal_mailbox_t **mailbox_list,
+                                                                               int *count, 
+                                                                               int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_stream [%p], mailbox_name [%p], mailbox_list [%p], count [%p], err_code [%p]", mail_stream, mailbox_name, mailbox_list, count, err_code);
+
+    MAILSTREAM *stream = mail_stream;
+    email_callback_holder_t holder;
+    char *pattern = NULL;
+    char *reference = NULL;
+    int   err = EMAIL_ERROR_NONE;
+    int   ret = false;
+
+       if (!stream || !mailbox_list || !count) {
+        err = EMAIL_ERROR_INVALID_PARAM;
+        goto FINISH_OFF;
+       }
+       
+       memset(&holder, 0x00, sizeof(holder));
+
+    /*  reference (ex : "{mail.test.com}", "{mail.test.com}inbox") */
+       if (mailbox_name)  {
+               char *s = NULL;
+               reference = em_malloc(EM_SAFE_STRLEN(stream->original_mailbox) + strlen(mailbox_name) + 1); /*prevent 34352*/
+               if (reference) {
+                       strncpy(reference, stream->original_mailbox, (size_t)EM_SAFE_STRLEN(stream->original_mailbox));
+                       if ((s = strchr(reference, '}')))
+                               *(++s) = '\0';
+                       strcat(reference, mailbox_name);
+               }
+       }
+       else
+               reference = EM_SAFE_STRDUP(stream->original_mailbox);
+
+       pattern        = "*";
+    stream->sparep = &holder;
+
+       /*  imap command : tag LIST reference * */
+    /*  see callback function mm_list */
+       mail_list(stream, reference, pattern);
+
+    stream->sparep = NULL;
+
+       EM_SAFE_FREE(reference);
+
+    *count        = holder.num;
+    *mailbox_list = (email_internal_mailbox_t*)holder.data;
+
+       ret = true;
+
+FINISH_OFF: 
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+/* description
+ *    check whether this imap mailbox is synchronous mailbox
+ * arguments
+ *    mailbox  :  imap mailbox to be checked
+ *    synchronous  :   boolean variable to be synchronous (1 : sync 0 : non-sync)
+ * return
+ *    succeed  :  1
+ *    fail  :  0
+ */
+int emcore_check_sync_imap_mailbox(email_mailbox_t *mailbox, int *synchronous, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       EM_DEBUG_LOG("\t mailbox[%p], synchronous[%p], err_code[%p]", mailbox, synchronous, err_code);
+       
+       if (err_code) {
+               *err_code = EMAIL_ERROR_NONE;
+       }
+
+       if (!mailbox || !synchronous) {
+               EM_DEBUG_EXCEPTION("\t mailbox[%p], synchronous[%p]", mailbox, synchronous);
+               
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *imap_mailbox_tbl = NULL;
+
+       if (!emstorage_get_mailbox_by_name(mailbox->account_id, 0, mailbox->mailbox_name, &imap_mailbox_tbl, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_name failed - %d", err);
+               goto FINISH_OFF;
+       }
+       
+       *synchronous = imap_mailbox_tbl ? 1  :  0;
+       
+       ret = true;
+       
+FINISH_OFF: 
+       if (imap_mailbox_tbl != NULL)
+               emstorage_free_mailbox(&imap_mailbox_tbl, 1, NULL);
+       
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+}
+
+
+/* description
+ *    set sync imap mailbox
+ * arguments
+ *    mailbox_list  :  imap mailbox to be synced
+ *    syncronous  :  0-sync 1 : non-sync
+ * return
+ *    succeed  :  1
+ *    fail  :  0
+ */
+
+INTERNAL_FUNC int emcore_set_sync_imap_mailbox(email_internal_mailbox_t *mailbox, int synchronous, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox[%p], synchronous[%d], err_code[%p]", mailbox, synchronous, err_code);
+       
+       if (!mailbox)  {
+               EM_DEBUG_EXCEPTION("mailbox[%p], synchronous[%d]", mailbox, synchronous);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *imap_mailbox_tbl_item = NULL;
+       emstorage_mailbox_tbl_t mailbox_tbl = { 0, };
+       emcore_uid_list *uid_list = NULL;
+       emstorage_read_mail_uid_tbl_t *downloaded_uids = NULL;
+       MAILSTREAM *stream = mailbox->mail_stream;
+       int mailbox_renamed = 0;
+       int j = 0;
+       int i = 0;
+       int temp = 0;
+       IMAPLOCAL *imap_local = NULL;
+       char cmd[128] = { 0 , }, tag[32] = { 0 , }, *p = NULL;
+               
+       if (synchronous) {              
+               /* if synchcronous, insert imap mailbox to db */
+               if (emstorage_get_mailbox_by_name(mailbox->account_id, 0, mailbox->mailbox_name, &imap_mailbox_tbl_item, true, &err))  {        
+                       /* mailbox already exists */
+                       /* mailbox Found, Do set the modifiable_yn = 1 */
+                       EM_DEBUG_LOG("mailbox already exists and setting modifiable_yn to 1");
+                       if (!emstorage_update_mailbox_modifiable_yn(mailbox->account_id, 0, mailbox->mailbox_name, 1, true, &err)) {
+                               EM_DEBUG_EXCEPTION(" emstorage_update_mailbox_modifiable_yn Failed [ %d ] ", err);
+                               goto JOB_ERROR;
+                       }
+               }
+               else {
+                       if (err != EMAIL_ERROR_MAILBOX_NOT_FOUND) {
+                               EM_DEBUG_EXCEPTION(">>>>.>>>>>Getting mailbox failed>>>>>>>>>>>>>>");
+                               /* This is error scenario so finish the job */
+                               goto JOB_ERROR;
+                       }
+                       else {
+                               /* This is not error scenario - mailbox is either new/renamed mailbox and needs to be added/modfied in DB */
+                               /* Now check if mailbox is renamed */
+                               EM_DEBUG_LOG(">>>>>>>>>>>>>>>>>>>>>>>MAILBOX NEW OR RENAMED");
+                               if (stream) {
+                                       imap_local = ((MAILSTREAM *)stream)->local;
+                                       EM_DEBUG_LINE;
+                                       sprintf(tag, "%08lx", 0xffffffff & (((MAILSTREAM *)stream)->gensym++));
+                                       EM_DEBUG_LINE;
+                                       sprintf(cmd, "%s SELECT %s\015\012", tag, mailbox->mailbox_name);
+                                       EM_DEBUG_LINE;
+
+                               }
+                               
+                               /* select the mailbox and get its UID */
+                               if (!imap_local || !imap_local->netstream || !net_sout(imap_local->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+                                       EM_DEBUG_EXCEPTION("network error - failed to IDLE on Mailbox [%s]", mailbox->mailbox_name);
+                                       /*
+                                       err = EMAIL_ERROR_CONNECTION_BROKEN;
+                                       if(imap_local)
+                                               imap_local->netstream = NULL;
+                                       mailbox->mail_stream = NULL;
+                                       goto JOB_ERROR;
+                                       */
+                               }
+                               else {
+                                       EM_DEBUG_LOG("Get response for select call");
+                                       while (imap_local->netstream) {
+                                       p = net_getline(imap_local->netstream);
+                                               EM_DEBUG_LOG("p =[%s]", p);
+                                               if (!strncmp(p, "+", 1)) {
+                                                       ret = 1;
+                                                       break;
+                                               }
+                                               else if (!strncmp(p, "*", 1)) {
+                                               EM_SAFE_FREE(p); 
+                                               continue;
+                                               }
+                                               else {
+                                                       ret = 0;
+                                                       break;
+                                               }
+                               }
+                                       EM_SAFE_FREE(p); 
+                                       EM_DEBUG_LINE;
+                                       /* check if OK or BAD response comes. */
+                                       /* if response is OK the try getting UID list. */
+                                       if (!strncmp((char *)imap_local->reply.key, "OK", strlen("OK")))  {
+                                               EM_DEBUG_LOG(">>>>>>>>>>Select success on %s mailbox", mailbox->mailbox_name);
+                                               if (!imap4_mailbox_get_uids(stream, &uid_list, &err)) {
+                                                       EM_DEBUG_EXCEPTION("imap4_mailbox_get_uids failed - %d", err);
+                                                       EM_SAFE_FREE(uid_list);
+                                               }
+                                               else {
+                                                       if (!emstorage_get_downloaded_list(mailbox->account_id, 0, &downloaded_uids, &j, true, &err)) {
+                                                               EM_DEBUG_EXCEPTION("emstorage_get_downloaded_list failed [%d]", err);
+                                               
+                                                               downloaded_uids = NULL;
+                                                       }
+                                                       else /* Prevent Defect - 28497 */ {
+                                                               emcore_uid_list *uid_elem = uid_list;
+                                                               emcore_uid_list *next_uid_elem = NULL;
+                                                               if (uid_elem) {
+                                                                       for (i = j; (i > 0 && !mailbox_renamed); i--)  {
+                                                                               if (uid_elem) {
+                                                                                       next_uid_elem = uid_elem->next;
+                                                                                       if (uid_elem->uid && downloaded_uids[i - 1].s_uid && !strcmp(uid_elem->uid, downloaded_uids[i - 1].s_uid)) {
+                                                                                               temp = i-1;
+                                                                                               mailbox_renamed = 1;
+                                                                                               break;
+                                                                                       }
+                                                                                       EM_SAFE_FREE(uid_elem->uid);
+                                                                                       uid_elem = next_uid_elem;
+                                                                               }
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       } /* mailbox selected */
+                               }       
+
+                               if (mailbox_renamed) /* renamed mailbox */ {
+                                       EM_DEBUG_LOG("downloaded_uids[temp].mailbox_name [%s]", downloaded_uids[temp].mailbox_name);
+                                       /* Do a mailbox rename in the DB */
+                                       if (!emstorage_modify_mailbox_of_mails(downloaded_uids[temp].mailbox_name, mailbox->mailbox_name, true, &err))
+                                               EM_DEBUG_EXCEPTION(" emstorage_modify_mailbox_of_mails Failed [%d]", err);
+
+                                       mailbox_renamed = 0;
+
+                                       memset(&mailbox_tbl, 0, sizeof(emstorage_mailbox_tbl_t));
+
+                                       mailbox_tbl.account_id = mailbox->account_id;
+                                       mailbox_tbl.local_yn = 0;
+                                       mailbox_tbl.mailbox_name = mailbox->mailbox_name;
+                                       mailbox_tbl.mailbox_type = mailbox->mailbox_type;
+
+                                       /* Get the Alias Name after parsing the Full mailbox Path */
+                                       if(mailbox->alias == NULL)
+                                               mailbox->alias = emcore_get_alias_of_mailbox((const char *)mailbox->mailbox_name);
+                                       
+                                       mailbox_tbl.alias = mailbox->alias;
+                                       mailbox_tbl.deleted_flag  = 1;
+                                       mailbox_tbl.modifiable_yn = 1;
+                                       mailbox_tbl.total_mail_count_on_server = 0;
+                                       
+                                       /* if non synchronous, delete imap mailbox from db */
+                                       if (!emstorage_update_mailbox(mailbox->account_id, 0, downloaded_uids[temp].mailbox_id, &mailbox_tbl, true, &err)) {
+                                               EM_DEBUG_EXCEPTION(" emstorage_update_mailbox Failed [ %d ] ", err);
+                                               goto JOB_ERROR;
+                                       }
+                                       
+                               }
+                               else /* Its a Fresh Mailbox */ {
+                                       memset(&mailbox_tbl, 0, sizeof(emstorage_mailbox_tbl_t));
+
+                                       mailbox_tbl.mailbox_id     = mailbox->mailbox_id;
+                                       mailbox_tbl.account_id     = mailbox->account_id;
+                                       mailbox_tbl.local_yn       = 0;
+                                       mailbox_tbl.deleted_flag   = 0;
+                                       mailbox_tbl.mailbox_type   = mailbox->mailbox_type;
+                                       mailbox_tbl.mailbox_name   = mailbox->mailbox_name;
+                                       mailbox_tbl.mail_slot_size = mailbox->mail_slot_size;
+                                       mailbox_tbl.no_select      = mailbox->no_select;
+
+                                       /* Get the Alias Name after Parsing the Full mailbox Path */
+                                       if(mailbox->alias == NULL)
+                                       mailbox->alias = emcore_get_alias_of_mailbox((const char *)mailbox->mailbox_name);
+
+                                       if (mailbox->alias) {
+                                               EM_DEBUG_LOG("mailbox->alias [%s] ", mailbox->alias);
+
+                                               mailbox_tbl.alias = mailbox->alias;
+                                               mailbox_tbl.modifiable_yn = 1; 
+                                               mailbox_tbl.total_mail_count_on_server = 0;
+                                                       
+                                               EM_DEBUG_LOG("mailbox_tbl.mailbox_type - %d", mailbox_tbl.mailbox_type);
+
+                                               if (!emstorage_add_mailbox(&mailbox_tbl, true, &err)) {
+                                                       EM_DEBUG_EXCEPTION("emstorage_add_mailbox failed - %d", err);
+                                                       goto JOB_ERROR;
+                                               }
+                                       }
+                               }
+                       }
+               }
+       }
+
+       /* set sync db mailbox */
+       mailbox->synchronous = synchronous;
+       
+       ret = true;
+       
+JOB_ERROR:
+
+       if (downloaded_uids) 
+               emstorage_free_read_mail_uid(&downloaded_uids, j, NULL);
+
+       if (imap_mailbox_tbl_item)
+               emstorage_free_mailbox(&imap_mailbox_tbl_item, 1, NULL);
+
+       if (err_code)
+               *err_code = err;
+       
+       return ret;
+}
+
+/* description
+ *    create a new imap mailbox
+ * arguments
+ *    new_mailbox  :  imap mailbox to be created
+ * return
+ *    succeed  :  1
+ *    fail  :  0
+ */
+INTERNAL_FUNC int emcore_create_imap_mailbox(email_mailbox_t *mailbox, int *err_code)
+{
+    MAILSTREAM *stream = NULL;
+    char *long_enc_path = NULL;
+    void *tmp_stream = NULL;
+    int ret = false;
+    int err = EMAIL_ERROR_NONE;
+
+    EM_DEBUG_FUNC_BEGIN();
+
+    if (!mailbox) {
+        err = EMAIL_ERROR_INVALID_PARAM;
+        goto FINISH_OFF;
+    }
+
+    /* connect mail server */
+    stream = NULL;
+    if (!emcore_connect_to_remote_mailbox(mailbox->account_id, 0, (void **)&tmp_stream, &err)) {
+       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+        goto FINISH_OFF;
+    }
+
+    stream = (MAILSTREAM *)tmp_stream;
+
+    /* encode mailbox name by UTF7, and rename to full path (ex : {mail.test.com}child_mailbox) */
+    if (!emcore_get_long_encoded_path(mailbox->account_id, mailbox->mailbox_name, '/', &long_enc_path, &err)) {
+       EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path failed [%d]", err);
+        goto FINISH_OFF;
+    }
+
+    /* create mailbox */
+    if (!mail_create(stream, long_enc_path)) {
+       EM_DEBUG_EXCEPTION("mail_create failed");
+        err = EMAIL_ERROR_IMAP4_CREATE_FAILURE;
+        goto FINISH_OFF;
+    }
+
+       emcore_close_mailbox(0, stream);
+       stream = NULL;
+
+    EM_SAFE_FREE(long_enc_path);
+
+    ret = true;
+
+FINISH_OFF:
+    if (stream){
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+    }
+
+    EM_SAFE_FREE(long_enc_path);
+
+    if (mailbox) {
+               if (err == EMAIL_ERROR_NONE) {
+                       if(!emcore_notify_network_event(NOTI_ADD_MAILBOX_FINISH, mailbox->account_id, mailbox->mailbox_name, 0, 0))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_ADD_MAILBOX_FINISH] failed");
+               }
+               else if (!emcore_notify_network_event(NOTI_ADD_MAILBOX_FAIL, mailbox->account_id, mailbox->mailbox_name, 0, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_ADD_MAILBOX_FAIL] failed");
+    }
+
+    if (err_code)
+        *err_code = err;
+
+    return ret;
+}
+
+
+/* description
+ *    delete a imap mailbox
+ * arguments
+ *    input_mailbox_id  :  mailbox ID to be deleted
+ * return
+ *    succeed  :  1
+ *    fail  :  0
+ */
+INTERNAL_FUNC int emcore_delete_imap_mailbox(int input_mailbox_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       MAILSTREAM *stream = NULL;
+       char *long_enc_path = NULL;
+       email_account_t *ref_account = NULL;
+       void *tmp_stream = NULL;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE || !mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox_tbl->account_id);
+
+       if (!ref_account || ref_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               EM_DEBUG_EXCEPTION("Invalid account information");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /* connect mail server */
+       if (!emcore_connect_to_remote_mailbox(mailbox_tbl->account_id, 0, (void **)&tmp_stream, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       stream = (MAILSTREAM *)tmp_stream;
+
+       /* encode mailbox name by UTF7, and rename to full path (ex : {mail.test.com}child_mailbox) */
+       if (!emcore_get_long_encoded_path(mailbox_tbl->account_id, mailbox_tbl->mailbox_name, '/', &long_enc_path, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* delete mailbox */
+       if (!mail_delete(stream, long_enc_path)) {
+               EM_DEBUG_EXCEPTION("mail_delete failed");
+               err = EMAIL_ERROR_IMAP4_DELETE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       emcore_close_mailbox(0, stream);
+       stream = NULL;
+
+       EM_SAFE_FREE(long_enc_path);
+
+       ret = true;
+
+FINISH_OFF:
+       if (stream) {
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+       }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       EM_SAFE_FREE(long_enc_path);
+
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       if (err == EMAIL_ERROR_NONE) {
+               if(!emcore_notify_network_event(NOTI_DELETE_MAILBOX_FINISH, input_mailbox_id, 0, 0, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_ADD_MAILBOX_FINISH] failed");
+       }
+       else if (!emcore_notify_network_event(NOTI_DELETE_MAILBOX_FAIL, input_mailbox_id, 0, 0, err))
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event[NOTI_ADD_MAILBOX_FAIL] failed");
+
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_move_mailbox_on_imap_server(int input_account_id, char *input_old_mailbox_path, char *input_new_mailbox_path)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], input_old_mailbox_path [%p], input_new_mailbox_path [%p]", input_account_id, input_old_mailbox_path, input_new_mailbox_path);
+       MAILSTREAM *stream = NULL;
+       char *long_enc_path_old = NULL;
+       char *long_enc_path_new = NULL;
+       email_account_t *ref_account = NULL;
+       void *tmp_stream = NULL;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!input_old_mailbox_path || !input_new_mailbox_path) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(input_account_id);
+
+       if (!ref_account || ref_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_ACCOUNT");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /* connect mail server */
+       stream = NULL;
+       if (!emcore_connect_to_remote_mailbox(input_account_id, 0, (void **)&tmp_stream, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       stream = (MAILSTREAM *)tmp_stream;
+
+       /* encode mailbox name by UTF7, and rename to full path (ex : {mail.test.com}child_mailbox) */
+       if (!emcore_get_long_encoded_path(input_account_id, input_old_mailbox_path, '/', &long_enc_path_old, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* encode mailbox name by UTF7, and rename to full path (ex : {mail.test.com}child_mailbox) */
+       if (!emcore_get_long_encoded_path(input_account_id, input_new_mailbox_path, '/', &long_enc_path_new, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* rename mailbox */
+       if (!mail_rename(stream, long_enc_path_old, long_enc_path_new)) {
+               err = EMAIL_ERROR_IMAP4_RENAME_FAILURE;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+       EM_SAFE_FREE(long_enc_path_old);
+       EM_SAFE_FREE(long_enc_path_new);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (stream) {
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-core/email-core-mail.c b/email-core/email-core-mail.c
new file mode 100755 (executable)
index 0000000..7106687
--- /dev/null
@@ -0,0 +1,6236 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File :  email-core-mail.c
+ * Desc :  Mail Operation
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#undef close
+#include <time.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <fcntl.h>
+
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <vconf.h> 
+#include <contacts.h>
+
+#include "email-internal-types.h"
+#include "c-client.h"
+#include "lnx_inc.h"
+#include "email-utilities.h"
+#include "email-core-global.h"
+#include "email-core-utils.h"
+#include "email-core-mail.h"
+#include "email-core-mime.h"
+#include "email-core-mailbox.h"
+#include "email-storage.h"
+#include "email-network.h"
+#include "email-core-mailbox-sync.h"
+#include "email-core-event.h"
+#include "email-core-account.h" 
+#include "email-core-signal.h"
+#include "email-core-smtp.h"
+
+#include "email-convert.h"
+#include "email-debug-log.h"
+
+#ifdef __FEATURE_DRM__
+#include <drm_client.h>
+#endif /* __FEATURE_DRM__ */
+
+#define ST_SILENT   (long) 0x2 /* don't return results */
+#define ST_SET      (long) 0x4 /* set vs. clear */
+
+static char g_new_server_uid[129];
+
+bool only_body_download = false;
+
+int multi_part_body_size = 0;
+int is_multi_part_body_download_all = 0;
+int _pop3_receiving_mail_id = 0;
+int _pop3_received_body_size = 0;
+int _pop3_last_notified_body_size = 0;
+int _pop3_total_body_size = 0;
+
+int _imap4_received_body_size = 0;
+int _imap4_last_notified_body_size = 0;
+int _imap4_total_body_size = 0;
+int _imap4_download_noti_interval_value = 0;
+
+BODY **g_inline_list = NULL ;
+int g_inline_count = 0;
+
+
+static int emcore_delete_mails_from_pop3_server(email_account_t *input_account, int input_mail_ids[], int input_mail_id_count);
+static int emcore_mail_cmd_read_mail_pop3(void *stream, int msgno, int limited_size, int *downloded_size, int *total_body_size, int *err_code);
+
+extern long pop3_send (MAILSTREAM *stream, char *command, char *args);
+
+
+#ifdef FEATURE_CORE_DEBUG
+static char *_getType(int type)
+{
+       switch (type) {
+               case 0:  return "TYPETEXT";
+               case 1:  return "TYPEMULTIPART";
+               case 2:  return "TYPEMESSAGE";
+               case 3:  return "TYPEAPPLICATION";
+               case 4:  return "TYPEAUDIO";
+               case 5:  return "TYPEVIDEO";
+               case 6:  return "TYPEMODEL";
+               case 7:  return "TYPEOTHER";
+       }
+       return g_strdup_printf("%d", type);
+}
+
+static char *_getEncoding(int encoding)
+{
+       switch (encoding) {
+               case 0:  return "ENC7BIT";
+               case 1:  return "ENC8BIT";
+               case 2:  return "ENCBINARY";
+               case 3:  return "ENCBASE64";
+               case 4:  return "ENCQUOTEDPRINTABLE";
+               case 5:  return "ENCOTHER";
+       }
+       return g_strdup_printf("%d", encoding);
+}
+
+static void _print_parameter(PARAMETER *param)
+{
+       while (param != NULL) {
+               EM_DEBUG_EXCEPTION("param->attribute[%s]", param->attribute);
+               EM_DEBUG_EXCEPTION("param->value[%s]", param->value);
+               
+               param = param->next;
+       }
+}
+
+static void _print_stringlist(STRINGLIST *stringlist)
+{
+       while (stringlist != NULL) {
+               EM_DEBUG_LOG("stringlist->text.data[%s]", stringlist->text.data);
+               EM_DEBUG_LOG("stringlist->text.size[%ld]", stringlist->text.size);
+               
+               stringlist = stringlist->next;
+       }
+}
+
+static void _print_body(BODY *body, int recursive)
+{
+       EM_DEBUG_LOG(" ========================================================== ");
+       
+       if (body != NULL) {
+               EM_DEBUG_LOG("body->type[%s]", _getType(body->type));
+               EM_DEBUG_LOG("body->encoding[%s]", _getEncoding(body->encoding));
+               EM_DEBUG_LOG("body->subtype[%s]", body->subtype);
+               
+               EM_DEBUG_LOG("body->parameter[%p]", body->parameter);
+               
+               _print_parameter(body->parameter);
+               
+               EM_DEBUG_LOG("body->id[%s]", body->id);
+               EM_DEBUG_LOG("body->description[%s]", body->description);
+               
+               EM_DEBUG_LOG("body->disposition.type[%s]", body->disposition.type);
+               EM_DEBUG_LOG("body->disposition.parameter[%p]", body->disposition.parameter);
+               
+               _print_parameter(body->disposition.parameter);
+               
+               EM_DEBUG_LOG("body->language[%p]", body->language);
+               
+               _print_stringlist(body->language);
+               
+               EM_DEBUG_LOG("body->location[%s]", body->location);
+       
+               EM_DEBUG_LOG("body->mime.offset[%ld]", body->mime.offset);
+               EM_DEBUG_LOG("body->mime.text.data[%s]", body->mime.text.data);
+               EM_DEBUG_LOG("body->mime.text.size[%ld]", body->mime.text.size);
+               
+               EM_DEBUG_LOG("body->contents.offset[%ld]", body->contents.offset);
+               EM_DEBUG_LOG("body->contents.text.data[%p]", body->contents.text.data);
+               EM_DEBUG_LOG("body->contents.text.size[%ld]", body->contents.text.size);
+       
+               EM_DEBUG_LOG("body->nested.part[%p]", body->nested.part);
+               
+               EM_DEBUG_LOG("body->size.lines[%ld]", body->size.lines);
+               EM_DEBUG_LOG("body->size.bytes[%ld]", body->size.bytes);
+               
+               EM_DEBUG_LOG("body->md5[%s]", body->md5);
+               EM_DEBUG_LOG("body->sparep[%p]", body->sparep);
+               
+               if (recursive)  {
+                       PART *part = body->nested.part;
+                       
+                       while (part != NULL)  {
+                               _print_body(&(part->body), recursive);
+                               part = part->next;
+                       }
+               }
+       }
+       
+       EM_DEBUG_LOG(" ========================================================== ");
+}
+#endif /*  FEATURE_CORE_DEBUG */
+
+static int convert_contact_err_to_email_err(int contact_err)
+{
+       int err = EMAIL_ERROR_NONE;
+
+       switch (contact_err) {
+       case CONTACTS_ERROR_NONE :
+               err = EMAIL_ERROR_NONE;
+               break;
+       case CONTACTS_ERROR_OUT_OF_MEMORY :
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               break;
+       case CONTACTS_ERROR_INVALID_PARAMETER :
+               err = EMAIL_ERROR_INVALID_PARAM;
+               break;
+       case CONTACTS_ERROR_NO_DATA :
+               err = EMAIL_ERROR_DATA_NOT_FOUND;
+               break;
+       case CONTACTS_ERROR_DB :
+               err = EMAIL_ERROR_DB_FAILURE;
+               break;
+       case CONTACTS_ERROR_IPC :
+               err = EMAIL_ERROR_IPC_CONNECTION_FAILURE;
+               break;
+       case CONTACTS_ERROR_SYSTEM:
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               break;
+       case CONTACTS_ERROR_INTERNAL:
+       default:
+               err = EMAIL_ERROR_UNKNOWN;
+               break;
+       }
+       return err;
+}
+
+static int pop3_mail_delete(MAILSTREAM *stream, int msgno, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msgno[%d], err_code[%p]", stream, msgno, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       POP3LOCAL *pop3local = NULL;
+       char cmd[64];
+       char *p = NULL;
+       
+       if (!stream)  {
+               EM_DEBUG_EXCEPTION("stream[%p]", stream);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       if (!(pop3local = stream->local) || !pop3local->netstream) {
+               EM_DEBUG_EXCEPTION("invalid POP3 stream detected...");
+               err = EMAIL_ERROR_UNKNOWN;
+               goto FINISH_OFF;
+       }
+       
+       memset(cmd, 0x00, sizeof(cmd));
+       
+       SNPRINTF(cmd, sizeof(cmd), "DELE %d\015\012", msgno);
+       
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG("[POP3] >>> %s", cmd);
+#endif
+       
+       /*  send command  :  delete specified mail */
+       if (!net_sout(pop3local->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+               EM_DEBUG_EXCEPTION("net_sout failed...");
+               err = EMAIL_ERROR_CONNECTION_BROKEN;            /* EMAIL_ERROR_UNKNOWN; */
+               goto FINISH_OFF;
+       }
+       
+       /*  receive response */
+       if (!(p = net_getline(pop3local->netstream))) {
+               EM_DEBUG_EXCEPTION("net_getline failed...");
+               err = EMAIL_ERROR_INVALID_RESPONSE;
+               goto FINISH_OFF;
+       }
+       
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG("[POP3] <<< %s", p);
+#endif
+
+       if (*p == '-') {                /*  '-ERR' */
+               err = EMAIL_ERROR_POP3_DELE_FAILURE;            /* EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER; */
+               goto FINISH_OFF;
+       }
+       
+       if (*p != '+') {                /*  '+OK' ... */
+               err = EMAIL_ERROR_INVALID_RESPONSE;
+               goto FINISH_OFF;
+       }
+       
+       ret = true;
+
+FINISH_OFF: 
+       if (p)
+               free(p);
+       
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+
+static void emcore_mail_copyuid_ex(MAILSTREAM *stream, char *mailbox, unsigned long uidvalidity, SEARCHSET *sourceset, SEARCHSET *destset)
+{
+       
+       EM_DEBUG_FUNC_BEGIN();
+
+       int index = -1;
+       int i = 0;
+       int err = EMAIL_ERROR_NONE;
+       
+       unsigned long  first_uid = 0;
+       unsigned long last_uid = 0;
+       
+       unsigned long *old_server_uid = NULL;
+       unsigned long *new_server_uid = NULL;
+       int count = 0;
+       SEARCHSET *temp = sourceset;
+
+       char old_server_uid_char[129];
+       char new_server_uid_char[129];
+
+       if (NULL == sourceset || NULL == destset) {
+               /* 
+               sourceset will be NULL when the sequence of UIDs sent to server for mail move operation has all invalid old server uids  
+               if sourceset is NULL then corresponding dest set will be NULL
+               */
+               
+               EM_DEBUG_LOG("emcore_mail_copyuid_ex failed :  Invalid Parameters--> sourceset[%p] , destset[%p]", sourceset, destset);
+               return;
+       }
+
+       /* To get count of mails actually moved */
+
+       while (temp) {
+               if (temp->first > 0) {
+                       first_uid = temp->first;
+
+                       count++;
+
+                       if (temp->last > 0) {
+                               last_uid = temp->last;
+
+                               while (first_uid < last_uid) {
+                                       first_uid++;
+                                       count++;
+                               }
+                       }
+               }
+               
+               temp = temp->next;
+       }
+
+
+       
+
+       EM_DEBUG_LOG("Count of mails copied [%d]", count);
+       old_server_uid = em_malloc(count * sizeof(unsigned long));
+       new_server_uid = em_malloc(count * sizeof(unsigned long));
+
+       /* While loop below will collect all old server uid from sourceset into old_server_uid array */
+       
+       while (sourceset) {
+               if (sourceset->first > 0) {
+                       first_uid = sourceset->first;
+
+                       index++;
+                       old_server_uid[index] = first_uid;
+
+                       if (sourceset->last > 0) {
+                               last_uid = sourceset->last;
+
+                               while (first_uid < last_uid) {
+                                       first_uid++;
+                                       index++;
+
+                                       old_server_uid[index] = first_uid;
+                               }
+                       }
+               }
+               
+               sourceset = sourceset->next;
+       }
+
+       /* While loop below will collect all new server uid from destset into new_server_uid array */
+
+       index = -1;
+       first_uid = last_uid = 0;
+       
+       while (destset) {
+               if (destset->first > 0) {
+                       first_uid = destset->first;
+
+                       index++;
+                       new_server_uid[index] = first_uid;
+
+                       if (destset->last > 0) {
+                               last_uid = destset->last;
+
+                               while (first_uid < last_uid) {
+                                       first_uid++;
+                                       index++;
+
+                                       new_server_uid[index] = first_uid;
+                               }
+                       }
+               }
+               
+               destset = destset->next;
+       }
+
+       /* For loop below updates mail_tbl and mail_read_mail_uid_tbl with new server uids*/
+       
+       for (i = 0; i <= index; ++i) {
+
+               memset(old_server_uid_char, 0x00, sizeof(old_server_uid_char));
+               sprintf(old_server_uid_char, "%ld", old_server_uid[i]);
+
+               EM_DEBUG_LOG("Old Server Uid Char[%s]", old_server_uid_char);
+               
+               memset(new_server_uid_char, 0x00, sizeof(new_server_uid_char));
+               sprintf(new_server_uid_char, "%ld", new_server_uid[i]);
+
+               EM_DEBUG_LOG("New Server Uid Char[%s]", new_server_uid_char);
+       
+               if (!emstorage_update_server_uid(old_server_uid_char, new_server_uid_char, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_update_server_uid failed...[%d]", err);
+               }
+               
+               if (!emstorage_update_read_mail_uid_by_server_uid(old_server_uid_char, new_server_uid_char, mailbox, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_update_read_mail_uid_by_server_uid failed... [%d]", err);
+               }
+               
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+               if (false == emstorage_update_pbd_activity(old_server_uid_char, new_server_uid_char, mailbox, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_update_pbd_activity failed... [%d]", err);
+               }
+               
+#endif
+       }
+
+       EM_SAFE_FREE(old_server_uid);
+       EM_SAFE_FREE(new_server_uid);
+       
+}
+
+INTERNAL_FUNC int emcore_move_mail_on_server_ex(int account_id, int src_mailbox_id,  int mail_ids[], int num, int dest_mailbox_id, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       MAILSTREAM *stream = NULL;
+       int err_code = EMAIL_ERROR_NONE;
+       email_account_t *ref_account = NULL;
+       int ret = false;
+       int i = 0;
+       email_id_set_t *id_set = NULL;
+       int id_set_count = 0;
+
+       email_uid_range_set *uid_range_set = NULL;
+       int len_of_each_range = 0;
+
+       email_uid_range_set *uid_range_node = NULL;
+
+       char **string_list = NULL;      
+       int string_count = 0;
+       emstorage_mailbox_tbl_t* dest_mailbox = NULL;
+       
+       if (num <= 0  || account_id <= 0 || src_mailbox_id <= 0 || dest_mailbox_id <= 0 || NULL == mail_ids) {
+               if (error_code != NULL) {
+                       *error_code = EMAIL_ERROR_INVALID_PARAM;
+               }
+               EM_DEBUG_LOG("Invalid Parameters- num[%d], account_id[%d], src_mailbox_id[%d], dest_mailbox_id[%d], mail_ids[%p]", num, account_id, src_mailbox_id, dest_mailbox_id, mail_ids);
+               return false;
+       }
+
+       ref_account = emcore_get_account_reference(account_id);
+       
+       if (NULL == ref_account) {
+               EM_DEBUG_EXCEPTION(" emcore_get_account_reference failed[%d]", account_id);
+               
+               *error_code = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (ref_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               *error_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+
+       if (!emcore_connect_to_remote_mailbox(account_id, src_mailbox_id, (void **)&stream, &err_code)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed[%d]", err_code);
+               
+               goto FINISH_OFF;
+       }
+
+       if (NULL != stream) {
+               mail_parameters(stream, SET_COPYUID, emcore_mail_copyuid_ex);
+               EM_DEBUG_LOG("calling mail_copy_full FODLER MAIL COPY ");
+               /*  [h.gahlaut] Break the set of mail_ids into comma separated strings of given length  */
+               /*  Length is decided on the basis of remaining keywords in the Query to be formed later on in emstorage_get_id_set_from_mail_ids  */
+               /*  Here about 90 bytes are required for fixed keywords in the query-> SELECT local_uid, s_uid from mail_read_mail_uid_tbl where local_uid in (....) ORDER by s_uid  */
+               /*  So length of comma separated strings which will be filled in (.....) in above query can be maximum QUERY_SIZE - 90  */
+               
+               if (false == emcore_form_comma_separated_strings(mail_ids, num, QUERY_SIZE - 90, &string_list, &string_count, &err_code))   {
+                       EM_DEBUG_EXCEPTION("emcore_form_comma_separated_strings failed [%d]", err_code);
+                       goto FINISH_OFF;
+               }
+               
+               if ( (err_code = emstorage_get_mailbox_by_id(dest_mailbox_id, &dest_mailbox)) != EMAIL_ERROR_NONE || !dest_mailbox) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err_code);
+                       goto FINISH_OFF;
+               }
+
+               /*  Now execute one by one each comma separated string of mail_ids */
+
+               for (i = 0; i < string_count; ++i) {
+                       /*  Get the set of mail_ds and corresponding server_mail_ids sorted by server mail ids in ascending order */
+               
+                       if (false == emstorage_get_id_set_from_mail_ids(string_list[i], &id_set, &id_set_count, &err_code)) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_id_set_from_mail_ids failed [%d]", err_code);
+                               goto FINISH_OFF;
+                       }
+                       
+                       /*  Convert the sorted sequence of server mail ids to range sequences of given length. A range sequence will be like A : B, C, D: E, H */
+                       
+                       len_of_each_range = MAX_IMAP_COMMAND_LENGTH - 40; /*  1000 is the maximum length allowed RFC 2683. 40 is left for keywords and tag. */
+                       
+                       if (false == emcore_convert_to_uid_range_set(id_set, id_set_count, &uid_range_set, len_of_each_range, &err_code)) {
+                               EM_DEBUG_EXCEPTION("emcore_convert_to_uid_range_set failed [%d]", err_code);
+                               goto FINISH_OFF;
+                       }
+               
+                       uid_range_node = uid_range_set;
+               
+                       while (uid_range_node != NULL) {
+                               /* Remove comma from end of uid_range */
+                               uid_range_node->uid_range[EM_SAFE_STRLEN(uid_range_node->uid_range) - 1] = '\0';
+                               EM_DEBUG_LOG("uid_range_node->uid_range - %s", uid_range_node->uid_range);
+                               if (!mail_copy_full(stream, uid_range_node->uid_range, dest_mailbox->mailbox_name, CP_UID | CP_MOVE)) {
+                                       EM_DEBUG_EXCEPTION("emcore_move_mail_on_server_ex :   Mail cannot be moved failed");
+                                       EM_DEBUG_EXCEPTION("Mail MOVE failed ");
+                                       goto FINISH_OFF;
+                               }
+                               else if (!mail_expunge_full(stream, uid_range_node->uid_range, EX_UID)) {
+                                       EM_DEBUG_EXCEPTION("emcore_move_mail_on_server_ex :   Mail cannot be expunged after move. failed!");
+                                               EM_DEBUG_EXCEPTION("Mail Expunge after move failed ");
+                                                 goto FINISH_OFF;
+                               }
+                               else {
+                                       EM_DEBUG_LOG("Mail MOVE SUCCESS ");
+                               }
+                               
+                               uid_range_node = uid_range_node->next;
+                       }       
+
+                       emcore_free_uid_range_set(&uid_range_set);
+
+                       EM_SAFE_FREE(id_set);
+                       
+                       id_set_count = 0;
+               }
+       
+       }
+       else {
+               EM_DEBUG_EXCEPTION(">>>> STREAM DATA IS NULL >>> ");
+               goto FINISH_OFF;
+       }
+       
+
+       ret = true;
+
+FINISH_OFF: 
+       emcore_close_mailbox(0, stream);
+       stream = NULL;
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       if (ret || ref_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) /* Delete local activity for POP3 mails and successful move operation in IMAP */ {
+               emstorage_activity_tbl_t new_activity;
+               for (i = 0; i<num ; i++) {              
+                       memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
+                       new_activity.activity_type = ACTIVITY_MOVEMAIL;
+                       new_activity.account_id    = account_id;
+                       new_activity.mail_id       = mail_ids[i];
+                       new_activity.src_mbox      = src_mailbox;
+                       new_activity.dest_mbox     = dest_mailbox;
+               
+                       if (!emcore_delete_activity(&new_activity, &err_code)) {
+                               EM_DEBUG_EXCEPTION(">>>>>>Local Activity ACTIVITY_MOVEMAIL [%d] ", err_code);
+                       }
+               }
+
+       }
+#endif
+       if (dest_mailbox) {
+               emstorage_free_mailbox(&dest_mailbox, 1, &err_code);
+       }
+
+       if (error_code != NULL) {
+               *error_code = err_code;
+       }
+
+       return ret;
+}
+
+int emcore_delete_mails_from_imap4_server(int mail_ids[], int num, int from_server, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       IMAPLOCAL *imaplocal = NULL;
+       char *p = NULL;
+       MAILSTREAM *stream = NULL;
+       char tag[MAX_TAG_SIZE];
+       char cmd[MAX_IMAP_COMMAND_LENGTH];
+       email_id_set_t *id_set = NULL;
+       int id_set_count = 0;
+       int i = 0;
+       email_uid_range_set *uid_range_set = NULL;
+       int len_of_each_range = 0;
+       email_uid_range_set *uid_range_node = NULL;
+       char **string_list = NULL;      
+       int string_count = 0;
+       int delete_success = false;
+       emstorage_mail_tbl_t *mail_tbl_data = NULL;
+               
+       if (num <= 0 || !mail_ids) {
+               EM_DEBUG_EXCEPTION(" Invalid parameter ");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < num; i++) {
+               if (!emstorage_get_downloaded_mail(mail_ids[i], &mail_tbl_data, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_downloaded_mail failed [%d]", err);
+
+                       if (err == EMAIL_ERROR_MAIL_NOT_FOUND) {        /* not server mail */
+                               continue;
+                       }
+                       else
+                               break;
+               }
+       }
+
+       if (!mail_tbl_data || mail_tbl_data->account_id <= 0 || mail_tbl_data->mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("mail_tbl_data [%p]", mail_tbl_data);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_connect_to_remote_mailbox(mail_tbl_data->account_id, mail_tbl_data->mailbox_id , (void **)&stream, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /*  [h.gahlaut] Break the set of mail_ids into comma separated strings of given length  */
+       /*  Length is decided on the basis of remaining keywords in the Query to be formed later on in emstorage_get_id_set_from_mail_ids  */
+       /*  Here about 90 bytes are required for fixed keywords in the query-> SELECT local_uid, s_uid from mail_read_mail_uid_tbl where local_uid in (....) ORDER by s_uid  */
+       /*  So length of comma separated strings which will be filled in (.....) in above query can be maximum QUERY_SIZE - 90  */
+
+       if (false == emcore_form_comma_separated_strings(mail_ids, num, QUERY_SIZE - 90, &string_list, &string_count, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_form_comma_separated_strings failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /*  Now execute one by one each comma separated string of mail_ids  */
+       
+       for (i = 0; i < string_count; ++i) {
+               /*  Get the set of mail_ds and corresponding server_mail_ids sorted by server mail ids in ascending order  */
+
+               if (false == emstorage_get_id_set_from_mail_ids(string_list[i], &id_set, &id_set_count, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_id_set_from_mail_ids failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               
+               /*  Convert the sorted sequence of server mail ids to range sequences of given length. A range sequence will be like A : B, C, D: E, H  */
+               
+               len_of_each_range = MAX_IMAP_COMMAND_LENGTH - 40;               /*   1000 is the maximum length allowed RFC 2683. 40 is left for keywords and tag.  */
+               
+               if (false == emcore_convert_to_uid_range_set(id_set, id_set_count, &uid_range_set, len_of_each_range, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_convert_to_uid_range_set failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               uid_range_node = uid_range_set;
+
+               while (uid_range_node != NULL) {
+                       /*  Remove comma from end of uid_range  */
+
+                       uid_range_node->uid_range[EM_SAFE_STRLEN(uid_range_node->uid_range) - 1] = '\0';
+
+                       if (!(imaplocal = stream->local) || !imaplocal->netstream)  {
+                               EM_DEBUG_EXCEPTION("invalid IMAP4 stream detected...");
+               
+                               err = EMAIL_ERROR_CONNECTION_BROKEN;
+                               goto FINISH_OFF;
+                       }
+
+                       memset(tag, 0x00, sizeof(tag));
+                       memset(cmd, 0x00, sizeof(cmd));
+                       
+                       SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+                       SNPRINTF(cmd, sizeof(cmd), "%s UID STORE %s +FLAGS (\\Deleted)\015\012", tag, uid_range_node->uid_range);
+                       
+                       EM_DEBUG_LOG("[IMAP4] >>> %s", cmd);
+
+                       
+                       /* send command  :  set deleted flag */
+                       if (!net_sout(imaplocal->netstream, cmd, (int)EM_SAFE_STRLEN(cmd)))  {
+                               EM_DEBUG_EXCEPTION("net_sout failed...");
+                               
+                               err = EMAIL_ERROR_CONNECTION_BROKEN;            /* EMAIL_ERROR_UNKNOWN */
+                               goto FINISH_OFF;
+                       }
+
+                       
+                       while (imaplocal->netstream)  {
+                               /* receive response */
+                               if (!(p = net_getline(imaplocal->netstream))) {
+                                       EM_DEBUG_EXCEPTION("net_getline failed...");
+                                       
+                                       err = EMAIL_ERROR_INVALID_RESPONSE;             /* EMAIL_ERROR_UNKNOWN; */
+                                       goto FINISH_OFF;
+                               }
+                               
+
+                               EM_DEBUG_LOG("[IMAP4] <<< %s", p);
+
+                               /* To confirm - Commented out as FETCH response does not contain the tag - may be a problem for common stream in email-service*/
+                               /* Success case - delete all local activity and entry from mail_read_mail_uid_tbl 
+                               if (strstr(p, "FETCH") != NULL)  {
+                                       EM_DEBUG_LOG(" FETCH Response recieved ");
+                                       delete_success = true;
+                                       EM_SAFE_FREE(p);
+                                       break;
+                               }
+                               */
+               
+                       
+                               if (!strncmp(p, tag, EM_SAFE_STRLEN(tag)))  {
+                                       if (!strncmp(p + EM_SAFE_STRLEN(tag) + 1, "OK", 2))  {
+                                               /*Error scenario delete all local activity and entry from mail_read_mail_uid_tbl */
+                                               EM_DEBUG_LOG(" OK Response recieved ");
+                                               delete_success = true;
+                                               EM_SAFE_FREE(p);
+                                               break;
+                                       }                                       
+                                       else  {
+                                               /*  'NO' or 'BAD' */
+                                               delete_success = false;
+                                               err = EMAIL_ERROR_IMAP4_STORE_FAILURE;          /* EMAIL_ERROR_INVALID_RESPONSE; */
+                                               goto FINISH_OFF;
+                                       }
+                               }
+                       
+                               EM_SAFE_FREE(p);
+                               }
+                               
+                               memset(tag, 0x00, sizeof(tag));
+                               memset(cmd, 0x00, sizeof(cmd));
+
+                               EM_DEBUG_LOG("Calling Expunge");
+                               
+                               SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+                               SNPRINTF(cmd, sizeof(cmd), "%s EXPUNGE\015\012", tag);
+                               
+                               EM_DEBUG_LOG("[IMAP4] >>> %s", cmd);
+                               
+                               /* send command  :   EXPUNGE */
+                               if (!net_sout(imaplocal->netstream, cmd, (int)EM_SAFE_STRLEN(cmd)))  {
+                                       EM_DEBUG_EXCEPTION("net_sout failed...");
+                                       
+                                       err = EMAIL_ERROR_CONNECTION_BROKEN;
+                                       goto FINISH_OFF;
+                               }
+
+                               while (imaplocal->netstream)  {
+                                       /* receive response */
+                                       if (!(p = net_getline(imaplocal->netstream))) {
+                                               EM_DEBUG_EXCEPTION("net_getline failed...");
+                                               
+                                               err = EMAIL_ERROR_INVALID_RESPONSE;             /* EMAIL_ERROR_UNKNOWN; */
+                                               goto FINISH_OFF;
+                                       }
+                                       
+                                       EM_DEBUG_LOG("[IMAP4] <<< %s", p);
+                                       
+                                       if (!strncmp(p, tag, EM_SAFE_STRLEN(tag)))  {
+                                               if (!strncmp(p + EM_SAFE_STRLEN(tag) + 1, "OK", 2))  {
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+                                                       int index = 0;
+                                                       emstorage_mail_tbl_t **mail = NULL;
+                                                       
+                                                       mail = (emstorage_mail_tbl_t **) em_malloc(num * sizeof(emstorage_mail_tbl_t *));
+                                                       if (!mail) {
+                                                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                                                               err = EMAIL_ERROR_UNKNOWN;
+                                                               goto FINISH_OFF;
+                                                       }
+
+                                                       if (delete_success) {
+                                                               for (index = 0 ; index < num; index++) {
+                                                                       if (!emstorage_get_downloaded_mail(mail_ids[index], &mail[index], false, &err))  {
+                                                                               EM_DEBUG_LOG("emstorage_get_uid_by_mail_id failed [%d]", err);
+                                                                               
+                                                                               if (err == EMAIL_ERROR_MAIL_NOT_FOUND)  {               
+                                                                                       EM_DEBUG_LOG("EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER  : ");
+                                                                                       continue;
+                                                                               }
+                                                                       }               
+                                                               
+                                                                       if (mail[index]) {                              
+                                                                               /* Clear entry from mail_read_mail_uid_tbl */
+                                                                               if (mail[index]->server_mail_id != NULL) {
+                                                                                       if (!emstorage_remove_downloaded_mail(mail[index]->account_id, mail[index]->mailbox_name, mail[index]->server_mail_id, true, &err))  {
+                                                                                               EM_DEBUG_LOG("emstorage_remove_downloaded_mail falied [%d]", err);
+                                                                                       }
+                                                                               }
+                                                                               
+                                                                               /* Delete local activity */
+                                                                               emstorage_activity_tbl_t new_activity;
+                                                                               memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
+                                                                               if (from_server == EMAIL_DELETE_FOR_SEND_THREAD) {
+                                                                                       new_activity.activity_type = ACTIVITY_DELETEMAIL_SEND;
+                                                                                       EM_DEBUG_LOG("from_server == EMAIL_DELETE_FOR_SEND_THREAD ");
+                                                                               }
+                                                                               else {
+                                                                                       new_activity.activity_type      = ACTIVITY_DELETEMAIL;
+                                                                               }
+
+                                                                               new_activity.mail_id            = mail[index]->mail_id;
+                                                                               new_activity.server_mailid      = NULL;
+                                                                               new_activity.src_mbox           = NULL;
+                                                                               new_activity.dest_mbox          = NULL;
+                                                                                                               
+                                                                               if (!emcore_delete_activity(&new_activity, &err)) {
+                                                                                       EM_DEBUG_EXCEPTION(" emcore_delete_activity  failed  - %d ", err);
+                                                                               }
+                                                                       }
+                                                                       else {
+                                                                               /* Fix for crash seen while deleting Outbox mails which are moved to Trash. Outbox mails do not have server mail id and are not updated in mail_read_mail_uid_tbl.
+                                                                                 * So there is no need of deleting entry in mail_read_mail_uid_tbl. However local activity has to be deleted. 
+                                                                               */
+                                                                               /* Delete local activity */
+                                                                               emstorage_activity_tbl_t new_activity;
+                                                                               memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
+                                                                               new_activity.activity_type      = ACTIVITY_DELETEMAIL;
+                                                                               new_activity.mail_id            = mail_ids[index]; /* valid mail id passed for outbox mails*/
+                                                                               new_activity.server_mailid      = NULL;
+                                                                               new_activity.src_mbox           = NULL;
+                                                                               new_activity.dest_mbox          = NULL;
+                                                                                                               
+                                                                               if (!emcore_delete_activity(&new_activity, &err)) {
+                                                                                       EM_DEBUG_EXCEPTION(" emcore_delete_activity  failed  - %d ", err);
+                                                                               }
+                                                                       }
+                                                               }
+
+                                                               for (index = 0; index < num; index++) {
+                                                                       if (!emstorage_free_mail(&mail[index], 1, &err)) {
+                                                                               EM_DEBUG_EXCEPTION(" emstorage_free_mail [%d]", err);
+                                                                       }
+                                                               }
+
+                                                               EM_SAFE_FREE(mail);
+                                                       }
+
+#endif
+       EM_SAFE_FREE(p);
+                                                       break;
+                                               }
+                                               else  {         /*  'NO' or 'BAD' */
+                                                       err = EMAIL_ERROR_IMAP4_EXPUNGE_FAILURE;                /* EMAIL_ERROR_INVALID_RESPONSE; */
+                                                       goto FINISH_OFF;
+                                               }
+                                       }
+                                       
+                                       EM_SAFE_FREE(p);
+                               }
+                               uid_range_node = uid_range_node->next;
+               }       
+
+               emcore_free_uid_range_set(&uid_range_set);
+
+               EM_SAFE_FREE(id_set);
+               
+               id_set_count = 0;
+       }
+       
+       ret = true;
+
+FINISH_OFF: 
+       EM_SAFE_FREE(p);
+       
+       emcore_free_comma_separated_strings(&string_list, &string_count);
+
+       if (false == ret) {
+               emcore_free_uid_range_set(&uid_range_set);
+       }
+       
+       if (err_code) {
+               *err_code = err;
+       }
+
+       return ret;
+
+}
+
+#endif
+
+typedef enum {
+       IMAP4_CMD_EXPUNGE
+} imap4_cmd_t;
+
+static int imap4_send_command(MAILSTREAM *stream, imap4_cmd_t cmd_type, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], cmd_type[%d], err_code[%p]", stream, cmd_type, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       IMAPLOCAL *imaplocal = NULL;
+       char tag[16], cmd[64];
+       char *p = NULL;
+       
+       if (!(imaplocal = stream->local) || !imaplocal->netstream) {
+               EM_DEBUG_EXCEPTION("invalid IMAP4 stream detected...");
+               
+               err = EMAIL_ERROR_INVALID_PARAM;                /* EMAIL_ERROR_UNKNOWN */
+               goto FINISH_OFF;
+       }
+       
+       memset(tag, 0x00, sizeof(tag));
+       memset(cmd, 0x00, sizeof(cmd));
+       
+       SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+       SNPRINTF(cmd, sizeof(cmd), "%s EXPUNGE\015\012", tag);
+
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG("[IMAP4] >>> %s", cmd);
+#endif
+       
+       /*  send command  :  delete flaged mail */
+       if (!net_sout(imaplocal->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+               EM_DEBUG_EXCEPTION("net_sout failed...");
+               
+               err = EMAIL_ERROR_CONNECTION_BROKEN;
+               goto FINISH_OFF;
+       }
+       
+       while (imaplocal->netstream) {
+               /*  receive response */
+               if (!(p = net_getline(imaplocal->netstream))) {
+                       EM_DEBUG_EXCEPTION("net_getline failed...");
+                       
+                       err = EMAIL_ERROR_INVALID_RESPONSE;             /* EMAIL_ERROR_UNKNOWN; */
+                       goto FINISH_OFF;
+               }
+               
+#ifdef FEATURE_CORE_DEBUG
+               EM_DEBUG_LOG("[IMAP4] <<< %s", p);
+#endif
+               
+               if (!strncmp(p, tag, EM_SAFE_STRLEN(tag))) {
+                       if (!strncmp(p + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
+                               EM_SAFE_FREE(p);
+                               break;
+                       }
+                       else {          /*  'NO' or 'BAD' */
+                               err = EMAIL_ERROR_IMAP4_EXPUNGE_FAILURE;                /* EMAIL_ERROR_INVALID_RESPONSE; */
+                               goto FINISH_OFF;
+                       }
+               }
+               
+               EM_SAFE_FREE(p);
+       }
+       
+       ret = true;
+
+FINISH_OFF: 
+       EM_SAFE_FREE(p);
+       
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+int emcore_get_mail_contact_info(email_mail_contact_info_t *contact_info, char *full_address, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("contact_info[%p], full_address[%s], err_code[%p]", contact_info, full_address, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (!emcore_get_mail_contact_info_with_update(contact_info, full_address, 0, &err))
+               EM_DEBUG_EXCEPTION("emcore_get_mail_contact_info_with_update failed [%d]", err);
+       else
+               ret = true;
+       
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+}
+
+int emcore_search_contact_info_by_address(const char *contact_uri, int property_id, char *address, int limit, contacts_record_h *contacts_record)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int contact_err = CONTACTS_ERROR_NONE;
+       
+       contacts_query_h query = NULL;
+       contacts_filter_h filter = NULL;
+       contacts_list_h list = NULL;
+
+       if ((contact_err = contacts_query_create(contact_uri, &query)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_query_create failed");
+               goto FINISH_OFF;
+       }
+       
+       if ((contact_err = contacts_filter_create(contact_uri, &filter)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_filter_create failed");
+               goto FINISH_OFF;
+       }
+
+       if ((contact_err = contacts_filter_add_str(filter, property_id, CONTACTS_MATCH_EXACTLY, address)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_filter_add_str failed");
+               goto FINISH_OFF;
+       }
+       
+       if ((contact_err = contacts_query_set_filter(query, filter)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_query_set_filter failed");
+               goto FINISH_OFF;
+       }
+
+       if ((contact_err = contacts_db_get_records_with_query(query, 0, limit, &list)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_db_get_record_with_query failed");
+               goto FINISH_OFF;
+       }
+
+       if ((contact_err = contacts_list_get_current_record_p(list, contacts_record)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_list_get_current_record_p failed");
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if (query != NULL)
+               contacts_query_destroy(query);
+
+       if (filter != NULL)
+               contacts_filter_destroy(filter);
+
+       if (list != NULL)
+               contacts_list_destroy(list, false);
+
+       return contact_err;
+}
+
+int emcore_set_contacts_log(int account_id, char *email_address, char *subject, time_t date_time, email_action_t action)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id : [%d], address : [%p], subject : [%s], action : [%d], date_time : [%d]", account_id, email_address, subject, action, (int)date_time);
+       
+       int err = EMAIL_ERROR_NONE;
+       int contacts_error = CONTACTS_ERROR_NONE;
+       int person_id = 0;
+       int action_type = 0;
+       
+       contacts_record_h phone_record = NULL;
+       contacts_record_h person_record = NULL; 
+
+       if ((contacts_error = contacts_connect2()) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("Open connect service failed [%d]", contacts_error);
+               goto FINISH_OFF;
+       }
+
+       if ((contacts_error = contacts_record_create(_contacts_phone_log._uri, &phone_record)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_query_create failed [%d]", contacts_error);
+               goto FINISH_OFF;
+       }
+
+       /* Set email address */
+       if ((contacts_error = contacts_record_set_str(phone_record, _contacts_phone_log.address, email_address)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_record_set_str [address] failed [%d]", contacts_error);
+               goto FINISH_OFF;
+       }
+
+       /* Search contact person info */
+       if ((contacts_error = emcore_search_contact_info_by_address(_contacts_person_email._uri, _contacts_person_email.email, email_address, 1, &person_record)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed [%d]", contacts_error);
+               EM_DEBUG_LOG("Not match person");
+       } else {
+               /* Get person_id in contacts_person_email record  */
+               if (person_record  && (contacts_error = contacts_record_get_int(person_record, _contacts_person_email.person_id, &person_id)) != CONTACTS_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("contacts_record_get_str failed [%d]", contacts_error);
+                       goto FINISH_OFF;
+               }
+
+               /* Set the person id */
+               if ((contacts_error = contacts_record_set_int(phone_record, _contacts_phone_log.person_id, person_id)) != CONTACTS_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("contacts_record_set_int [person id] failed [%d]", contacts_error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       switch (action) {
+       case EMAIL_ACTION_SEND_MAIL :
+               action_type = CONTACTS_PLOG_TYPE_EMAIL_SENT;
+               break;
+       case EMAIL_ACTION_SYNC_HEADER :
+               action_type = CONTACTS_PLOG_TYPE_EMAIL_RECEIVED;
+               break;
+       default :
+               EM_DEBUG_EXCEPTION("Unknown action type");
+               goto FINISH_OFF;
+       }
+
+       /* Set log type */
+       if ((contacts_error = contacts_record_set_int(phone_record, _contacts_phone_log.log_type, action_type)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_record_set_int [log_type] failed [%d]", contacts_error);
+               goto FINISH_OFF;
+       }
+
+       /* Set log time */
+       if ((contacts_error = contacts_record_set_int(phone_record, _contacts_phone_log.log_time, (int)date_time)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_record_set_str [address] failed [%d]", contacts_error);
+               goto FINISH_OFF;
+       }
+
+       /* Set subject */
+       if ((contacts_error = contacts_record_set_str(phone_record, _contacts_phone_log.extra_data2, subject)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_record_set_str [subject] failed [%d]", contacts_error);
+               goto FINISH_OFF;
+       }
+
+       /* Set Mail id */
+       if ((contacts_error = contacts_record_set_int(phone_record, _contacts_phone_log.extra_data1, account_id)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_record_set_int [mail id] failed [%d]", contacts_error);
+               goto FINISH_OFF;
+       }
+
+       /* Insert the record in DB */
+       if ((contacts_error = contacts_db_insert_record(phone_record, NULL)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_db_insert_record failed [%d]",contacts_error );
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if (phone_record != NULL)
+               contacts_record_destroy(phone_record, false);
+
+       if (person_record != NULL)
+               contacts_record_destroy(person_record, false);
+
+       err = convert_contact_err_to_email_err(contacts_error);
+
+       if ((contacts_error = contacts_disconnect2()) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("Open connect service failed [%d]", contacts_error);
+               err = convert_contact_err_to_email_err(contacts_error);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_set_sent_contacts_log(emstorage_mail_tbl_t *input_mail_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data : [%p]", input_mail_data);
+       
+       int i = 0;
+       int err = EMAIL_ERROR_NONE;
+       char email_address[MAX_EMAIL_ADDRESS_LENGTH];
+       char *address_array[3] = {input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc};
+       ADDRESS *addr = NULL;
+       ADDRESS *p_addr = NULL;
+
+       for (i = 0; i < 3; i++) {
+               if (address_array[i] && address_array[i][0] != 0) {
+                       rfc822_parse_adrlist(&addr, address_array[i], NULL);
+                       for (p_addr = addr ; p_addr ;p_addr = p_addr->next) {
+                               SNPRINTF(email_address, MAX_EMAIL_ADDRESS_LENGTH, "%s@%s", addr->mailbox, addr->host);
+                               if ((err = emcore_set_contacts_log(input_mail_data->account_id, email_address, input_mail_data->subject, input_mail_data->date_time, EMAIL_ACTION_SEND_MAIL)) != EMAIL_ERROR_NONE) {
+                                       EM_DEBUG_EXCEPTION("emcore_set_contacts_log failed : [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+                       }
+               
+                       if (addr) {     
+                               mail_free_address(&addr);
+                               addr = NULL;
+                       }
+               }
+       }
+
+FINISH_OFF:
+
+       if (addr) 
+               mail_free_address(&addr);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_set_received_contacts_log(emstorage_mail_tbl_t *input_mail_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data : [%p]", input_mail_data);
+       int err = EMAIL_ERROR_NONE;
+
+       if ((err = emcore_set_contacts_log(input_mail_data->account_id, input_mail_data->email_address_sender, input_mail_data->subject, input_mail_data->date_time, EMAIL_ACTION_SYNC_HEADER)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_set_contacts_log failed [%d]", err);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_delete_contacts_log(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d]", account_id);
+
+       int err = EMAIL_ERROR_NONE;
+       int contacts_error = CONTACTS_ERROR_NONE;
+
+       if ((contacts_error = contacts_connect2()) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("Open connect service failed [%d]", contacts_error);
+               goto FINISH_OFF;
+       }
+       
+       /* Delete record of the account id */
+       if ((contacts_error = contacts_phone_log_delete(CONTACTS_PHONE_LOG_DELETE_BY_EMAIL_EXTRA_DATA1, account_id)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_phone_log_delete failed [%d]", contacts_error);
+       }
+       
+
+FINISH_OFF:
+       err = convert_contact_err_to_email_err(contacts_error);
+
+       if ((contacts_error = contacts_disconnect2()) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("Open connect service failed [%d]", contacts_error);
+               err = convert_contact_err_to_email_err(contacts_error);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_get_mail_display_name(char *email_address, char **contact_display_name, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("contact_name_value[%s], contact_display_name[%p]", email_address, contact_display_name);
+
+       int contact_err = 0;
+       int ret = false;
+       char *display = NULL;
+       /* Contact variable */
+       contacts_record_h record = NULL;
+
+       if ((contact_err = emcore_search_contact_info_by_address(_contacts_contact_email._uri, _contacts_contact_email.email, email_address, 1, &record)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_search_contact_info_by_address failed");
+               goto FINISH_OFF;
+       }
+/*
+       if ((contact_err = contacts_list_get_count(list, &list_count)) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_list_get_count failed");
+               goto FINISH_OFF;
+       }
+
+       if (list_count > 1) {
+               EM_DEBUG_EXCEPTION("Duplicated contacts info");
+               contact_err = CONTACTS_ERROR_INTERNAL;
+               goto FINISH_OFF;
+       } else if (list_count == 0) {
+               EM_DEBUG_EXCEPTION("Not found contact info");
+               contact_err = CONTACTS_ERROR_NO_DATA;
+               goto FINISH_OFF;
+       }
+*/
+
+       if (contacts_record_get_str(record, _contacts_contact_email.display_name, &display) != CONTACTS_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("contacts_record_get_str failed");
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (record != NULL)
+               contacts_record_destroy(record, false);
+
+       if (ret) {
+               *contact_display_name = display;
+       } else {
+               *contact_display_name = NULL;
+               EM_SAFE_FREE(display);
+       }
+
+       if (err_code != NULL)
+               *err_code = convert_contact_err_to_email_err(contact_err);
+
+       return ret;
+}
+
+int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_info, char *full_address, int mail_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("contact_info[%p], full_address[%s], mail_id[%d], err_code[%p]", contact_info, full_address, mail_id, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       ADDRESS *addr = NULL;
+       char *address = NULL;
+       char *temp_emailaddr = NULL;
+       char *alias = NULL;
+       int is_searched = false;
+       int address_length = 0;
+       char *email_address = NULL;
+       int contact_name_len = 0;
+       char temp_string[1024] = { 0 , };
+       int is_saved = 0;
+       char *contact_display_name = NULL;
+       char *contact_display_name_from_contact_info = NULL;
+       int contact_display_name_len = 0;
+       int i = 0;
+       int contact_name_buffer_size = 0;
+       char *contact_name = NULL;
+
+       if (!contact_info)  {
+               EM_DEBUG_EXCEPTION("contact_info[%p]", contact_info);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!full_address) {
+               full_address = "";
+               address_length = 0;
+               temp_emailaddr = NULL;
+       }
+       else {
+               address_length = 2 * EM_SAFE_STRLEN(full_address);
+               temp_emailaddr = (char  *)calloc(1, address_length); 
+       }
+
+       em_skip_whitespace(full_address , &address);
+       EM_DEBUG_LOG("address[address][%s]", address);  
+
+
+       /*  ',' -> "%2C" */
+       gchar **tokens = g_strsplit(address, ", ", -1);
+       char *p = g_strjoinv("%2C", tokens);
+       
+       g_strfreev(tokens);
+       
+       /*  ';' -> ',' */
+       while (p && p[i] != '\0') 
+       {
+               if (p[i] == ';') 
+                       p[i] = ',';
+               i++;
+       }
+       EM_DEBUG_LOG("  2  converted address %s ", p);
+
+       rfc822_parse_adrlist(&addr, p, NULL);
+
+       EM_SAFE_FREE(p);
+       EM_DEBUG_LOG("  3  full_address  %s ", full_address);
+
+       if (!addr) {
+               EM_DEBUG_EXCEPTION("rfc822_parse_adrlist failed...");
+               err = EMAIL_ERROR_INVALID_ADDRESS;
+               goto FINISH_OFF;
+       }
+
+       contact_name_buffer_size = address_length;
+       contact_name = (char*)em_malloc(contact_name_buffer_size);
+
+       if (!contact_name) {
+               EM_DEBUG_EXCEPTION("Memory allocation error!");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       
+       while (addr != NULL)  {
+               if (addr->mailbox && addr->host) {      
+                       if (!strncmp(addr->mailbox , "UNEXPECTED_DATA_AFTER_ADDRESS", strlen("UNEXPECTED_DATA_AFTER_ADDRESS")) || !strncmp(addr->mailbox , "INVALID_ADDRESS", strlen("INVALID_ADDRESS")) || !strncmp(addr->host , ".SYNTAX-ERROR.", strlen(".SYNTAX-ERROR.")))
+               {
+                               EM_DEBUG_LOG("Invalid address ");
+                               addr = addr->next;
+                               continue;
+                       }
+               }
+               else  {
+                       EM_DEBUG_LOG("Error in parsing..! ");
+                       addr = addr->next;
+                       continue;
+               }
+
+               EM_SAFE_FREE(email_address);
+               email_address = g_strdup_printf("%s@%s", addr->mailbox ? addr->mailbox  :  "", addr->host ? addr->host  :  "");
+               
+               EM_DEBUG_LOG(" addr->personal[%s]", addr->personal);
+               EM_DEBUG_LOG(" email_address[%s]", email_address);
+       
+               is_searched = false;
+               EM_DEBUG_LOG(" >>>>> emcore_get_mail_contact_info - 10");
+       
+               if (emcore_get_mail_display_name(email_address, &contact_display_name_from_contact_info, &err) && err == EMAIL_ERROR_NONE) {
+                       contact_display_name = contact_display_name_from_contact_info;
+
+                       EM_DEBUG_LOG(">>> contact_name[%s]", contact_display_name);
+                       /*  Make display name string */
+                       is_searched = true;
+
+                       if (mail_id == 0 || (contact_name_len == 0)) {  /*  save only the first address information - 09-SEP-2010 */
+                               contact_display_name_len = EM_SAFE_STRLEN(contact_display_name);
+                               if (contact_name_len + contact_display_name_len >= contact_name_buffer_size) {  /*  re-alloc memory */
+                                       char *temp = contact_name;
+                                       contact_name_buffer_size += contact_name_buffer_size;
+                                       contact_name = (char  *)calloc(1, contact_name_buffer_size); 
+                                       if (contact_name == NULL) {
+                                               EM_DEBUG_EXCEPTION("Memory allocation failed.");
+                                               EM_SAFE_FREE(temp);
+                                               goto FINISH_OFF;
+                                       }
+                                       snprintf(contact_name, contact_name_buffer_size, "%s", temp);
+                                       EM_SAFE_FREE(temp);
+                               }
+
+                               /* snprintf(temp_string, sizeof(temp_string), "%c%d%c%s <%s>%c", start_text_ascii, contact_index, start_text_ascii, contact_display_name, email_address, end_text_ascii); */
+                               if (addr->next == NULL) {
+                                       snprintf(temp_string, sizeof(temp_string), "\"%s\" <%s>", contact_display_name, email_address);
+                               }
+                               else {
+                                       snprintf(temp_string, sizeof(temp_string), "\"%s\" <%s>, ", contact_display_name, email_address);
+                               }                                       
+
+                               contact_display_name_len = EM_SAFE_STRLEN(temp_string);
+                               if (contact_name_len + contact_display_name_len >= contact_name_buffer_size) {  /*  re-alloc memory */
+                                       char *temp = contact_name;
+                                       contact_name_buffer_size += contact_name_buffer_size;
+                                       contact_name = (char  *)calloc(1, contact_name_buffer_size); 
+                                       if (contact_name == NULL) {
+                                               EM_DEBUG_EXCEPTION("Memory allocation failed.");
+                                               EM_SAFE_FREE(temp);
+                                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                               goto FINISH_OFF;
+                                       }
+                                       snprintf(contact_name, contact_name_buffer_size, "%s", temp);
+                                       EM_SAFE_FREE(temp);
+                               }
+                               snprintf(contact_name + contact_name_len, contact_name_buffer_size - contact_name_len, "%s", temp_string);
+                               contact_name_len += contact_display_name_len;
+                               EM_DEBUG_LOG("new contact_name >>>>> %s ", contact_name);
+                       }
+               }
+               else {
+                       EM_DEBUG_LOG("emcore_get_mail_display_name - Not found contact record(if err is 203) or error [%d]", err);
+               }
+
+               /*  if contact doesn't exist, use alias or email address as display name */
+               if (addr->personal != NULL) {
+                       /*  "%2C" -> ',' */
+                       tokens = g_strsplit(addr->personal, "%2C", -1);
+                       
+                       EM_SAFE_FREE(addr->personal);
+                       
+                       addr->personal = g_strjoinv(", ", tokens);
+                       
+                       g_strfreev(tokens);
+                       /* contact_info->contact_name = EM_SAFE_STRDUP(addr->personal); */
+                       alias = addr->personal;
+               }
+               else {
+                       /* alias = addr->mailbox ? addr->mailbox  :  ""; */
+                       alias = email_address;
+               }
+               contact_info->alias = EM_SAFE_STRDUP(alias);
+
+               if (!is_searched) {
+                       contact_display_name = alias;
+                       contact_info->contact_id = -1;          /*  NOTE :  This is valid only if there is only one address. */
+                       contact_info->storage_type = -1;
+
+                       /*  Make display name string */
+                       EM_DEBUG_LOG("contact_display_name : [%s]", contact_display_name);
+                       EM_DEBUG_LOG("email_address : [%s]", email_address);
+
+                       /*  if mail_id is 0, return only contact info without saving contact info to DB */
+                       if (mail_id == 0 || (contact_name_len == 0))             {      /*  save only the first address information - 09-SEP-2010 */
+                               /* snprintf(temp_string, sizeof(temp_string), "%c%d%c%s <%s>%c", start_text_ascii, contact_index, start_text_ascii, contact_display_name, email_address, end_text_ascii); */
+                               if (addr->next == NULL) {
+                                       snprintf(temp_string, sizeof(temp_string), "\"%s\" <%s>", contact_display_name, email_address);
+                               }
+                               else {
+                                       snprintf(temp_string, sizeof(temp_string), "\"%s\" <%s>, ", contact_display_name, email_address);
+                               }
+                               EM_DEBUG_LOG("temp_string[%s]", temp_string);
+
+                               contact_display_name_len = EM_SAFE_STRLEN(temp_string);
+                               if (contact_name_len + contact_display_name_len >= contact_name_buffer_size) {  /*  re-alloc memory */
+                                       char *temp = contact_name;
+                                       contact_name_buffer_size += contact_name_buffer_size;
+                                       contact_name = (char  *)calloc(1, contact_name_buffer_size); 
+                                       if (contact_name == NULL) {
+                                               EM_DEBUG_EXCEPTION("Memory allocation failed.");
+                                               EM_SAFE_FREE(temp);
+                                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                               goto FINISH_OFF;
+                                       }
+                                       snprintf(contact_name, contact_name_buffer_size, "%s", temp);
+                                       EM_SAFE_FREE(temp);
+                               }
+                               
+                               snprintf(contact_name + contact_name_len, contact_name_buffer_size - contact_name_len, "%s", temp_string);
+                               contact_name_len += contact_display_name_len;
+                               EM_DEBUG_LOG("new contact_name >>>>> %s ", contact_name);
+                       }
+               }
+
+               if (temp_emailaddr && email_address) {  
+                       if (mail_id == 0) {     /*  if mail_id is 0, return only contact info without saving contact info to DB */
+                               /* snprintf(temp_emailaddr, 400, "%s", contact_info->email_address); */
+                               EM_SAFE_STRCAT(temp_emailaddr, email_address);
+                               if (addr->next != NULL)
+                                       EM_SAFE_STRCAT(temp_emailaddr, ", ");
+                               EM_DEBUG_LOG(">>>> TEMP EMail Address [ %s ] ", temp_emailaddr);
+                       }
+                       else {  /*  save only the first address information - 09-SEP-2010 */
+                               if (is_saved == 0) {
+                                       is_saved = 1;
+                                       /* snprintf(temp_emailaddr, 400, "%s", contact_info->email_address); */
+                                       EM_SAFE_STRCAT(temp_emailaddr, email_address);
+                                       /*
+                                       if (addr->next != NULL)
+                                               EM_SAFE_STRCAT(temp_emailaddr, ", ");
+                                       */
+                                       EM_DEBUG_LOG(">>>> TEMP EMail Address [ %s ] ", temp_emailaddr);
+                               }
+                       }
+               }
+
+               EM_SAFE_FREE(contact_display_name_from_contact_info);
+               /*  next address */
+               addr = addr->next;
+       } /*  while (addr != NULL) */
+
+       if (temp_emailaddr) {
+               EM_DEBUG_LOG(">>>> TEMPEMAIL ADDR [ %s ] ", temp_emailaddr);
+               contact_info->email_address = temp_emailaddr;
+               temp_emailaddr = NULL;
+       }
+
+
+       contact_info->contact_name = g_strdup(contact_name); /*prevent 40020*/
+
+       ret = true;
+       
+FINISH_OFF: 
+
+       EM_SAFE_FREE(email_address);
+       EM_SAFE_FREE(address);
+       EM_SAFE_FREE(temp_emailaddr);
+       EM_SAFE_FREE(contact_name);             
+       EM_SAFE_FREE(contact_display_name_from_contact_info);
+       
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+}
+
+int emcore_free_contact_info(email_mail_contact_info_t *contact_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("contact_info[%p], err_code[%p]", contact_info, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (!contact_info)  {
+               EM_DEBUG_EXCEPTION("contact_info[%p]", contact_info);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       EM_SAFE_FREE(contact_info->contact_name);
+       EM_SAFE_FREE(contact_info->email_address);
+       EM_SAFE_FREE(contact_info->alias);
+       
+       contact_info->storage_type = -1;
+       contact_info->contact_id = -1;
+       
+       ret = true;
+       
+FINISH_OFF: 
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emcore_sync_contact_info(int mail_id, int *err_code)
+{
+       EM_PROFILE_BEGIN(emCoreMailContactSync);
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       emstorage_mail_tbl_t *mail = NULL;
+
+       email_mail_contact_info_t contact_info_from;
+       email_mail_contact_info_t contact_info_to;
+       email_mail_contact_info_t contact_info_cc;
+       email_mail_contact_info_t contact_info_bcc;
+       
+       EM_DEBUG_LOG("mail_id[%d], err_code[%p]", mail_id, err_code);
+       
+       memset(&contact_info_from, 0x00, sizeof(email_mail_contact_info_t));    
+       memset(&contact_info_to, 0x00, sizeof(email_mail_contact_info_t));
+       memset(&contact_info_cc, 0x00, sizeof(email_mail_contact_info_t));
+       memset(&contact_info_bcc, 0x00, sizeof(email_mail_contact_info_t));     
+
+       if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if (mail->full_address_from != NULL) {
+               if (!emcore_get_mail_contact_info_with_update(&contact_info_from, mail->full_address_from, mail_id, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_contact_info failed [%d]", err);
+               }
+       }
+
+       if (mail->full_address_to != NULL)  {
+               if (!emcore_get_mail_contact_info_with_update(&contact_info_to, mail->full_address_to, mail_id, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_contact_info failed [%d]", err);
+               }
+       }
+
+       if (mail->full_address_cc != NULL)  {
+               if (!emcore_get_mail_contact_info_with_update(&contact_info_cc, mail->full_address_cc, mail_id, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_contact_info failed [%d]", err);
+               }
+       }
+
+       if (mail->full_address_bcc != NULL)  {
+               if (!emcore_get_mail_contact_info_with_update(&contact_info_bcc, mail->full_address_bcc, mail_id, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_contact_info failed [%d]", err);
+               }
+       }       
+
+       EM_SAFE_FREE(mail->email_address_sender);
+       mail->email_address_sender = contact_info_from.email_address;
+       contact_info_from.contact_name = NULL;
+       contact_info_from.email_address = NULL;
+       EM_SAFE_FREE(mail->email_address_recipient);
+       if (mail->full_address_to != NULL) {
+               mail->email_address_recipient = contact_info_to.email_address;
+               contact_info_to.contact_name = NULL;
+               contact_info_to.email_address = NULL;
+       }
+       else if (mail->full_address_cc != NULL) {
+               mail->email_address_recipient = contact_info_cc.email_address;
+               contact_info_cc.contact_name = NULL;
+               contact_info_cc.email_address = NULL;
+       }
+       else if (mail->full_address_bcc != NULL) {
+               mail->email_address_recipient = contact_info_bcc.email_address;
+               contact_info_bcc.contact_name  = NULL;
+               contact_info_bcc.email_address = NULL;
+       }
+       
+       /*  Update DB */
+       if (!emstorage_change_mail_field(mail_id, UPDATE_ALL_CONTACT_INFO, mail, false, &err))  {                                       
+               EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
+
+               goto FINISH_OFF;
+       }       
+
+       ret = true;
+
+FINISH_OFF: 
+       if (mail != NULL)
+               emstorage_free_mail(&mail, 1, NULL);
+
+       emcore_free_contact_info(&contact_info_from, NULL);
+       emcore_free_contact_info(&contact_info_to, NULL);
+       emcore_free_contact_info(&contact_info_cc, NULL);
+       emcore_free_contact_info(&contact_info_bcc, NULL);      
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_PROFILE_END(emCoreMailContactSync);
+       return ret;
+}
+
+/*  1. parsing  :  alias and address */
+/*  2. sync with contact */
+/*  3. make glist of address info */
+static int emcore_sync_address_info(email_address_type_t address_type, char *full_address, GList **address_info_list, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("address type[%d], address_info_list[%p], full_address[%p]", address_type, address_info_list, full_address);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int contact_index = -1;
+       int is_search = false;
+       char *alias = NULL;
+       char *address = NULL;
+       char *contact_display_name_from_contact_info = NULL;
+       char email_address[MAX_EMAIL_ADDRESS_LENGTH];
+       email_address_info_t *p_address_info = NULL;
+       ADDRESS *addr = NULL;
+       
+       if (address_info_list == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid param : address_info_list is NULL");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /*  Parsing */
+       address = EM_SAFE_STRDUP(full_address);
+
+       /*  ',' -> "%2C" */
+       gchar **tokens = g_strsplit(address, ", ", -1);
+       char *p = g_strjoinv("%2C", tokens);
+       int i = 0;
+       
+       g_strfreev(tokens);
+       
+       /*  ';' -> ',' */
+       while (p && p[i] != '\0')  {
+               if (p[i] == ';') 
+                       p[i] = ',';
+               i++;
+       }
+
+       rfc822_parse_adrlist(&addr, p, NULL);
+
+       EM_SAFE_FREE(p);        
+
+       if (!addr)  {
+               EM_DEBUG_EXCEPTION("rfc822_parse_adrlist failed...");
+               error = EMAIL_ERROR_INVALID_PARAM;              
+               goto FINISH_OFF;
+       }
+
+       /*  Get a contact name */
+       while (addr != NULL)  {
+               if (addr->mailbox && addr->host) {      
+                       if (!strcmp(addr->mailbox , "UNEXPECTED_DATA_AFTER_ADDRESS") || !strcmp(addr->mailbox , "INVALID_ADDRESS") || !strcmp(addr->host , ".SYNTAX-ERROR.")) {
+                               EM_DEBUG_LOG("Invalid address ");
+                               addr = addr->next;
+                               continue;
+                       }
+               }
+               else  {
+                       EM_DEBUG_LOG("Error in parsing..! ");
+                       addr = addr->next;
+                       continue;
+               }
+
+               /*   set display name  */
+               /*    1) contact name */
+               /*    2) alias (if a alias in an original mail doesn't exist, this field is set with email address */
+               /*    3) email address   */
+
+               if (!(p_address_info = (email_address_info_t *)malloc(sizeof(email_address_info_t)))) {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }       
+               memset(p_address_info, 0x00, sizeof(email_address_info_t)); 
+
+               SNPRINTF(email_address, MAX_EMAIL_ADDRESS_LENGTH, "%s@%s", addr->mailbox ? addr->mailbox  :  "", addr->host ? addr->host  :  "");
+               EM_DEBUG_LOG("Search a contact  :  address[%s]", email_address);
+
+               is_search = false;
+
+               if (emcore_get_mail_display_name(email_address, &contact_display_name_from_contact_info, &error) && error == EMAIL_ERROR_NONE) {
+                       EM_DEBUG_LOG(">>> contact display name[%s]", contact_display_name_from_contact_info);
+
+                       is_search = true;
+               }
+               else
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_display_name - Not found contact record(if err is -203) or error [%d]", error);
+
+               if (is_search == true) {
+                       p_address_info->contact_id = contact_index;             
+                       p_address_info->storage_type = -1;                              
+                       p_address_info->display_name = contact_display_name_from_contact_info;
+                       EM_DEBUG_LOG("display_name from contact[%s]", p_address_info->display_name);
+               }
+               else {
+                       /*  if contact doesn't exist, use alias or email address as display name */
+                       if (addr->personal != NULL) {
+                               /*  "%2C" -> ',' */
+                               tokens = g_strsplit(addr->personal, "%2C", -1);
+                               
+                               EM_SAFE_FREE(addr->personal);
+                               
+                               addr->personal = g_strjoinv(", ", tokens);
+                               
+                               g_strfreev(tokens);
+                               alias = addr->personal;
+                       }
+                       else {
+                               alias = NULL;
+                       }               
+                       p_address_info->contact_id = -1;
+                       p_address_info->storage_type = -1;      
+                       /*  Use an alias or an email address as a display name */
+                       if (alias == NULL)
+                               p_address_info->display_name = EM_SAFE_STRDUP(email_address);
+                       else
+                               p_address_info->display_name = EM_SAFE_STRDUP(alias);
+
+                       EM_DEBUG_LOG("display_name from email [%s]", p_address_info->display_name);
+               }
+               
+               p_address_info->address = EM_SAFE_STRDUP(email_address);
+               p_address_info->address_type = address_type;
+
+               EM_DEBUG_LOG("email address[%s]", p_address_info->address);
+
+               *address_info_list = g_list_append(*address_info_list, p_address_info);
+               p_address_info = NULL;
+
+               EM_DEBUG_LOG("after append");
+
+               alias = NULL;
+
+               EM_DEBUG_LOG("next address[%p]", addr->next);
+
+               /*  next address */
+               addr = addr->next;
+       }
+
+       ret = true;
+       
+FINISH_OFF: 
+
+       EM_SAFE_FREE(address);
+       
+       if (err_code != NULL)
+               *err_code = error;      
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+static gint address_compare(gconstpointer a, gconstpointer b)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       email_sender_list_t *recipients_list1 = (email_sender_list_t *)a;
+       email_sender_list_t *recipients_list2 = (email_sender_list_t *)b;       
+
+       EM_DEBUG_FUNC_END();    
+       return strcmp(recipients_list1->address, recipients_list2->address);
+}
+
+INTERNAL_FUNC GList *emcore_get_recipients_list(GList *old_recipients_list, char *full_address, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int i = 0, err = EMAIL_ERROR_NONE;
+       int is_search = false;
+       char *address = NULL;
+       char email_address[MAX_EMAIL_ADDRESS_LENGTH];
+       char *display_name = NULL;
+       char *alias = NULL;
+       ADDRESS *addr = NULL;
+       GList *new_recipients_list = old_recipients_list;
+       GList *recipients_list;
+
+       email_sender_list_t *temp_recipients_list = NULL;
+       email_sender_list_t *old_recipients_list_t = NULL;
+       
+       if (full_address == NULL || EM_SAFE_STRLEN(full_address) == 0) {
+               EM_DEBUG_EXCEPTION("Invalid param : full_address NULL or empty");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       address = EM_SAFE_STRDUP(full_address);
+
+       gchar **tokens = g_strsplit(address, ", ", -1);
+       char *p = g_strjoinv("%2C", tokens);
+
+       g_strfreev(tokens);
+
+       while (p && p[i] != '\0') {
+               if (p[i] == ';') 
+                       p[i] = ',';
+               i++;
+       }
+
+       rfc822_parse_adrlist(&addr, p, NULL);
+
+       EM_SAFE_FREE(p);
+
+       if (!addr) {
+               EM_DEBUG_EXCEPTION("rfc822_parse_adrlist failed...");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       while (addr != NULL) {
+               if (addr->mailbox && addr->host) {
+                       if (!strcmp(addr->mailbox , "UNEXPECTED_DATA_AFTER_ADDRESS") || !strcmp(addr->mailbox , "INVALID_ADDRESS") || !strcmp(addr->host , ".SYNTAX-ERROR.")) {
+                               EM_DEBUG_LOG("Invalid address ");
+                               addr = addr->next;
+                               continue;
+                       } 
+               } else {
+                       EM_DEBUG_LOG("Error in parsing..! ");
+                       addr = addr->next;
+                       continue;
+               }                       
+       
+               if ((temp_recipients_list = g_new0(email_sender_list_t, 1)) == NULL) {
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               
+               SNPRINTF(email_address, MAX_EMAIL_ADDRESS_LENGTH, "%s@%s", addr->mailbox ? addr->mailbox : "", addr->host ? addr->host : "");
+
+               EM_DEBUG_LOG("Search a contact : address[%s]", email_address);
+
+               if (emcore_get_mail_display_name(email_address, &display_name, &err) && err == EMAIL_ERROR_NONE) {
+                       EM_DEBUG_LOG(">>> contact display name[%s]", display_name);
+                       is_search = true;
+               } else {
+                       EM_DEBUG_LOG("emcore_get_mail_display_name - Not found contact record(if err is -203) or error [%d]", err);
+               }
+
+               if (is_search) {
+                       temp_recipients_list->display_name = display_name;
+                       EM_DEBUG_LOG("display_name from contact[%s]", temp_recipients_list->display_name);
+               } else {
+                       if (addr->personal != NULL) {
+                               tokens = g_strsplit(addr->personal, "%2C", -1);
+                               EM_SAFE_FREE(addr->personal);
+                               addr->personal = g_strjoinv(", ", tokens);
+                               g_strfreev(tokens);
+                               alias = addr->personal;
+                       } else {
+                               alias = NULL;
+                       }
+
+                       if (alias == NULL)
+                               temp_recipients_list->display_name = EM_SAFE_STRDUP(email_address);
+                       else
+                               temp_recipients_list->display_name = EM_SAFE_STRDUP(alias);
+
+                       EM_DEBUG_LOG("display_name from contact[%s]", temp_recipients_list->display_name);
+               }
+
+               temp_recipients_list->address = EM_SAFE_STRDUP(email_address);
+               EM_DEBUG_LOG("email address[%s]", temp_recipients_list->address);
+
+               EM_SAFE_FREE(display_name);
+               EM_DEBUG_LOG("next address[%p]", addr->next);
+
+               recipients_list = g_list_first(new_recipients_list);
+               while (recipients_list != NULL) {
+                       old_recipients_list_t = (email_sender_list_t *)recipients_list->data;
+                       if (!strcmp(old_recipients_list_t->address, temp_recipients_list->address)) {
+                               old_recipients_list_t->total_count = old_recipients_list_t->total_count + 1;
+                               g_free(temp_recipients_list);
+                               goto FINISH_OFF;
+                       }
+                       recipients_list = g_list_next(recipients_list);
+               }
+
+               new_recipients_list = g_list_insert_sorted(new_recipients_list, temp_recipients_list, address_compare);
+
+               g_free(temp_recipients_list);
+               temp_recipients_list = NULL;
+
+               alias = NULL;
+               addr = addr->next;
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(address);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return new_recipients_list;                     
+}
+
+INTERNAL_FUNC int emcore_get_mail_address_info_list(int mail_id, email_address_info_list_t **address_info_list, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], address_info_list[%p]", mail_id, address_info_list);
+
+       int ret = false, err = EMAIL_ERROR_NONE;
+       int failed = true;
+       int contact_error;
+
+       emstorage_mail_tbl_t *mail = NULL;
+       email_address_info_list_t *p_address_info_list = NULL;
+
+       if (mail_id <= 0 || !address_info_list) {
+               EM_DEBUG_EXCEPTION("mail_id[%d], address_info_list[%p]", mail_id, address_info_list);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       /* get mail from mail table */
+       if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+               
+
+               goto FINISH_OFF;
+       }
+
+       if (!(p_address_info_list = (email_address_info_list_t *)malloc(sizeof(email_address_info_list_t)))) {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }       
+       memset(p_address_info_list, 0x00, sizeof(email_address_info_list_t));   
+
+       if ((contact_error = contacts_connect2()) == CONTACTS_ERROR_NONE)        {              
+               EM_DEBUG_LOG("Open Contact Service Success");   
+       }       
+       else     {              
+               EM_DEBUG_EXCEPTION("contact_db_service_connect failed [%d]", contact_error);            
+               err = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (mail->full_address_from && emcore_sync_address_info(EMAIL_ADDRESS_TYPE_FROM, mail->full_address_from, &p_address_info_list->from, &err))
+               failed = false;
+       if (mail->full_address_to && emcore_sync_address_info(EMAIL_ADDRESS_TYPE_TO, mail->full_address_to, &p_address_info_list->to, &err))
+               failed = false;
+       if (mail->full_address_cc && emcore_sync_address_info(EMAIL_ADDRESS_TYPE_CC, mail->full_address_cc, &p_address_info_list->cc, &err))
+               failed = false;
+       if (mail->full_address_bcc && emcore_sync_address_info(EMAIL_ADDRESS_TYPE_BCC, mail->full_address_bcc, &p_address_info_list->bcc, &err))
+               failed = false;
+
+       if ((contact_error = contacts_disconnect2()) == CONTACTS_ERROR_NONE)
+               EM_DEBUG_LOG("Close Contact Service Success");
+       else
+               EM_DEBUG_EXCEPTION("Close Contact Service Fail [%d]", contact_error);
+
+       if (failed == false)
+               ret = true;
+
+FINISH_OFF: 
+       if (ret == true) 
+               *address_info_list = p_address_info_list;
+       else if (p_address_info_list != NULL)
+               emstorage_free_address_info_list(&p_address_info_list);
+
+       emstorage_free_mail(&mail, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+/* description
+ *    get a mail data
+ * arguments  
+ *    input_mail_id     : [in]  mail id
+ *    output_mail_data  : [out] double pointer to hold mail data.
+ * return  
+ *    succeed  :  EMAIL_ERROR_NONE
+ *    fail     :  error code
+ */
+INTERNAL_FUNC int emcore_get_mail_data(int input_mail_id, email_mail_data_t **output_mail_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], output_mail_data[%p]", input_mail_id, output_mail_data);
+       
+       int             error = EMAIL_ERROR_NONE;
+       int             result_mail_count = 0;
+       char            conditional_clause_string[QUERY_SIZE] = { 0, };
+       emstorage_mail_tbl_t *result_mail_tbl = NULL;
+       
+       if (input_mail_id == 0 || !output_mail_data)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(conditional_clause_string, QUERY_SIZE, "WHERE mail_id = %d", input_mail_id);
+       
+       if(!emstorage_query_mail_tbl(conditional_clause_string, true, &result_mail_tbl, &result_mail_count, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_tbl falied [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       if(!em_convert_mail_tbl_to_mail_data(result_mail_tbl, 1, output_mail_data, &error)) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_tbl_to_mail_data falied [%d]", error);
+               goto FINISH_OFF;
+       }
+       
+FINISH_OFF: 
+       if (result_mail_tbl)
+               emstorage_free_mail(&result_mail_tbl, result_mail_count, NULL);
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+
+/* internal function */
+void emcore_free_body_sharep(void **p)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_SAFE_FREE(*p);
+       EM_DEBUG_FUNC_END();
+}
+
+int emcore_check_drm(emstorage_attachment_tbl_t *input_attachment_tb_data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = 0;
+#ifdef __FEATURE_DRM__
+       drm_bool_type_e drm_file = DRM_UNKNOWN;
+       drm_file_info_s drm_file_info; 
+
+       if (input_attachment_tb_data == NULL)
+               return ret;
+
+       ret = drm_is_drm_file(input_attachment_tb_data->attachment_path, &drm_file);
+
+       if (ret == DRM_RETURN_SUCCESS && drm_file == DRM_TRUE) {
+               if (drm_get_file_info (input_attachment_tb_data->attachment_path, &drm_file_info) == DRM_RETURN_SUCCESS) {
+                       input_attachment_tb_data->attachment_drm_type = 0;
+                       EM_DEBUG_LOG ("fileInfo is [%d]", drm_file_info.oma_info.method);
+                       if (drm_file_info.oma_info.method != DRM_METHOD_TYPE_UNDEFINED) {
+                               input_attachment_tb_data->attachment_drm_type = drm_file_info.oma_info.method;
+                               ret = 1;
+                       }
+               }
+       }
+       else {
+               EM_DEBUG_LOG("not DRM file %s", input_attachment_tb_data->attachment_path);
+               input_attachment_tb_data->attachment_drm_type = 0;
+               ret = 0;
+       }
+#endif
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+/* description
+ *    get mail attachment from local mailbox
+ * arguments  
+ *    mailbox  :  server mailbox
+ *    mail_id  :  mai id to own attachment
+ *    attachment  :  the number string to be downloaded
+ *    callback  :  function callback. if NULL, ignored.
+ * return  
+ *     succeed  :  1
+ *     fail  :  0
+ */
+INTERNAL_FUNC int emcore_get_attachment_info(int attachment_id, email_attachment_data_t **attachment, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_id[%d], attachment[%p], err_code[%p]", attachment_id, attachment, err_code);
+
+       if (attachment == NULL || attachment_id == 0)  {
+               EM_DEBUG_EXCEPTION("attachment_id[%d], attachment[%p]", attachment_id, attachment);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_attachment_tbl_t *attachment_tbl = NULL;
+       
+       /* get attachment from attachment tbl */
+       if (!emstorage_get_attachment(attachment_id, &attachment_tbl, true, &err) || !attachment_tbl)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+       
+       *attachment = em_malloc(sizeof(email_attachment_data_t));
+       if (!*attachment)  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       
+       (*attachment)->attachment_id = attachment_id;
+       (*attachment)->attachment_name = attachment_tbl->attachment_name; attachment_tbl->attachment_name = NULL;
+       (*attachment)->attachment_size = attachment_tbl->attachment_size;
+       (*attachment)->save_status = attachment_tbl->attachment_save_status;
+       (*attachment)->attachment_path = attachment_tbl->attachment_path; attachment_tbl->attachment_path = NULL;
+       (*attachment)->drm_status = attachment_tbl->attachment_drm_type;
+       (*attachment)->inline_content_status = attachment_tbl->attachment_inline_content_status;
+
+       ret = true;
+
+FINISH_OFF: 
+       if (attachment_tbl)
+               emstorage_free_attachment(&attachment_tbl, 1, NULL);
+
+       if (err_code)
+               *err_code = err;
+       
+       return ret;
+}
+
+/* description
+ *    get mail attachment
+ * arguments  
+ *    input_mail_id           :  mail id to own attachment
+ *    output_attachment_data  :  result attahchment data
+ *    output_attachment_count :  result attahchment count
+ * return  
+ *     succeed : EMAIL_ERROR_NONE
+ *     fail    : error code
+ */
+INTERNAL_FUNC int emcore_get_attachment_data_list(int input_mail_id, email_attachment_data_t **output_attachment_data, int *output_attachment_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], output_attachment_data[%p], output_attachment_count[%p]", input_mail_id, output_attachment_data, output_attachment_count);
+       
+       if (input_mail_id == 0|| output_attachment_data == NULL || output_attachment_count == NULL)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int                        i = 0;
+       int                        err = EMAIL_ERROR_NONE;
+       int                        attachment_tbl_count = 0;
+       emstorage_attachment_tbl_t *attachment_tbl_list = NULL;
+       email_attachment_data_t     *temp_attachment_data = NULL;
+       
+       /* get attachment from attachment tbl */
+       if ( (err = emstorage_get_attachment_list(input_mail_id, true, &attachment_tbl_list, &attachment_tbl_count)) != EMAIL_ERROR_NONE ){
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       } 
+
+       if (attachment_tbl_count)  {
+               EM_DEBUG_LOG("attchment count %d", attachment_tbl_count);
+
+               *output_attachment_data = em_malloc(sizeof(email_attachment_data_t) * attachment_tbl_count);
+
+               if(*output_attachment_data == NULL) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               for (i = 0; i < attachment_tbl_count; i++)  {
+                       temp_attachment_data = (*output_attachment_data) + i;
+
+                       temp_attachment_data->attachment_id         = attachment_tbl_list[i].attachment_id;
+                       temp_attachment_data->attachment_name       = attachment_tbl_list[i].attachment_name; attachment_tbl_list[i].attachment_name = NULL;
+                       temp_attachment_data->attachment_path       = attachment_tbl_list[i].attachment_path; attachment_tbl_list[i].attachment_path = NULL;
+                       temp_attachment_data->attachment_size       = attachment_tbl_list[i].attachment_size;
+                       temp_attachment_data->mail_id               = attachment_tbl_list[i].mail_id;
+                       temp_attachment_data->account_id            = attachment_tbl_list[i].account_id;
+                       temp_attachment_data->mailbox_id            = attachment_tbl_list[i].mailbox_id;
+                       temp_attachment_data->save_status           = attachment_tbl_list[i].attachment_save_status;
+                       temp_attachment_data->drm_status            = attachment_tbl_list[i].attachment_drm_type;
+                       temp_attachment_data->inline_content_status = attachment_tbl_list[i].attachment_inline_content_status;
+               }
+       }
+       
+FINISH_OFF: 
+       
+       *output_attachment_count = attachment_tbl_count;
+
+       if (attachment_tbl_list)
+               emstorage_free_attachment(&attachment_tbl_list, attachment_tbl_count, NULL);
+       
+       return err;
+}
+
+
+INTERNAL_FUNC int emcore_download_attachment(int account_id, int mail_id, int nth, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], nth[%d], err_code[%p]", account_id, mail_id, nth, err_code);
+
+       int err = EMAIL_ERROR_NONE;
+
+       if (mail_id < 1)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+
+               if (err_code != NULL)
+                       *err_code = err;
+
+               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FAIL, mail_id, 0, nth, err);
+               return false;
+       }
+
+       int ret = false;
+       int status = EMAIL_DOWNLOAD_FAIL;
+       MAILSTREAM *stream = NULL;
+       BODY *mbody = NULL;
+       emstorage_mail_tbl_t *mail = NULL;
+       emstorage_attachment_tbl_t *attachment = NULL;
+       struct attachment_info *ai = NULL;
+       struct _m_content_info *cnt_info = NULL;
+       void *tmp_stream = NULL;
+       char *s_uid = NULL, buf[1024];
+       int msg_no = 0;
+       emstorage_attachment_tbl_t *attachment_list = NULL;
+       int current_attachment_no = 0;
+       int attachment_count_to_be_downloaded = 0;              /*  how many attachments should be downloaded */
+       int i = 0;
+       int server_mbox_id = 0;
+
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       
+       only_body_download = false;
+       
+       /*  get mail from mail table. */
+       if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if (!mail->server_mail_status)  {
+               EM_DEBUG_EXCEPTION("not synchronous mail...");
+               err = EMAIL_ERROR_INVALID_MAIL;
+               goto FINISH_OFF;
+       }
+       
+       if (nth == 0) { /*  download all attachments, nth starts from 1, not zero */
+               /*  get attachment list from db */
+               attachment_count_to_be_downloaded = EMAIL_ATTACHMENT_MAX_COUNT;
+               if ( (err = emstorage_get_attachment_list(mail_id, true, &attachment_list, &attachment_count_to_be_downloaded)) != EMAIL_ERROR_NONE ){
+                       EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+       }
+       else {  /*  download only nth attachment */
+               attachment_count_to_be_downloaded = 1;
+               if (!emstorage_get_attachment_nth(mail_id, nth, &attachment_list, true, &err) || !attachment_list)  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_attachment_nth failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+       }
+       
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       
+       account_id              = mail->account_id;
+       s_uid                   = EM_SAFE_STRDUP(mail->server_mail_id);
+       server_mbox_id  = mail->mailbox_id;
+
+       /*  open mail server. */
+       if (!emcore_connect_to_remote_mailbox(account_id, server_mbox_id, (void **)&tmp_stream, &err) || !tmp_stream)  {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               if(err == EMAIL_ERROR_NO_SUCH_HOST)
+                       err = EMAIL_ERROR_CONNECTION_FAILURE;
+               status = EMAIL_DOWNLOAD_CONNECTION_FAIL;
+               goto FINISH_OFF;
+       }
+       
+       stream = (MAILSTREAM *)tmp_stream;
+       
+       for (i = 0; i < attachment_count_to_be_downloaded; i++) {
+               EM_DEBUG_LOG(" >>>>>> Attachment Downloading [%d / %d] start", i + 1, attachment_count_to_be_downloaded);
+
+               attachment = attachment_list + i;
+               if (nth == 0)                                   /*  download all attachments, nth starts from 1, not zero */
+                       current_attachment_no = i + 1;                  /*  attachment no */
+               else                                                                            /*  download only nth attachment */
+                       current_attachment_no = nth;    /*  attachment no */
+
+               if (!emcore_check_thread_status())  {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+               
+               if (!(cnt_info = em_malloc(sizeof(struct _m_content_info))))  {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               
+               cnt_info->grab_type = GRAB_TYPE_ATTACHMENT;     /*  attachment */
+               cnt_info->file_no   = current_attachment_no;    /*  attachment no */
+
+#ifdef CHANGE_HTML_BODY_TO_ATTACHMENT
+               /*  text/html be changed to attachment, this isn't real attachment in RFC822. */
+               if (html_changed)
+                       cnt_info->file_no--;
+#endif
+
+               /*  set sparep(member of BODY) memory free function. */
+               mail_parameters(stream, SET_FREEBODYSPAREP, emcore_free_body_sharep);
+               
+               if (!emcore_check_thread_status()) {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               msg_no = s_uid? atoi(s_uid): 0;
+
+               /*  get body structure. */
+               /*  don't free mbody because mbody is freed in closing mail_stream. */
+               if ((!stream) || emcore_get_body_structure(stream, msg_no, &mbody, &err) < 0)  {
+                       EM_DEBUG_EXCEPTION("emcore_get_body_structure failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_check_thread_status())  {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               /*  set body fetch section. */
+               if (emcore_set_fetch_body_section(mbody, false, NULL,  &err) < 0) {
+                       EM_DEBUG_EXCEPTION("emcore_set_fetch_body_section failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       
+               /*  download attachment. */
+               _imap4_received_body_size = 0;
+               _imap4_last_notified_body_size = 0;
+               _imap4_total_body_size = 0;                                     /*  This will be assigned in imap_mail_write_body_to_file() */
+               _imap4_download_noti_interval_value = 0;        /*  This will be assigned in imap_mail_write_body_to_file() */
+
+               EM_DEBUG_LOG("cnt_info->file_no[%d], current_attachment_no[%d]", cnt_info->file_no, current_attachment_no);
+               if (emcore_get_body(stream, account_id, mail_id, msg_no, mbody, cnt_info, &err) < 0)  {
+                       EM_DEBUG_EXCEPTION("emcore_get_body failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_check_thread_status())  {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               /*  select target attachment information. */
+               for (ai = cnt_info->file ; ai; ai = ai->next) {
+                       EM_DEBUG_LOG("[in loop] name[%s] save[%s] no[%d]", ai->save, ai->name, cnt_info->file_no);
+                       if (--cnt_info->file_no == 0)
+                               break;
+               }
+
+               EM_DEBUG_LOG("selected cnt_info->file_no = %d, ai = %p", cnt_info->file_no, ai);
+               
+               if (cnt_info->file_no == 0 && ai) {
+                       /*  rename temporary file to real file. */
+                       if (!emstorage_create_dir(account_id, mail_id, current_attachment_no, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if (!emstorage_get_save_name(account_id, mail_id, current_attachment_no, ai->name, buf, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if (!emstorage_move_file(ai->save, buf, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                               err = EMAIL_ERROR_INVALID_ATTACHMENT_SAVE_NAME;
+                               goto FINISH_OFF;
+                       }
+
+                       EM_SAFE_FREE(ai->save);
+
+                       EM_DEBUG_LOG("ai->size [%d]", ai->size);
+                       attachment->attachment_size = ai->size;
+                       attachment->attachment_path = EM_SAFE_STRDUP(buf);
+
+                       /*  update attachment information. */
+                       if (!emstorage_change_attachment_field(mail_id, UPDATE_SAVENAME, attachment, true, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_change_attachment_field failed [%d]", err);
+                               /*  delete created file. */
+                               remove(buf);
+
+                               goto FINISH_OFF;
+                       }
+
+#ifdef __FEATURE_DRM__
+                       if (emcore_check_drm(attachment))  {    /*  has drm attachment ? */
+                               if (drm_process_request(DRM_REQUEST_TYPE_REGISTER_FILE, (void *)attachment->attachment_path, NULL) == DRM_RETURN_SUCCESS)
+                                       EM_DEBUG_LOG("drm_svc_register_file success");
+                               else
+                                       EM_DEBUG_EXCEPTION("drm_svc_register_file fail");
+                               mail->DRM_status = attachment->attachment_drm_type;
+                       }
+#endif /* __FEATURE_DRM__ */
+               }
+               else  {
+                       EM_DEBUG_EXCEPTION("invalid attachment sequence...");
+                       err = EMAIL_ERROR_INVALID_ATTACHMENT;
+                       goto FINISH_OFF;
+               }
+       
+               if (cnt_info)  {
+                       emcore_free_content_info(cnt_info);
+                       cnt_info = NULL;
+               }
+               EM_DEBUG_LOG(" >>>>>> Attachment Downloading [%d / %d] completed", i+1, attachment_count_to_be_downloaded);
+       }
+
+       if (stream)  {
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+       }
+       
+       ret = true;
+       
+FINISH_OFF:
+       if (stream)
+               emcore_close_mailbox(account_id, stream);
+       if (attachment_list)
+               emstorage_free_attachment(&attachment_list, attachment_count_to_be_downloaded, NULL);
+       if (cnt_info)
+               emcore_free_content_info(cnt_info);
+       if (mail)
+               emstorage_free_mail(&mail, 1, NULL);
+
+       EM_SAFE_FREE(s_uid);
+
+       if (ret == true)
+               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FINISH, mail_id, NULL, nth, 0);
+       else
+               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FAIL, mail_id, NULL, nth, err);
+
+       if (err_code != NULL)
+               *err_code = err;
+       
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+#ifdef __ATTACHMENT_OPTI__
+INTERNAL_FUNC int emcore_download_attachment_bulk(int account_id, int mail_id, int nth, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], nth[%d], err_code[%p]", account_id, mail_id, nth, err_code);
+
+       int err = EMAIL_ERROR_NONE; /* Prevent Defect - 25093 */
+       int ret = false;
+       int status = EMAIL_DOWNLOAD_FAIL;
+       MAILSTREAM *stream = NULL;
+       emstorage_mail_tbl_t *mail = NULL;
+       emstorage_attachment_tbl_t *attachment = NULL;
+       void *tmp_stream = NULL;
+       char *s_uid = NULL, *server_mbox = NULL, buf[512];
+       emstorage_attachment_tbl_t *attachment_list = NULL;
+       int current_attachment_no = 0;
+       int attachment_count_to_be_downloaded = 0;              /*  how many attachments should be downloaded */
+       int i = 0;
+       char *savefile = NULL;
+       int dec_len = 0;
+       int uid = 0;
+#ifdef SUPPORT_EXTERNAL_MEMORY
+       int iActualSize = 0;
+       int is_add = 0;
+       char dirName[512];
+       int bIs_empty = 0;
+       int bIs_full = 0;
+       int bIsAdd_to_mmc = false;
+       int is_on_mmc = false;
+       email_file_list *pFileListMMc = NULL;
+       email_file_list *pFileList = NULL;
+#endif /*  SUPPORT_EXTERNAL_MEMORY */
+       
+       
+       memset(buf, 0x00, 512);
+       /* CID FIX 31230 */
+       if (mail_id < 1 || !nth) {
+               EM_DEBUG_EXCEPTION("account_id[%d], mail_id[%d], nth[%p]", account_id, mail_id, nth);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+
+               if (err_code != NULL)
+                       *err_code = err;
+
+               if (nth)
+                       attachment_no = atoi(nth);
+
+               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FAIL, mail_id, 0, attachment_no, err);         /*  090525, kwangryul.baek */
+
+               return false;
+       }
+       
+       if (!emcore_check_thread_status()) {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       only_body_download = false;
+       
+       attachment_no = atoi(nth);
+
+       if (attachment_no == 0) {
+               /*  download all attachments, nth starts from 1, not zero */
+               /*  get attachment list from db */
+               attachment_count_to_be_downloaded = EMAIL_ATTACHMENT_MAX_COUNT;
+               if ( (err = emstorage_get_attachment_list(mail_id, true, &attachment_list, &attachment_count_to_be_downloaded)) != EMAIL_ERROR_NONE || !attachment_list){
+                       EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+       
+                       goto FINISH_OFF;
+               }
+       }
+       else {  /*  download only nth attachment */
+               attachment_count_to_be_downloaded = 1;
+               if (!emstorage_get_attachment_nth(mail_id, attachment_no, &attachment_list, true, &err) || !attachment_list) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_attachment_nth failed [%d]", err);
+
+
+                       goto FINISH_OFF;
+               }
+       }
+
+
+       if (!emcore_check_thread_status()) {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       
+       /*  get mail from mail table. */
+       if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+               
+
+               goto FINISH_OFF;
+       }
+
+       /* if (!mail->server_mail_yn || !mail->text_download_yn) {*/ /*  faizan.h@samsung.com */
+
+       if (!emcore_check_thread_status()) {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       account_id = mail->account_id;
+       s_uid = EM_SAFE_STRDUP(mail->server_mail_id); mail->server_mail_id = NULL;
+       server_mbox = EM_SAFE_STRDUP(mail->mailbox); mail->server_mailbox_name = NULL;
+
+
+
+       /*  open mail server. */
+       if (!emcore_connect_to_remote_mailbox(account_id, server_mbox, (void **)&tmp_stream, &err) || !tmp_stream) {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+
+               status = EMAIL_DOWNLOAD_CONNECTION_FAIL;
+               goto FINISH_OFF;
+       }
+
+       stream = (MAILSTREAM *)tmp_stream;
+
+
+       if (!emcore_check_thread_status()) {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+
+       for (i = 0; i < attachment_count_to_be_downloaded; i++) {
+               EM_DEBUG_LOG(" >>>>>> Attachment Downloading [%d / %d] start", i+1, attachment_count_to_be_downloaded);
+
+               attachment = attachment_list + i;
+               if (attachment_no == 0) {
+                       /*  download all attachments, nth starts from 1, not zero */
+                       current_attachment_no = i + 1;          /*  attachment no */
+               }
+               else {
+                       /*  download only nth attachment */
+                       current_attachment_no = attachment_no;          /*  attachment no */
+               }
+
+               if (!emcore_check_thread_status()) {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               _imap4_received_body_size = 0;
+               _imap4_last_notified_body_size = 0;
+               _imap4_total_body_size = 0;                             /*  This will be assigned in imap_mail_write_body_to_file() */
+               _imap4_download_noti_interval_value = 0;        /*  This will be assigned in imap_mail_write_body_to_file() */
+
+               
+               EM_SAFE_FREE(savefile);
+               if (!emcore_get_temp_file_name(&savefile, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed [%d]", err);
+
+                       if (err_code != NULL)
+                               *err_code = err;
+                       goto FINISH_OFF;
+               }
+
+               if (s_uid)
+                       uid = atoi(s_uid);
+
+               EM_DEBUG_LOG("uid [%d]", uid);
+
+               if (!imap_mail_write_body_to_file(stream, account_id, mail_id, attachment_no, savefile, uid , attachment->section, attachment->encoding, &dec_len, NULL, &err)) {
+                       EM_DEBUG_EXCEPTION("imap_mail_write_body_to_file failed [%d]", err);
+                       if (err_code != NULL)
+                               *err_code = err;
+                       goto FINISH_OFF;
+               }
+
+#ifdef SUPPORT_EXTERNAL_MEMORY
+               iActualSize = emcore_get_actual_mail_size (cnt_info->text.plain , cnt_info->text.html, cnt_info->file , &err);
+               if (!emstorage_mail_check_free_space(iActualSize, &bIs_full, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_mail_check_free_space failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               
+               if (bIs_full) {
+                       /* If external memory not present, return error */
+                       if (PS_MMC_REMOVED == emstorage_get_mmc_status()) {
+                               err = EMAIL_ERROR_MAIL_MEMORY_FULL;
+                               goto FINISH_OFF;
+                       }
+                       bIsAdd_to_mmc = true;
+               }
+#endif /*  SUPPORT_EXTERNAL_MEMORY */
+
+               if (!emstorage_create_dir(account_id, mail_id, attachment_no, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_get_save_name(account_id, mail_id, attachment_no, attachment->name, buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_move_file(savefile, buf, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+
+               attachment->attachment = EM_SAFE_STRDUP(buf);
+               /*  update attachment information. */
+               if (!emstorage_change_attachment_field(mail_id, UPDATE_SAVENAME, attachment, true, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_change_attachment_field failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+
+#ifdef __FEATURE_DRM__
+               if (emcore_check_drm(attachment)) {
+                       /*  is drm */
+                       if (drm_svc_register_file(attachment->attachment) == DRM_RESULT_SUCCESS)
+                               EM_DEBUG_LOG("drm_svc_register_file success");
+                       else
+                               EM_DEBUG_EXCEPTION("drm_svc_register_file fail");
+                       mail->flag3 = attachment->flag2;
+               }
+#endif /* __FEATURE_DRM__ */
+
+               if (!emcore_check_thread_status()) {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG(" >>>>>> Attachment Downloading [%d / %d] completed", i+1, attachment_count_to_be_downloaded);
+       }
+
+       ret = true;
+
+       FINISH_OFF:
+
+       EM_SAFE_FREE(savefile);
+
+       emcore_close_mailbox(0, stream);
+       stream = NULL;
+
+       if (attachment_list) 
+               emstorage_free_attachment(&attachment_list, attachment_count_to_be_downloaded, NULL);
+
+       if (mail) 
+               emstorage_free_mail(&mail, 1, NULL);
+
+       if (s_uid)
+               free(s_uid);
+
+       if (server_mbox)
+               free(server_mbox);server_mbox = NULL;
+
+       if (ret == true)
+               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FINISH, mail_id, NULL, attachment_no, 0);
+       else if (err != EMAIL_ERROR_CANCELLED)
+               emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_FAIL, mail_id, NULL, attachment_no, err);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       return ret;
+}
+#endif
+
+INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, int account_id, int mail_id, int verbose, int with_attach, int limited_size, int event_handle , int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_stream[%p], account_id[%d], mail_id[%d], verbose[%d], with_attach[%d], event_handle [ %d ] ", mail_stream, account_id, mail_id, verbose, with_attach, event_handle);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int status = EMAIL_DOWNLOAD_FAIL;
+       int pop3_body_size = 0;
+       int pop3_downloaded_size = 0;
+       MAILSTREAM *stream = NULL;
+       BODY *mbody = NULL;
+       PARTLIST *section_list = NULL;
+       email_internal_mailbox_t mailbox = { 0 };
+       emstorage_mail_tbl_t *mail = NULL;
+       emstorage_attachment_tbl_t attachment = {0, 0, NULL, };
+       email_account_t *ref_account = NULL;
+       struct attachment_info *ai = NULL;
+       struct _m_content_info *cnt_info = NULL;
+       void *tmp_stream = NULL;
+       char *s_uid = NULL, buf[512];
+       int msgno = 0, attachment_num = 1, local_attachment_count = 0, local_inline_content_count = 0;
+       int iActualSize = 0;
+       char html_body[MAX_PATH] = {0, };
+       emcore_uid_list *uid_list = NULL;
+       char *mailbox_name = NULL;
+#ifdef CHANGE_HTML_BODY_TO_ATTACHMENT
+       int html_changed = 0;
+#endif
+
+       if (mail_id < 1)  {
+               EM_DEBUG_EXCEPTION("mail_stream[%p], account_id[%d], mail_id[%d], verbose[%d], with_attach[%d]", mail_stream, account_id, mail_id, verbose, with_attach);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               
+               if (err_code != NULL)
+                       *err_code = err;
+
+               emcore_notify_network_event(NOTI_DOWNLOAD_BODY_FAIL, mail_id, NULL, event_handle, err);
+               return false;
+       }
+       
+       FINISH_OFF_IF_CANCELED;
+
+       only_body_download = true;
+
+       if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+       
+       if (mail->mailbox_name)
+               mailbox_name = EM_SAFE_STRDUP(mail->mailbox_name);
+       
+       if (1 == mail->body_download_status)  {
+               EM_DEBUG_EXCEPTION("not synchronous mail...");
+               err = EMAIL_ERROR_INVALID_MAIL;
+               goto FINISH_OFF;
+       }
+       
+       s_uid                             = EM_SAFE_STRDUP(mail->server_mail_id);
+
+       attachment.account_id             = mail->account_id;
+       attachment.mail_id                = mail->mail_id;
+       attachment.mailbox_id             = mail->mailbox_id;
+       attachment.attachment_save_status = 0;
+       
+       if (!(ref_account = emcore_get_account_reference(account_id)))   {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       FINISH_OFF_IF_CANCELED;
+
+       /*  open mail server. */
+       if (!mail_stream)  {
+               if (!emcore_connect_to_remote_mailbox(account_id, mail->mailbox_id, (void **)&tmp_stream, &err) || !tmp_stream)  {
+                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+                       status = EMAIL_DOWNLOAD_CONNECTION_FAIL;
+                       goto FINISH_OFF;
+               }
+               stream = (MAILSTREAM *)tmp_stream;
+       }
+       else
+               stream = (MAILSTREAM *)mail_stream;
+       
+       FINISH_OFF_IF_CANCELED;
+       
+       if (!(cnt_info = em_malloc(sizeof(struct _m_content_info))))  {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_POP3)  {
+               /*  POP3 */
+               /*  in POP3 case, both text and attachment are downloaded in this call. */
+               cnt_info->grab_type = GRAB_TYPE_TEXT | GRAB_TYPE_ATTACHMENT;
+               attachment.attachment_save_status = 1;          /*  all attachments should be downloaded in the case of POP3 */
+
+               mailbox.account_id = account_id;
+               mailbox.mail_stream = stream;
+
+               /*  download all uids from server. */
+               if (!emcore_download_uid_all(&mailbox, &uid_list, NULL, NULL, 0, EM_CORE_GET_UIDS_FOR_NO_DELETE, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_download_uid_all failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               /*  get mesg number to be related to last download mail from uid list file */
+               if (!emcore_get_msgno(uid_list, s_uid, &msgno, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_get_msgno failed [%d]", err);
+                       err = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER;
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_check_thread_status())  {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               _pop3_received_body_size = 0;
+               _pop3_total_body_size = 0;
+               _pop3_last_notified_body_size = 0;
+               _pop3_receiving_mail_id = mail_id;
+               
+               /*  send read mail commnad. */
+               if (!emcore_mail_cmd_read_mail_pop3(stream, msgno, limited_size, &pop3_downloaded_size, &pop3_body_size, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_mail_cmd_read_mail_pop3 failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               _pop3_total_body_size = pop3_body_size;
+
+               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, "dummy-file", _pop3_total_body_size, 0))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] failed >>>> ");
+               else
+                       EM_DEBUG_LOG("NOTI_DOWNLOAD_BODY_START notified (%d / %d)", 0, _pop3_total_body_size);
+
+               FINISH_OFF_IF_CANCELED;
+               
+               /*  save message into tempfile */
+               /*  parsing mime from stream. */
+
+               if (!emcore_parse_mime(stream, 0, cnt_info,  &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_parse_mime failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               
+               FINISH_OFF_IF_CANCELED;
+       }
+       else  { /*  in IMAP case, both text and attachment list are downloaded in this call. */
+               /*  This flag is just for downloading mailbox.(sync header), don't be used when retrieve body. */
+               if (with_attach > 0)
+                       cnt_info->grab_type = GRAB_TYPE_TEXT | GRAB_TYPE_ATTACHMENT;
+               else
+                       cnt_info->grab_type = GRAB_TYPE_TEXT;
+
+               int uid = s_uid? atoi(s_uid):0; /*prevent 39118*/
+
+               /*  set sparep(member of BODY) memory free function  */
+               mail_parameters(stream, SET_FREEBODYSPAREP, emcore_free_body_sharep);
+
+               /*  get body strucutre. */
+               /*  don't free mbody because mbody is freed in closing mail_stream. */
+               if (emcore_get_body_structure(stream, uid, &mbody, &err) < 0 || (mbody == NULL))  {
+                       EM_DEBUG_EXCEPTION("emcore_get_body_structure failed [%d]", err);
+                       err = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER;
+                       goto FINISH_OFF;
+               }
+
+               FINISH_OFF_IF_CANCELED;
+
+               if (mbody->type == TYPEMULTIPART) {
+                       EM_DEBUG_LOG(">>> check multipart body size to download : only_body_download[%d]", only_body_download);
+                       PART *part_child = mbody->nested.part;
+                       int counter = 0;
+
+                       char filename[MAX_PATH+1] = {0, };
+                       int is_attachment = 0;
+                       while (part_child)  {
+                               BODY *body = &(part_child->body);
+                               if (only_body_download == true) {
+                                       if (((body->id) && EM_SAFE_STRLEN(body->id) > 1) || (body->location))
+                                               is_attachment = 0;
+                                       else if (body->disposition.type)  {     /*  "attachment" or "inline" or etc... */
+                                               PARAMETER *param = body->disposition.parameter;
+
+                                               while (param)  {
+                                                       EM_DEBUG_LOG("param->attribute [%s], param->value [%s]", param->attribute, param->value);
+
+                                                       if (!strcasecmp(param->attribute, "filename"))  {       /* attribute is "filename" */
+                                                               strncpy(filename, param->value, MAX_PATH);
+                                                               EM_DEBUG_LOG(">>>>> FILENAME [%s] ", filename);
+                                                               break;
+                                                       }
+                                                       param = param->next;
+                                               }
+
+                                               is_attachment = 1;
+
+                                               if (!*filename)  {
+                                                       /*  it may be report msg */
+                                                       if (body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I')
+                                                               is_attachment = 0;
+                                               }
+                                       }
+
+                                       if (is_attachment == 0) {
+                                               EM_DEBUG_LOG("%d :  body->size.bytes[%ld]", counter+1, body->size.bytes);
+                                               multi_part_body_size = multi_part_body_size + body->size.bytes;
+                                       }
+                               }
+                               else {
+                                       /*  download all */
+                                       EM_DEBUG_LOG("%d :  body->size.bytes[%ld]", counter+1, body->size.bytes);
+                                       multi_part_body_size = multi_part_body_size + body->size.bytes;
+                               }
+                               part_child = part_child->next;
+                               counter++;
+                       }
+               }
+
+               /*  set body fetch section. */
+               if (emcore_set_fetch_body_section(mbody, true, &iActualSize, &err) < 0) {
+                       EM_DEBUG_EXCEPTION("emcore_set_fetch_body_section failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("iActualSize [%d]", iActualSize);
+               multi_part_body_size = iActualSize;
+
+               _imap4_received_body_size = 0;
+               _imap4_last_notified_body_size = 0;
+               if (multi_part_body_size > 0) { /*  download multiparts */
+                       _imap4_total_body_size = multi_part_body_size;
+                       _imap4_download_noti_interval_value = DOWNLOAD_NOTI_INTERVAL_PERCENT * multi_part_body_size / 100;
+               }
+               else {  /*  download only one body part */
+                       _imap4_total_body_size = 0;                                     /*  This will be assigned in imap_mail_write_body_to_file() */
+                       _imap4_download_noti_interval_value = 0;        /*  This will be assigned in imap_mail_write_body_to_file() */
+               }
+
+               /*  save message into tempfile */
+               /*  download body text and get attachment list. */
+               if (emcore_get_body_part_list_full(stream, uid, account_id, mail_id, mbody, cnt_info, &err, section_list, event_handle) < 0)  {
+                       EM_DEBUG_EXCEPTION("emcore_get_body_part_list_full failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               FINISH_OFF_IF_CANCELED;
+       }
+
+       if (cnt_info->text.plain)  {
+               EM_DEBUG_LOG("cnt_info->text.plain [%s]", cnt_info->text.plain);
+
+               if (!emstorage_create_dir(account_id, mail_id, 0, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+
+               if (!emstorage_get_save_name(account_id, mail_id, 0, cnt_info->text.plain_charset ? cnt_info->text.plain_charset  :  "UTF-8", buf, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_move_file(cnt_info->text.plain, buf, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               mail->file_path_plain = EM_SAFE_STRDUP(buf);
+               EM_DEBUG_LOG("mail->file_path_plain [%s]", mail->file_path_plain);
+       }
+       
+       if (cnt_info->text.html)  {
+               if (!emstorage_create_dir(account_id, mail_id, 0, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               
+               if (cnt_info->text.plain_charset != NULL) {
+                       memcpy(html_body, cnt_info->text.plain_charset, EM_SAFE_STRLEN(cnt_info->text.plain_charset));
+                       strcat(html_body, HTML_EXTENSION_STRING);
+               }
+               else {
+                       memcpy(html_body, "UTF-8.htm", strlen("UTF-8.htm"));
+               }
+               if (!emstorage_get_save_name(account_id, mail_id, 0, html_body, buf, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_move_file(cnt_info->text.html, buf, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               mail->file_path_html = EM_SAFE_STRDUP(buf);
+       }
+       
+       if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_POP3 && limited_size != NO_LIMITATION && limited_size < pop3_body_size)
+               mail->body_download_status = EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED;
+       else
+               mail->body_download_status = EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED;
+
+       /* Update local_preview_text */
+       if ((err = emcore_get_preview_text_from_file(mail->file_path_plain, mail->file_path_html, MAX_PREVIEW_TEXT_LENGTH, &(mail->preview_text))) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_preview_text_from_file failedi : [%d]", err);
+       }
+       
+#ifdef CHANGE_HTML_BODY_TO_ATTACHMENT
+       if (html_changed) mail->flag2 = 1;
+#endif
+       
+       FINISH_OFF_IF_CANCELED;
+       
+       for (ai = cnt_info->file; ai; ai = ai->next, attachment_num++)  {
+               attachment.attachment_id                    = attachment_num;
+               attachment.attachment_size                  = ai->size;
+               attachment.attachment_path                  = ai->save;
+               attachment.attachment_name                  = ai->name;
+               attachment.attachment_drm_type              = ai->drm;
+               attachment.attachment_inline_content_status = ai->type == 1;
+               attachment.attachment_save_status           = 0;
+               attachment.attachment_mime_type             = ai->attachment_mime_type;
+#ifdef __ATTACHMENT_OPTI__
+               attachment.encoding                         = ai->encoding;
+               attachment.section                          = ai->section;
+#endif
+               EM_DEBUG_LOG("attachment.attachment_id[%d]", attachment.attachment_id);
+               EM_DEBUG_LOG("attachment.attachment_size[%d]", attachment.attachment_size);
+               EM_DEBUG_LOG("attachment.attachment_path[%s]", attachment.attachment_path);
+               EM_DEBUG_LOG("attachment.attachment_name[%s]", attachment.attachment_name);
+               EM_DEBUG_LOG("attachment.attachment_drm_type[%d]", attachment.attachment_drm_type);
+               EM_DEBUG_LOG("attachment.attachment_inline_content_status[%d]", attachment.attachment_inline_content_status);
+
+               if (ai->type == 1)
+                       local_inline_content_count++;
+               local_attachment_count++;
+
+               if (ai->save)  {
+                       /*  in POP3 case, rename temporary file to real file. */
+                       attachment.attachment_save_status = 1;
+                       if (ai->type == 1)  {           /*  it is inline content */
+                               if (!emstorage_create_dir(account_id, mail_id, 0, &err))  {
+                                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+                               if (!emstorage_get_save_name(account_id, mail_id, 0, attachment.attachment_name, buf, &err))  {
+                                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+                       }
+                       else  {
+                               if (!emstorage_create_dir(account_id, mail_id, attachment_num, &err)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+
+                               if (!emstorage_get_save_name(account_id, mail_id, attachment_num, attachment.attachment_name, buf, &err))  {
+                                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+                       }
+
+                       if (!emstorage_move_file(ai->save, buf, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+
+                               /*  delete all created files. */
+                               if (!emstorage_get_save_name(account_id, mail_id, 0, NULL, buf, NULL)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed...");
+                                       /* goto FINISH_OFF; */
+                               }
+
+                               if (!emstorage_delete_dir(buf, NULL)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_delete_dir failed...");
+                                       /* goto FINISH_OFF; */
+                               }
+
+
+                               goto FINISH_OFF;
+                       }
+
+                       free(ai->save); ai->save = EM_SAFE_STRDUP(buf);
+
+                       attachment.attachment_path = ai->save;
+
+#ifdef __FEATURE_DRM__
+                       if (emcore_check_drm(&attachment)) /*  is drm content ?*/ {
+                               if (drm_process_request(DRM_REQUEST_TYPE_REGISTER_FILE, attachment.attachment_path, NULL) != DRM_RETURN_SUCCESS)
+                                       EM_DEBUG_EXCEPTION("drm_process_request : register file fail");
+                               mail->DRM_status = attachment.attachment_drm_type;
+                       }
+#endif/*  __FEATURE_DRM__ */
+               }
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+               /*  Information :  Attachment info already saved if partial body is dowloaded. */
+               if (ai->type)  {
+                       emstorage_attachment_tbl_t *attch_info = NULL;
+                       /*  Get attachment details  */
+                       if (!emstorage_get_attachment_nth(mail_id, attachment.attachment_id, &attch_info, true, &err) || !attch_info)  {
+                               EM_DEBUG_EXCEPTION("emstorage_get_attachment_nth failed [%d]", err);
+                               if (err == EMAIL_ERROR_ATTACHMENT_NOT_FOUND) {   /*  save only attachment file. */
+                                       if (!emstorage_add_attachment(&attachment, 0, false, &err)) {
+                                               EM_DEBUG_EXCEPTION("emstorage_add_attachment failed [%d]", err);
+                                               if (attch_info)
+                                                       emstorage_free_attachment(&attch_info, 1, NULL);
+                                               /*  delete all created files. */
+                                               if (!emstorage_get_save_name(account_id, mail_id, 0, NULL, buf, &err))  {
+                                                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                                                       goto FINISH_OFF;
+                                               }
+
+                                               if (!emstorage_delete_dir(buf, &err))  {
+                                                       EM_DEBUG_EXCEPTION("emstorage_delete_dir failed [%d]", err);
+                                                       goto FINISH_OFF;
+                                               }
+
+                                               /*  ROLLBACK TRANSACTION; */
+                                               emstorage_rollback_transaction(NULL, NULL, NULL);
+
+
+                                               goto FINISH_OFF;
+                                       }
+                               }
+                       }
+                       else {
+                               EM_DEBUG_LOG("Attachment info already exists...!");
+                               /* Update attachment size */
+                               EM_DEBUG_LOG("attachment_size [%d], ai->size [%d]", attch_info->attachment_size, ai->size);
+                               attch_info->attachment_size = ai->size;
+                               if (!emstorage_update_attachment(attch_info, true, &err)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_update_attachment failed [%d]", err);
+
+                                               goto FINISH_OFF;
+                               }
+                       }
+
+                       if (attch_info)
+                               emstorage_free_attachment(&attch_info, 1, NULL);
+               }
+
+#else
+               
+               if (ai->type)  {
+                       mail->attachment_yn = 1;
+                       /*  save only attachment file. */
+                       if (!emstorage_add_attachment(&attachment, 0, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_add_attachment failed [%d]", err);
+                               if (bIsAdd_to_mmc)  {
+                                       if (attachment.attachment) {
+                                       }
+                               }
+                               else  {
+                                       /*  delete all created files. */
+                                       if (!emstorage_get_save_name(account_id, mail_id, 0, NULL, buf, &err))  {
+                                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+
+                                       if (!emstorage_delete_dir(buf, &err))  {
+                                               EM_DEBUG_EXCEPTION("emstorage_delete_dir failed [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+
+                                       /*  ROLLBACK TRANSACTION; */
+                                       emstorage_rollback_transaction(NULL, NULL, NULL);
+                                       goto FINISH_OFF;
+                               }
+                       }
+           }
+#endif /*  End of #ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
+
+       }
+
+       EM_DEBUG_LOG("Check #1");
+
+       mail->attachment_count = local_attachment_count;
+       mail->inline_content_count = local_inline_content_count;
+
+       EM_DEBUG_LOG("Check #2");
+
+       EM_DEBUG_LOG("Mailbox Name [%s]", mailbox_name);
+       mail->mailbox_name = EM_SAFE_STRDUP(mailbox_name);       /*  fix for mailboox sync fail */
+
+       EM_DEBUG_LOG("Check #3");
+
+       /*  change mail's information. */
+       if (!emstorage_change_mail_field(mail_id, APPEND_BODY, mail, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
+               emstorage_rollback_transaction(NULL, NULL, NULL); /*  ROLLBACK TRANSACTION; */
+
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("cnt_info->text.plain [%s], cnt_info->text.html [%s]", cnt_info->text.plain, cnt_info->text.html);
+       
+       /*  in pop3 mail case, the mail is deleted from server after being downloaded. */
+       if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_POP3)  {
+#ifdef DELETE_AFTER_DOWNLOADING
+               char delmsg[24];
+
+               SNPRINTF(delmsg, sizeof(delmsg), "%d", msg_no);
+
+               if (!ref_account->keep_mails_on_pop_server_after_download)  {
+                       if (!emcore_delete_mails_from_pop3_server(&mbox, delmsg, &err))
+                               EM_DEBUG_EXCEPTION("emcore_delete_mails_from_pop3_server failed [%d]", err);
+               }
+#endif
+               
+               if (!mail_stream)  {
+                       if (stream != NULL)  {
+                               emcore_close_mailbox(0, stream);
+                               stream = NULL;
+                       }
+               }
+       }
+
+       FINISH_OFF_IF_CANCELED;
+       
+       ret = true;
+
+FINISH_OFF:
+
+       if (g_inline_count) {
+               g_inline_count = 0;
+               EM_SAFE_FREE(g_inline_list);
+       }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       multi_part_body_size = 0;
+       _pop3_received_body_size = 0;
+       _pop3_last_notified_body_size = 0;
+       _pop3_total_body_size = 0;
+       _pop3_receiving_mail_id = 0;
+       
+       _imap4_received_body_size = 0;
+       _imap4_last_notified_body_size = 0;
+       _imap4_total_body_size = 0;
+       _imap4_download_noti_interval_value = 0;
+       
+       if (cnt_info)
+               emcore_free_content_info(cnt_info);
+       if (mail)
+               emstorage_free_mail(&mail, 1, NULL);
+       EM_SAFE_FREE(s_uid);
+       EM_SAFE_FREE(mailbox_name);
+
+       multi_part_body_size = 0;
+       
+       if (ret == true)
+               emcore_notify_network_event(NOTI_DOWNLOAD_BODY_FINISH, mail_id, NULL, event_handle, 0);
+       else
+               emcore_notify_network_event(NOTI_DOWNLOAD_BODY_FAIL, mail_id, NULL, event_handle, err);
+
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+}
+
+
+
+void emcore_mail_copyuid(MAILSTREAM *stream, char *mailbox,
+                          unsigned long uidvalidity, SEARCHSET *sourceset,
+                          SEARCHSET *destset)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       char  old_server_uid[129];
+
+       EM_DEBUG_LOG("mailbox name - %s", mailbox);
+       EM_DEBUG_LOG("first sequence number source- %ld", sourceset->first);
+       EM_DEBUG_LOG("last sequence number last- %ld", sourceset->last);
+       EM_DEBUG_LOG("first sequence number dest - %ld", destset->first);
+       EM_DEBUG_LOG("last sequence number dest- %ld", sourceset->last);
+
+       /* search for server _mail_id with value sourceset->first and update it with destset->first */
+       /* faizan.h@samsung.com */
+       memset(old_server_uid, 0x00, 129);
+       sprintf(old_server_uid, "%ld", sourceset->first);
+       EM_DEBUG_LOG(">>>>> old_server_uid = %s", old_server_uid);
+
+       memset(g_new_server_uid, 0x00, 129);
+       sprintf(g_new_server_uid, "%ld", destset->first);
+       EM_DEBUG_LOG(">>>>> new_server_uid =%s", g_new_server_uid);
+
+       if (!emstorage_update_server_uid(old_server_uid, g_new_server_uid, NULL)) {
+               EM_DEBUG_EXCEPTION("emstorage_update_server_uid falied...");
+       }
+}
+
+static int emcore_delete_mails_from_remote_server(int input_account_id, int input_mail_ids[], int input_mail_id_count, int input_delete_option)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id[%d], input_mail_ids[%p], input_mail_id_count[%d], input_delete_option [%d]", input_account_id, input_mail_ids, input_mail_id_count, input_delete_option);
+
+       int err = EMAIL_ERROR_NONE;
+       email_account_t *account = NULL;
+#ifdef         __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+       int bulk_flag = false;
+#endif
+
+       if (!(account = emcore_get_account_reference(input_account_id)))  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", input_account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!emnetwork_check_network_status(&err)) {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       FINISH_OFF_IF_CANCELED;
+
+       if (account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+               if (!bulk_flag && !emcore_delete_mails_from_imap4_server(input_mail_ids, input_mail_id_count, input_delete_option, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_delete_mails_from_imap4_server failed [%d]", err);
+                       if (err == EMAIL_ERROR_IMAP4_STORE_FAILURE)
+                               err = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER;
+                       goto FINISH_OFF;
+               }
+               else
+                       bulk_flag = true;
+       }
+       else if (account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) {
+               if (!emcore_delete_mails_from_pop3_server(account, input_mail_ids, input_mail_id_count))  {
+                       EM_DEBUG_EXCEPTION("emcore_delete_mails_from_pop3_server falied [%d]", err);
+                       goto FINISH_OFF;
+               }
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+               else {
+                       /* Remove local activity */
+                       emstorage_activity_tbl_t new_activity;
+                       memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
+                       if (from_server == EMAIL_DELETE_FOR_SEND_THREAD) {
+                               new_activity.activity_type = ACTIVITY_DELETEMAIL_SEND;
+                               EM_DEBUG_LOG("from_server == EMAIL_DELETE_FOR_SEND_THREAD ");
+                       }
+                       else {
+                               new_activity.activity_type      = ACTIVITY_DELETEMAIL;
+                       }
+
+                       new_activity.mail_id            = mail->mail_id;
+                       new_activity.server_mailid      = mail->server_mail_id;
+                       new_activity.src_mbox           = NULL;
+                       new_activity.dest_mbox          = NULL;
+
+                       if (!emcore_delete_activity(&new_activity, &err)) {
+                               EM_DEBUG_EXCEPTION(" emcore_delete_activity  failed  - %d ", err);
+                       }
+
+                       /* Fix for issue - Sometimes mail move and immediately followed by mail delete is not reflected on server */
+                       if (!emstorage_remove_downloaded_mail(input_account_id, mail->server_mailbox_name, mail->server_mail_id, true, &err))  {
+                               EM_DEBUG_LOG("emstorage_remove_downloaded_mail falied [%d]", err);
+                       }
+               }
+
+#endif /*  __FEATURE_LOCAL_ACTIVITY__ */
+       }
+
+FINISH_OFF:
+
+       if (account) {
+               emcore_free_account(account);
+               EM_SAFE_FREE(account);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+int emcore_delete_mail(int account_id, int mail_ids[], int num, int from_server, int noti_param_1, int noti_param_2, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_ids[%p], num[%d], from_server[%d], noti_param_1 [%d], noti_param_2 [%d], err_code[%p]", account_id, mail_ids, num, from_server, noti_param_1, noti_param_2, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t *account = NULL;
+
+       if (!account_id || !mail_ids || !num)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], mail_ids[%p], num[%d], from_server[%d]", account_id, mail_ids, num, from_server);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(account = emcore_get_account_reference(account_id)))  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       FINISH_OFF_IF_CANCELED;
+
+       if (from_server == EMAIL_DELETE_LOCALLY) /* Delete mails from local storage*/ {
+               emcore_delete_mails_from_local_storage(account_id, mail_ids, num, noti_param_1, noti_param_2, err_code);
+               emcore_display_unread_in_badge();
+       }
+       else {   /* Delete mails from server*/
+               emcore_delete_mails_from_remote_server(account_id, mail_ids, num, from_server);
+       }
+
+
+       ret = true;
+
+FINISH_OFF: 
+       if (from_server)
+               emcore_show_user_message(account_id, EMAIL_ACTION_DELETE_MAIL, ret == true ? 0  :  err);
+
+       if (account) {
+               emcore_free_account(account);
+               EM_SAFE_FREE(account);
+       }
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+
+       return ret;
+}
+
+int emcore_delete_all_mails_of_acount(int input_account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d]");
+
+       int   err = EMAIL_ERROR_NONE;
+       char  buf[512] = { 0, };
+
+       /* emstorage_delete_mail_by_account is available only locally */
+       if (!emstorage_delete_mail_by_account(input_account_id, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_delete_mail_by_account failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_delete_attachment_all_on_db(input_account_id, NULL, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_delete_attachment_all_on_db failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /*  delete mail contents from filesystem */
+       if (!emstorage_get_save_name(input_account_id, 0, 0, NULL, buf, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_delete_dir(buf, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_delete_dir failed [%d]", err);
+       }
+
+       /*  delete meeting request */
+       if (!emstorage_delete_meeting_request(input_account_id, 0, 0, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_delete_attachment_all_on_db failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]",err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_delete_all_mails_of_mailbox(int input_account_id, int input_mailbox_id, int input_from_server, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id[%d] input_mailbox_id[%d] input_from_server[%d] err_code[%p]", input_account_id, input_mailbox_id, input_from_server, err_code);
+
+       int   ret = false;
+       int   err = EMAIL_ERROR_NONE;
+       int  *mail_id_array = NULL;
+       int   mail_id_count = 0;
+       char  conditional_clause[QUERY_SIZE] = { 0, };
+
+       if (!input_mailbox_id) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               goto FINISH_OFF;
+       }
+
+       /* Delete all mails in specific mailbox */
+
+       SNPRINTF(conditional_clause, QUERY_SIZE, " where mailbox_id = %d ", input_mailbox_id);
+
+       emstorage_query_mail_id_list(conditional_clause, false, &mail_id_array, &mail_id_count);
+
+       EM_DEBUG_LOG("emstorage_query_mail_id_list returns [%d]", mail_id_count);
+
+       if (mail_id_count > 0) {
+               if (!emcore_delete_mail(input_account_id, mail_id_array, mail_id_count, input_from_server, EMAIL_DELETED_BY_COMMAND, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_delete_mail failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(mail_id_array);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d], err [%d]", ret, err);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_delete_mails_from_local_storage(int account_id, int *mail_ids, int num, int noti_param_1, int noti_param_2, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_ids[%p], num [%d], noti_param_1 [%d], noti_param_2 [%d], err_code[%p]", account_id, mail_ids, num, noti_param_1, noti_param_2, num, err_code);
+       int ret = false, err = EMAIL_ERROR_NONE, i;
+       emstorage_mail_tbl_t *result_mail_list = NULL;
+       char mail_id_string[10], *noti_param_string = NULL, buf[512] = {0, };
+
+       /* Getting mail list by using select mail_id [in] */
+       if(!emstorage_get_mail_field_by_multiple_mail_id(mail_ids, num, RETRIEVE_SUMMARY, &result_mail_list, true, &err) || !result_mail_list) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_field_by_multiple_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Deleting mails by using select mail_id [in] */
+       if(!emstorage_delete_multiple_mails(mail_ids, num, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_delete_multiple_mails failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Sending Notification */
+       noti_param_string = em_malloc(sizeof(char) * 10 * num);
+
+       if(!noti_param_string) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < num; i++) {
+               memset(mail_id_string, 0, sizeof(mail_id_string));
+               SNPRINTF(mail_id_string, sizeof(mail_id_string), "%d,", mail_ids[i]);
+               strcat(noti_param_string, mail_id_string);
+               /* can be optimized by appending sub string with directly pointing on string array kyuho.jo 2011-10-07 */
+       }
+
+       if (!emcore_notify_storage_event(NOTI_MAIL_DELETE, account_id, noti_param_1, noti_param_string, noti_param_2))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event failed [ NOTI_MAIL_DELETE_FINISH ] >>>> ");
+
+       /* Updating Thread informations */
+       /* Thread information should be updated as soon as possible. */
+       for(i = 0; i < num; i++) {
+               if (result_mail_list[i].thread_item_count > 1)  {
+                       if (!emstorage_update_latest_thread_mail(account_id, result_mail_list[i].thread_id, 0, 0, false,  &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_update_latest_thread_mail failed [%d]", err);
+               
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+       if (!emcore_notify_storage_event(NOTI_MAIL_DELETE_FINISH, account_id, noti_param_1, noti_param_string, noti_param_2))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event failed [ NOTI_MAIL_DELETE_FINISH ] >>>> ");
+
+       for(i = 0; i < num; i++) {
+               /* Deleting attachments */
+               if (!emstorage_delete_all_attachments_of_mail(result_mail_list[i].mail_id, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_all_attachments_of_mail failed [%d]", err);
+                       if (err == EMAIL_ERROR_ATTACHMENT_NOT_FOUND)
+                               err = EMAIL_ERROR_NONE;
+               }
+
+               /* Deleting Directories */
+               /*  delete mail contents from filesystem */
+               if (!emstorage_get_save_name(account_id, result_mail_list[i].mail_id, 0, NULL, buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_delete_dir(buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_dir failed [%d]", err);
+               }
+               
+               /* Deleting Meeting Request */
+               if (!emstorage_delete_meeting_request(account_id, result_mail_list[i].mail_id, 0, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_meeting_request failed [%d]", err);
+                       if (err != EMAIL_ERROR_CONTACT_NOT_FOUND) {
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(noti_param_string);
+
+       if (result_mail_list)
+               emstorage_free_mail(&result_mail_list, num, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+static int emcore_delete_mails_from_pop3_server(email_account_t *input_account, int input_mail_ids[], int input_mail_id_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account[%p], input_mail_ids[%p], input_mail_id_count[%d]", input_account, input_mail_ids, input_mail_id_count);
+
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       int mail_id = 0;
+       int msgno = 0;
+       void *stream = NULL;
+       email_internal_mailbox_t mailbox_data = { 0, };
+       emstorage_mail_tbl_t    *mail_tbl_data = NULL;
+       
+       if (!input_account || !input_mail_ids) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < input_mail_id_count; i++)  {
+               FINISH_OFF_IF_CANCELED;
+
+               mail_id = input_mail_ids[i];
+
+               if (!emstorage_get_downloaded_mail(mail_id, &mail_tbl_data, false, &err) || !mail_tbl_data)  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_downloaded_mail failed [%d]", err);
+
+                       if (err == EMAIL_ERROR_MAIL_NOT_FOUND) {        /* not server mail */
+                               continue;
+                       }
+                       else
+                               goto FINISH_OFF;
+               }
+
+               if (stream == NULL)  {
+                       if (!emcore_connect_to_remote_mailbox(input_account->account_id, 0, (void **)&stream, &err))  {
+                               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       mailbox_data.mail_stream  = stream;
+                       mailbox_data.account_id   = input_account->account_id;
+                       mailbox_data.mailbox_id   = mail_tbl_data->mailbox_id;
+               }
+
+               if (mailbox_data.user_data != NULL) {
+                       emcore_free_uids(mailbox_data.user_data, NULL);
+                       mailbox_data.user_data = NULL;
+               }
+
+               if (!emcore_get_mail_msgno_by_uid(input_account, &mailbox_data, mail_tbl_data->server_mail_id, &msgno, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_get_mail_msgno_by_uid faild [%d]", err);
+                       if (err == EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER)
+                               goto NOT_FOUND_ON_SERVER;
+                       else
+                               goto FINISH_OFF;
+               }
+
+               if (!pop3_mail_delete(mailbox_data.mail_stream, msgno, &err)) {
+                       EM_DEBUG_EXCEPTION("pop3_mail_delete failed [%d]", err);
+       
+                       if (err == EMAIL_ERROR_POP3_DELE_FAILURE)
+                               err = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER;
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_remove_downloaded_mail(input_account->account_id, mail_tbl_data->server_mailbox_name, mail_tbl_data->server_mail_id, true, &err))
+                       EM_DEBUG_LOG("emstorage_remove_downloaded_mail falied [%d]", err);
+
+NOT_FOUND_ON_SERVER :
+
+               if (mail_tbl_data != NULL)
+                       emstorage_free_mail(&mail_tbl_data, 1, NULL);
+       }
+
+FINISH_OFF: 
+
+       if (mail_tbl_data != NULL)
+               emstorage_free_mail(&mail_tbl_data, 1, NULL);
+
+       if (stream)              {
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+       }
+
+       if (mailbox_data.user_data != NULL) {
+               emcore_free_uids(mailbox_data.user_data, NULL);
+               mailbox_data.user_data = NULL;
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_get_mail_msgno_by_uid(email_account_t *account, email_internal_mailbox_t *mailbox, char *uid, int *msgno, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p], mailbox[%p], uid[%s], msgno[%p], err_code[%p]", account, mailbox, uid, msgno, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       emcore_uid_list *uid_list = NULL;
+       
+       if (!account || !mailbox || !uid || !msgno)  {
+               EM_DEBUG_EXCEPTION("account[%p], mailbox[%p], uid[%s], msgno[%p]", account, mailbox, uid, msgno);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       uid_list = mailbox->user_data;
+       
+       if (uid_list == NULL)  {
+               if (account->incoming_server_type == EMAIL_SERVER_TYPE_POP3)  {
+                       if (!pop3_mailbox_get_uids(mailbox->mail_stream, &uid_list, &err))  {
+                               EM_DEBUG_EXCEPTION("pop3_mailbox_get_uids failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+               }
+               else  {         /*  EMAIL_SERVER_TYPE_IMAP4 */
+                       if (!imap4_mailbox_get_uids(mailbox->mail_stream, &uid_list, &err))  {
+                               EM_DEBUG_EXCEPTION("imap4_mailbox_get_uids failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+               }
+               mailbox->user_data = uid_list;
+       }
+
+       while (uid_list)  {
+               if (!strcmp(uid_list->uid, uid))  {
+                       *msgno = uid_list->msgno;
+                       EM_DEBUG_LOG("uid_list->msgno[%d]", uid_list->msgno);
+                       ret = true;
+                       goto FINISH_OFF;
+               }
+               EM_DEBUG_LOG("other uid_list->msgno[%d]", uid_list->msgno);
+               uid_list = uid_list->next;
+       }
+       
+       err = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER;
+
+FINISH_OFF: 
+       if (err_code != NULL)
+               *err_code = err;
+
+       if (uid_list != NULL)
+               emcore_free_uids(uid_list, NULL);
+       /*  mailbox->user_data and uid_list both point to same memory address, So when uid_list  is freed then just set  */
+       /*  mailbox->user_data to NULL and dont use EM_SAFE_FREE, it will crash  : ) */
+       if (mailbox)
+       mailbox->user_data = NULL;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_expunge_mails_deleted_flagged_from_local_storage(int input_mailbox_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d]", input_mailbox_id);
+       int   err = EMAIL_ERROR_NONE;
+       char *conditional_clause_string = NULL;
+       email_list_filter_t *filter_list = NULL;
+       int  filter_count = 0;
+       int *result_mail_id_list = NULL;
+       int  result_count = 0;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+
+       if (input_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err =  EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       filter_count = 3;
+
+       filter_list = em_malloc(sizeof(email_list_filter_t) * filter_count);
+
+       if (filter_list == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       filter_list[0].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[0].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_MAILBOX_ID;
+       filter_list[0].list_filter_item.rule.key_value.integer_type_value = input_mailbox_id;
+
+       filter_list[1].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[1].list_filter_item.operator_type                     = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+       filter_list[2].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[2].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[2].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_FLAGS_DELETED_FIELD;
+       filter_list[2].list_filter_item.rule.key_value.integer_type_value = 1;
+
+       if ( (err = emstorage_write_conditional_clause_for_getting_mail_list(filter_list, filter_count, NULL, 0, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("conditional_clause_string[%s].", conditional_clause_string);
+
+       if ((err = emstorage_query_mail_id_list(conditional_clause_string, true, &result_mail_id_list, &result_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_id_list [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_delete_mails_from_local_storage(mailbox_tbl->account_id, result_mail_id_list, result_count, 1, EMAIL_DELETED_BY_COMMAND, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_delete_mails_from_local_storage [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if(mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       if(filter_list)
+               emstorage_free_list_filter(&filter_list, filter_count);
+
+       EM_SAFE_FREE(conditional_clause_string);
+       EM_SAFE_FREE(result_mail_id_list);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_expunge_mails_deleted_flagged_from_remote_server(int input_account_id, int input_mailbox_id)
+{
+       int   err = EMAIL_ERROR_NONE;
+       char *conditional_clause_string = NULL;
+       email_list_filter_t *filter_list = NULL;
+       int  filter_count = 0;
+       int *result_mail_id_list = NULL;
+       int  result_count = 0;
+
+       if ( input_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err =  EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       filter_count = 3;
+
+       filter_list = em_malloc(sizeof(email_list_filter_t) * filter_count);
+
+       if (filter_list == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       filter_list[0].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[0].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_MAILBOX_ID;
+       filter_list[0].list_filter_item.rule.key_value.integer_type_value = input_mailbox_id;
+
+       filter_list[1].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[1].list_filter_item.operator_type                     = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+       filter_list[2].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[2].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[2].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_FLAGS_DELETED_FIELD;
+       filter_list[2].list_filter_item.rule.key_value.integer_type_value = 1;
+
+       if ( (err = emstorage_write_conditional_clause_for_getting_mail_list(filter_list, filter_count, NULL, 0, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("conditional_clause_string[%s].", conditional_clause_string);
+
+       if ((err = emstorage_query_mail_id_list(conditional_clause_string, true, &result_mail_id_list, &result_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_id_list [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_delete_mail(input_account_id, result_mail_id_list, result_count, EMAIL_DELETE_FROM_SERVER, 1, EMAIL_DELETED_BY_COMMAND, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_delete_mail [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if(filter_list)
+               emstorage_free_list_filter(&filter_list, filter_count);
+
+       EM_SAFE_FREE(result_mail_id_list);
+       EM_SAFE_FREE(conditional_clause_string);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+
+       return err;
+}
+
+/* description 
+ *    add a attachment to mail.
+ * arguments  
+ *    mailbox  :  mail box
+ *    mail_id  :  mail id
+ *    attachment  :  attachment to be added
+ * return  
+ *    succeed  :  1
+ *    fail  :  0
+ */
+INTERNAL_FUNC int emcore_mail_add_attachment(int mail_id, email_attachment_data_t *attachment, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], attachment[%p], err_code[%p]", mail_id, attachment, err_code);
+       
+       if (attachment == NULL)  {
+               EM_DEBUG_EXCEPTION("mail_id[%d], attachment[%p]", mail_id, attachment);
+               if (err_code)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       
+       int ret = false, err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *mail_table_data = NULL;
+       int attachment_id = 0;
+       
+
+       
+       if (!emstorage_get_mail_field_by_id(mail_id, RETRIEVE_SUMMARY, &mail_table_data, true, &err) || !mail_table_data)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_field_by_id failed [%d]", err);
+
+               goto FINISH_OFF2;
+       }
+       
+       int account_id = mail_table_data->account_id;
+       emstorage_attachment_tbl_t attachment_tbl;
+       
+       memset(&attachment_tbl, 0x00, sizeof(emstorage_attachment_tbl_t));
+
+       mail_table_data->attachment_count               = mail_table_data->attachment_count + 1;
+       attachment_tbl.account_id                       = mail_table_data->account_id;
+       attachment_tbl.mailbox_id                       = mail_table_data->mailbox_id;
+       attachment_tbl.mail_id                          = mail_id;
+       attachment_tbl.attachment_name                  = attachment->attachment_name;
+       attachment_tbl.attachment_size                  = attachment->attachment_size;
+       attachment_tbl.attachment_save_status           = attachment->save_status;
+       attachment_tbl.attachment_drm_type              = attachment->drm_status;
+       attachment_tbl.attachment_inline_content_status = attachment->inline_content_status;
+
+       /*  BEGIN TRANSACTION; */
+       emstorage_begin_transaction(NULL, NULL, NULL);
+
+       if (!emstorage_add_attachment(&attachment_tbl, 0, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_add_attachment failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+       
+       attachment->attachment_id = attachment_tbl.attachment_id;
+
+       if (attachment->attachment_path)  {
+               char buf[512];
+
+               if (!attachment->inline_content_status) {
+                       if (!emstorage_create_dir(account_id, mail_id, attachment_tbl.attachment_id, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+                       attachment_id = attachment_tbl.attachment_id;
+               }
+
+               if (!emstorage_get_save_name(account_id, mail_id, attachment_id, attachment->attachment_name, buf, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+        attachment_tbl.attachment_path = buf;
+
+               if (!emstorage_change_attachment_field(mail_id, UPDATE_SAVENAME, &attachment_tbl, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_change_attachment_field failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_change_mail_field(mail_id, APPEND_BODY, mail_table_data, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
+       
+                       goto FINISH_OFF;
+               }
+
+               if (attachment->save_status) {
+                       if (!emstorage_move_file(attachment->attachment_path, buf, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+
+                               goto FINISH_OFF;
+                       }
+               }
+
+               /* Here only filename is being updated. Since first add is being done there will not be any old files.
+                   So no need to check for old files in this update case */
+               if (!emstorage_change_attachment_field(mail_id, UPDATE_SAVENAME, &attachment_tbl, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_change_attachment_field failed [%d]", err);
+       
+                       goto FINISH_OFF;
+               }
+
+               EM_SAFE_FREE(attachment->attachment_path);
+               attachment->attachment_path = EM_SAFE_STRDUP(buf);
+       }
+       
+       ret = true;
+       
+FINISH_OFF: 
+       if (ret == true) {      /*  COMMIT TRANSACTION; */
+               if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+                       err = EMAIL_ERROR_DB_FAILURE;
+                       ret = false;
+               }
+       }
+       else {  /*  ROLLBACK TRANSACTION; */
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       err = EMAIL_ERROR_DB_FAILURE;
+       }       
+
+FINISH_OFF2: 
+       if (mail_table_data != NULL)
+               emstorage_free_mail(&mail_table_data, 1, NULL);
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_mail_add_attachment_data(int input_mail_id, email_attachment_data_t *input_attachment_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], input_attachment_data[%p]", input_mail_id, input_attachment_data);
+
+       int                        err             = EMAIL_ERROR_NONE;
+       int                        attachment_id   = 0;
+       char                       buf[512] = { 0, };
+       emstorage_mail_tbl_t            *mail_table_data = NULL;
+       emstorage_attachment_tbl_t  attachment_tbl  = { 0 };
+       
+       if (input_attachment_data == NULL)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if (!emstorage_get_mail_field_by_id(input_mail_id, RETRIEVE_SUMMARY, &mail_table_data, true, &err) || !mail_table_data)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_field_by_id failed [%d]", err);
+
+               goto FINISH_OFF2;
+       }
+
+       mail_table_data->attachment_count               = mail_table_data->attachment_count + 1;
+
+       attachment_tbl.account_id                       = mail_table_data->account_id;
+       attachment_tbl.mailbox_id                       = mail_table_data->mailbox_id;
+       attachment_tbl.mail_id                          = input_mail_id;
+       attachment_tbl.attachment_name                  = input_attachment_data->attachment_name;
+       attachment_tbl.attachment_size                  = input_attachment_data->attachment_size;
+       attachment_tbl.attachment_save_status           = input_attachment_data->save_status;
+       attachment_tbl.attachment_drm_type          = input_attachment_data->drm_status;
+       attachment_tbl.attachment_inline_content_status = input_attachment_data->inline_content_status;
+       
+       /*  BEGIN TRANSACTION; */
+       emstorage_begin_transaction(NULL, NULL, NULL);
+
+       if (!emstorage_add_attachment(&attachment_tbl, 0, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_add_attachment failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+       
+       input_attachment_data->attachment_id = attachment_tbl.attachment_id;
+
+       if (input_attachment_data->attachment_path)  {
+               if (!input_attachment_data->inline_content_status) {
+                       if (!emstorage_create_dir(mail_table_data->account_id, input_mail_id, attachment_tbl.attachment_id, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+                       attachment_id = attachment_tbl.attachment_id;
+               }
+
+               if (!emstorage_get_save_name(mail_table_data->account_id, input_mail_id, attachment_id, input_attachment_data->attachment_name, buf, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+        attachment_tbl.attachment_path = buf;
+
+               if (!emstorage_change_attachment_field(input_mail_id, UPDATE_SAVENAME, &attachment_tbl, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_change_attachment_field failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_change_mail_field(input_mail_id, APPEND_BODY, mail_table_data, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
+       
+                       goto FINISH_OFF;
+               }
+
+               if (input_attachment_data->save_status) {
+                       if (!emstorage_move_file(input_attachment_data->attachment_path, buf, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+
+                               goto FINISH_OFF;
+                       }
+               }
+               
+               /* Here only filename is being updated. Since first add is being done there will not be any old files.
+                   So no need to check for old files in this update case */
+               if (!emstorage_change_attachment_field(input_mail_id, UPDATE_SAVENAME, &attachment_tbl, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_change_attachment_field failed [%d]", err);
+       
+                       goto FINISH_OFF;
+               }
+               
+               EM_SAFE_FREE(input_attachment_data->attachment_path);
+               input_attachment_data->attachment_path = EM_SAFE_STRDUP(buf);
+       }
+       
+FINISH_OFF:
+       if (err == EMAIL_ERROR_NONE) {  /*  COMMIT TRANSACTION; */
+               if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+                       err = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+       else {  /*  ROLLBACK TRANSACTION; */
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       err = EMAIL_ERROR_DB_FAILURE;
+       }       
+       
+FINISH_OFF2:
+       if (mail_table_data != NULL)
+               emstorage_free_mail(&mail_table_data, 1, NULL);
+       
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+/* description
+ *    delete a attachment from mail.
+ * arguments
+ *    mailbox  :  mail box
+ *    mail_id  :  mail id
+ *    attachment_id  :  number string of attachment-id to be deleted
+ *                 (ex :  if attachment id is 2, number stirng will be "2")
+ * return
+ *    succeed  :  1
+ *    fail  :  0
+ */
+int emcore_delete_mail_attachment(int attachment_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_id[%d], err_code[%p]", attachment_id, err_code);
+       
+       if (attachment_id == 0)  {
+               EM_DEBUG_EXCEPTION("attachment_id[%d]", attachment_id);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = true;
+       int error = EMAIL_ERROR_NONE;
+       char attachment_folder_path[MAX_PATH] = {0, };
+       emstorage_attachment_tbl_t *attachment_tbl = NULL;
+       
+       if (!emstorage_get_attachment(attachment_id, &attachment_tbl, true, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment failed");
+               return false;
+       }
+
+       /*  BEGIN TRANSACTION; */
+       emstorage_begin_transaction(NULL, NULL, NULL);
+       
+       if (!emstorage_delete_attachment_on_db(attachment_id, false, &error))  {
+               EM_DEBUG_EXCEPTION("emstorage_delete_attachment_on_db failed [%d]", error);
+
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       error = EMAIL_ERROR_DB_FAILURE;
+
+               ret = false;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(attachment_folder_path, sizeof(attachment_folder_path), "%s/%d/%d/%d", MAILHOME, attachment_tbl->account_id, attachment_tbl->mail_id, attachment_id);
+
+       if (!emstorage_delete_dir(attachment_folder_path, NULL)) {
+               EM_DEBUG_EXCEPTION("emstorage_delete_dir failed");
+       }
+
+       if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+               error = EMAIL_ERROR_DB_FAILURE;
+               ret = false;
+       }
+
+FINISH_OFF:
+       if (attachment_tbl)
+               emstorage_free_attachment(&attachment_tbl, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+static int emcore_mail_update_attachment_data(int input_mail_id, email_attachment_data_t *input_attachment_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], input_attachment_data[%p]", input_mail_id, input_attachment_data);
+
+       int                         err = EMAIL_ERROR_NONE;
+       int                         attachment_id = 0;
+       char                        buf[512] = { 0 , };
+       emstorage_attachment_tbl_t *existing_attachment_info = NULL;
+       emstorage_attachment_tbl_t  attachment_tbl = { 0 };
+
+       if (input_attachment_data == NULL)  {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF2;
+       }
+
+       if (!emstorage_get_attachment(input_attachment_data->attachment_id, &existing_attachment_info, 1, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment failed [%d]", err);
+
+               goto FINISH_OFF2;
+       }
+       
+       attachment_tbl.mail_id                          = input_mail_id;
+       attachment_tbl.account_id                       = existing_attachment_info->account_id;
+       attachment_tbl.mailbox_id                       = existing_attachment_info->mailbox_id;
+       attachment_tbl.attachment_name                  = input_attachment_data->attachment_name;
+       attachment_tbl.attachment_size                  = input_attachment_data->attachment_size;
+       attachment_tbl.attachment_path                  = input_attachment_data->attachment_path;
+       attachment_tbl.attachment_save_status           = input_attachment_data->save_status;
+       attachment_tbl.attachment_drm_type              = input_attachment_data->drm_status;
+       attachment_tbl.attachment_inline_content_status = input_attachment_data->inline_content_status;
+       attachment_tbl.attachment_id                    = input_attachment_data->attachment_id;
+
+       if (!input_attachment_data->inline_content_status) {
+               if (!emstorage_create_dir(attachment_tbl.account_id, input_mail_id, attachment_tbl.attachment_id, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               attachment_id = attachment_tbl.attachment_id;
+       }
+       
+       if (!emstorage_get_save_name(attachment_tbl.account_id, input_mail_id, attachment_id, input_attachment_data->attachment_name, buf, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+               goto FINISH_OFF2;
+       }
+    attachment_tbl.attachment_path = buf;
+
+       EM_DEBUG_LOG("downloaded [%d], savename [%s], attachment_path [%s]", input_attachment_data->save_status, input_attachment_data->attachment_path, existing_attachment_info->attachment_path);
+       if (input_attachment_data->save_status && EM_SAFE_STRCMP(input_attachment_data->attachment_path, existing_attachment_info->attachment_path) != 0) {
+               if (!emstorage_move_file(input_attachment_data->attachment_path, buf, false ,&err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+
+                       goto FINISH_OFF2;
+               }
+       }
+       else
+               EM_DEBUG_LOG("no need to move");
+
+       EM_SAFE_FREE(input_attachment_data->attachment_path);
+       input_attachment_data->attachment_path = EM_SAFE_STRDUP(buf);
+
+       emstorage_begin_transaction(NULL, NULL, NULL);
+
+       if (!emstorage_update_attachment(&attachment_tbl, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_update_attachment failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+       
+FINISH_OFF:
+       if (err == EMAIL_ERROR_NONE) {  /*  COMMIT TRANSACTION; */
+               if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+                       err = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+       else {  /*  ROLLBACK TRANSACTION; */
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       err = EMAIL_ERROR_DB_FAILURE;
+       }
+
+FINISH_OFF2:
+       if (existing_attachment_info)
+               emstorage_free_attachment(&existing_attachment_info, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+static int emcore_mail_compare_filename_of_attachment_data(int input_mail_id, int input_attachment_a_id, email_attachment_data_t *input_attachment_b_data, int *result)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], input_attachment_a_id[%d], input_attachment_b_data[%p], result[%p]", input_mail_id, input_attachment_a_id, input_attachment_b_data, result);
+
+       EM_IF_NULL_RETURN_VALUE(input_attachment_b_data, false);
+       EM_IF_NULL_RETURN_VALUE(result, false);
+
+       int err, err_2, ret = EMAIL_ERROR_NONE;
+       emstorage_attachment_tbl_t *attachment_a_tbl = NULL;
+
+       if (!emstorage_get_attachment(input_attachment_a_id, &attachment_a_tbl, 1, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if (attachment_a_tbl->attachment_name && input_attachment_b_data->attachment_name) {
+               EM_DEBUG_LOG("attachment_a_tbl->attachment_name [%s], input_attachment_b_data->name [%s]", attachment_a_tbl->attachment_name, input_attachment_b_data->attachment_name);
+               *result = strcmp(attachment_a_tbl->attachment_name, input_attachment_b_data->attachment_name);
+       }
+
+       ret = true;
+
+FINISH_OFF: 
+
+       if (attachment_a_tbl)
+               emstorage_free_attachment(&attachment_a_tbl, 1, &err_2);
+       EM_DEBUG_FUNC_END("*result [%d]", *result);
+       return ret;
+}
+
+
+/* description 
+ *    copy a mail to mail box
+ * arguments  
+ *    src_mailbox  :  source mail box
+ *    msgno  :  mail sequence
+ *    dst_mailbox  :  target mail box
+ * return  
+ *    succeed  :  1
+ *    fail  :  0
+ */
+INTERNAL_FUNC int emcore_mail_copy(int mail_id, email_mailbox_t *dst_mailbox, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], dst_mailbox[%p], err_code[%p]", mail_id, dst_mailbox, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int i;
+       emstorage_mail_tbl_t *mail = NULL;
+       emstorage_attachment_tbl_t *atch_list = NULL;
+       char buf[512];
+       int count = EMAIL_ATTACHMENT_MAX_COUNT;
+       char *mailbox_name = NULL;
+
+       if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if ( (err = emstorage_get_attachment_list(mail_id, true, &atch_list, &count)) != EMAIL_ERROR_NONE ){
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       /*  get increased uid. */
+       if (!emstorage_increase_mail_id(&mail->mail_id, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_increase_mail_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       /*  copy mail body(text) file */
+       if (mail->file_path_plain)  {
+               if (!emstorage_create_dir(dst_mailbox->account_id, mail->mail_id, 0, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+
+               gchar *filename = g_path_get_basename(mail->file_path_plain);
+
+               if (!emstorage_get_save_name(dst_mailbox->account_id, mail->mail_id, 0, filename, buf, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       g_free(filename);
+
+                       goto FINISH_OFF;
+               }
+
+               g_free(filename);
+
+               if (!emstorage_copy_file(mail->file_path_plain, buf, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+
+               mail->file_path_plain = EM_SAFE_STRDUP(buf);
+       }
+
+       /*  copy mail body(html) file */
+       if (mail->file_path_html)  {
+               if (!emstorage_create_dir(dst_mailbox->account_id, mail->mail_id, 0, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+
+               gchar *filename = g_path_get_basename(mail->file_path_html);
+
+               if (!emstorage_get_save_name(dst_mailbox->account_id, mail->mail_id, 0, filename, buf, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       g_free(filename);
+
+                       goto FINISH_OFF;
+               }
+
+               g_free(filename);
+
+               if (!emstorage_copy_file(mail->file_path_html, buf, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
+       
+                       goto FINISH_OFF;
+               }
+
+               mail->file_path_html = EM_SAFE_STRDUP(buf);
+       }
+
+       /*  BEGIN TRANSACTION; */
+       emstorage_begin_transaction(NULL, NULL, NULL);
+
+       /*  insert mail data */
+       EM_SAFE_FREE(mail->mailbox_name);
+       
+       mail->account_id   = dst_mailbox->account_id;
+       mail->mailbox_id   = dst_mailbox->mailbox_id;
+       mail->mailbox_name = EM_SAFE_STRDUP(dst_mailbox->mailbox_name);
+       mail->mailbox_type = dst_mailbox->mailbox_type;
+       
+       if (!emstorage_add_mail(mail, 0, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_add_mail failed [%d]", err);
+
+               if (mail->file_path_plain)  {
+                       if (!emstorage_delete_file(mail->file_path_plain, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_delete_file failed [%d]", err);
+                               emstorage_rollback_transaction(NULL, NULL, NULL);
+                               goto FINISH_OFF;
+                       }
+               }
+               if (mail->file_path_html) {
+                       if (!emstorage_delete_file(mail->file_path_html, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_delete_file failed [%d]", err);
+                               emstorage_rollback_transaction(NULL, NULL, NULL);
+                               goto FINISH_OFF;
+                       }
+               }
+
+               /*  ROLLBACK TRANSACTION; */
+               emstorage_rollback_transaction(NULL, NULL, NULL);
+
+
+               goto FINISH_OFF;
+       }
+
+       /*  copy attachment file */
+       for (i = 0; i<count; i++)  {
+               if (atch_list[i].attachment_path)  {
+                       if (!emstorage_create_dir(dst_mailbox->account_id, mail->mail_id, i+1, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                               break;
+                       }
+                       
+                       if (!emstorage_get_save_name(dst_mailbox->account_id, mail->mail_id, i+1, atch_list[i].attachment_name, buf, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                               break;
+                       }
+
+                       if (!emstorage_copy_file(atch_list[i].attachment_path, buf, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
+                               break;
+                       }
+
+                       EM_SAFE_FREE(atch_list[i].attachment_path);
+
+                       atch_list[i].attachment_path = EM_SAFE_STRDUP(buf);
+               }
+
+               atch_list[i].account_id = dst_mailbox->account_id;
+               atch_list[i].mail_id = mail->mail_id;
+               atch_list[i].mailbox_id = mail->mailbox_id;
+
+               if (!emstorage_add_attachment(&atch_list[i], 0, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_add_attachment failed [%d]", err);
+
+                       break;
+               }
+       }
+
+       /*  in case error happened, delete copied file. */
+       if (i && i != count)  {
+               for (;i >= 0; i--)  {
+                       if (atch_list[i].attachment_path)  {
+                       
+                               if (!emstorage_delete_file(atch_list[i].attachment_path, &err))  {
+                                       EM_DEBUG_EXCEPTION("emstorage_delete_file failed [%d]", err);
+                                       emstorage_rollback_transaction(NULL, NULL, NULL);
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+
+               if (mail->file_path_plain)  {
+                       if (!emstorage_delete_file(mail->file_path_plain, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_delete_file failed [%d]", err);
+                               emstorage_rollback_transaction(NULL, NULL, NULL);
+                               goto FINISH_OFF;
+                       }
+               }
+               if (mail->file_path_html)  {
+                       if (!emstorage_delete_file(mail->file_path_html, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_delete_file failed [%d]", err);
+                               emstorage_rollback_transaction(NULL, NULL, NULL);
+                               goto FINISH_OFF;
+                       }
+               }
+
+               /*  ROLLBACK TRANSACTION; */
+               emstorage_rollback_transaction(NULL, NULL, NULL);
+               goto FINISH_OFF;
+       }
+
+       if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+               err = EMAIL_ERROR_DB_FAILURE;
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       err = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_mailbox_name_by_mailbox_type(dst_mailbox->account_id, EMAIL_MAILBOX_TYPE_INBOX, &mailbox_name, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!strcmp(dst_mailbox->mailbox_name, mailbox_name) && !(mail->flags_seen_field))
+               emcore_display_unread_in_badge();
+
+       ret = true;
+
+FINISH_OFF: 
+       if (atch_list != NULL)
+               emstorage_free_attachment(&atch_list, count, NULL);
+
+       if (mail != NULL)
+               emstorage_free_mail(&mail, 1, NULL);
+
+       EM_SAFE_FREE(mailbox_name);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+
+/* description
+ *    move a mail to mail box
+ * arguments
+ *    old_mailbox  :  previous mail box
+ *    msgno  :  msgno
+ *    new_mailbox  :  target mail box
+ * return
+ *    succeed  :  1
+ *    fail  :  0
+ */
+INTERNAL_FUNC int emcore_move_mail(int mail_ids[], int mail_ids_count, int dst_mailbox_id, int noti_param_1, int noti_param_2 ,int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], mail_ids_count[%d], dst_mailbox_id[%d], noti_param [%d], err_code[%p]", mail_ids, mail_ids_count, dst_mailbox_id, noti_param_1, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *mail_list = NULL;
+       int account_id = 0;
+       int i = 0, parameter_string_length = 0;
+       char *parameter_string = NULL, mail_id_string[10];
+
+       if ( dst_mailbox_id <= 0  && mail_ids_count < 1) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_mail_field_by_multiple_mail_id(mail_ids, mail_ids_count, RETRIEVE_FLAG, &mail_list, true, &err) || !mail_list) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_field_by_multiple_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       account_id = mail_list[0].account_id;
+
+       if(!emstorage_move_multiple_mails_on_db(account_id, dst_mailbox_id, mail_ids, mail_ids_count, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_move_multiple_mails_on_db failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       /* Sending a notification */
+       parameter_string_length = sizeof(char) * (mail_ids_count * 10 + 128/*MAILBOX_LEN_IN_MAIL_TBL*/ * 2);
+       parameter_string = em_malloc(parameter_string_length);
+
+       if (parameter_string == NULL) {
+               EM_DEBUG_EXCEPTION("Memory allocation for mail_id_list_string failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (mail_list[0].mailbox_id > 0)
+               SNPRINTF(parameter_string, parameter_string_length, "%d%c%d%c", mail_list[0].mailbox_id, 0x01, dst_mailbox_id , 0x01);
+
+       for (i = 0; i < mail_ids_count; i++) {
+               memset(mail_id_string, 0, 10);
+               SNPRINTF(mail_id_string, 10, "%d,", mail_ids[i]);
+               strcat(parameter_string, mail_id_string);
+       }
+       
+       EM_DEBUG_LOG("num : [%d], param string : [%s]", mail_ids_count , parameter_string);
+
+       if (!emcore_notify_storage_event(NOTI_MAIL_MOVE, account_id, noti_param_1, parameter_string, noti_param_2))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event failed [NOTI_MAIL_MOVE] >>>> ");
+
+
+       for (i = 0; i < mail_ids_count; i++) {
+               if (!emstorage_update_latest_thread_mail(account_id, mail_list[i].thread_id, 0, 0, true, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_update_latest_thread_mail failed [%d]", err);
+       }
+
+       if (!emcore_notify_storage_event(NOTI_MAIL_MOVE_FINISH, account_id, noti_param_1, parameter_string, noti_param_2))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event failed [NOTI_MAIL_MOVE_FINISH] >>>> ");
+
+       emcore_display_unread_in_badge();
+
+       ret = true;
+
+FINISH_OFF:
+       emstorage_free_mail(&mail_list, mail_ids_count, NULL);
+       EM_SAFE_FREE(parameter_string);
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_move_mail_on_server(int account_id, int src_mailbox_id,  int mail_ids[], int num, char *dest_mailbox, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       MAILSTREAM *stream = NULL;
+       int err_code = 0;
+       email_account_t *ref_account = NULL;
+       emstorage_mail_tbl_t *mail = NULL;
+       int ret = 1;
+       int mail_id = 0;
+       int i = 0;
+       
+       mail_id = mail_ids[0];
+       
+       ref_account = emcore_get_account_reference(account_id);
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_move_mail_on_server failed  :  get account reference[%d]", account_id);
+               *error_code = EMAIL_ERROR_INVALID_ACCOUNT;
+               ret = 0;
+               goto FINISH_OFF;
+       }
+
+       /* if not imap4 mail, return */
+       if (ref_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               *error_code = EMAIL_ERROR_INVALID_PARAM;
+               ret = 0;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < num; i++)  {
+               mail_id = mail_ids[i];
+
+               if (!emstorage_get_mail_by_id(mail_id, &mail, false, &err_code) || !mail)  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_uid_by_mail_id  :  emstorage_get_downloaded_mail failed [%d]", err_code);
+                       mail = NULL;
+                       if (err_code == EMAIL_ERROR_MAIL_NOT_FOUND)  {  /*  not server mail */
+                               /* err = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER; */
+                               /* continue; */
+                       }
+                       else {
+                               *error_code = err_code;
+                       }
+
+                       ret = 0;
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_connect_to_remote_mailbox(account_id, src_mailbox_id, (void **)&stream, &err_code))         /* faizan.h@samsung.com mail_move_fix_07042009 */ {
+                       EM_DEBUG_EXCEPTION("emcore_move_mail_on_server failed :  Mailbox open[%d]", err_code);
+
+                       ret = 0;
+                       goto FINISH_OFF;
+               }
+
+               if (stream) {
+                       /* set callback for COPY_UID */
+                       mail_parameters(stream, SET_COPYUID, emcore_mail_copyuid);
+
+                       EM_DEBUG_LOG("calling mail_copy_full FODLER MAIL COPY ");
+                       
+                       if (mail->server_mail_id) {
+                               if (!mail_copy_full(stream, mail->server_mail_id, dest_mailbox, CP_UID | CP_MOVE)) {
+                                       EM_DEBUG_EXCEPTION("emcore_move_mail_on_server :   Mail cannot be moved failed");
+                                       ret = 0;
+                               }
+                               else {
+                                       /*  send EXPUNGE command */
+                                       if (!imap4_send_command(stream, IMAP4_CMD_EXPUNGE, &err_code)) {
+                                               EM_DEBUG_EXCEPTION("imap4_send_command failed [%d]", err_code);
+
+                                               if (err_code == EMAIL_ERROR_IMAP4_STORE_FAILURE)
+                                                       err_code = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       /* faizan.h@samsung.com   duplicate copy while sync mailbox issue fixed */
+                                       EM_DEBUG_LOG(">>>mailbox_name[%s]>>>>>>", mail->mailbox_name);
+                                       EM_DEBUG_LOG(">>>g_new_server_uid[%s]>>>>>>", g_new_server_uid);
+                                       EM_DEBUG_LOG(">>>mail_id[%d]>>>>>>", mail_id);
+
+                                       if (!emstorage_update_read_mail_uid(mail_id, g_new_server_uid, mail->mailbox_name, &err_code)) {
+                                               EM_DEBUG_EXCEPTION("emstorage_update_read_mail_uid failed [%d]", err_code);
+                                               goto FINISH_OFF;
+                                       }
+
+                                       EM_DEBUG_LOG("Mail MOVE SUCCESS ");
+                               }
+                       }
+                       else
+                               EM_DEBUG_EXCEPTION(">>>> Server MAIL ID IS NULL >>>> ");
+               }
+               else {
+                       EM_DEBUG_EXCEPTION(">>>> STREAM DATA IS NULL >>> ");
+                       ret = 0;
+                       goto FINISH_OFF;
+               }
+       }
+
+       /* ret = true; */
+
+FINISH_OFF:
+       if (stream) emcore_close_mailbox(account_id, stream);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (mail != NULL)
+               emstorage_free_mail(&mail, 1, NULL);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+static int emcore_copy_mail_to_another_account_on_local_storeage(int input_mail_id, emstorage_mailbox_tbl_t *input_source_mailbox, emstorage_mailbox_tbl_t *input_target_mailbox, int input_task_id, int *output_mail_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d] input_source_mailbox[%p] input_target_mailbox[%p] input_task_id [%d] output_mail_id[%p]", input_mail_id, input_source_mailbox, input_target_mailbox, input_task_id, output_mail_id);
+
+       int err = EMAIL_ERROR_NONE;
+       int   attachment_count = 0;
+       email_mail_data_t       *mail_data = NULL;
+       email_attachment_data_t *attachment_data = NULL;
+
+       if ( input_source_mailbox == NULL || input_target_mailbox == NULL || input_mail_id <= 0 || output_mail_id == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if((err = emcore_get_mail_data(input_mail_id, &mail_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_data failed [%d]", err);
+               err = EMAIL_ERROR_INVALID_MAIL;
+               goto FINISH_OFF;
+       }
+
+       /* Check download status */
+       if(mail_data->body_download_status != 1) {
+               /* If not downloaded, download fully */
+               if (!emcore_download_body_multi_sections_bulk(NULL,
+                                       input_source_mailbox->account_id,
+                                       input_mail_id,
+                                       0,
+                                       (mail_data->attachment_count > 0)?1:0,
+                                       NO_LIMITATION,
+                                       input_task_id,
+                                       &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_download_body_multi_sections_bulk failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       /* Get attachments */
+       if((err = emcore_get_attachment_data_list(input_mail_id, &attachment_data, &attachment_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_attachment_data_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       mail_data->account_id        = input_target_mailbox->account_id;
+       mail_data->mail_id           = 0;
+       mail_data->mailbox_id        = input_target_mailbox->mailbox_id;
+       mail_data->mailbox_type      = input_target_mailbox->mailbox_type;
+       mail_data->thread_id         = 0;
+       mail_data->thread_item_count = 0;
+
+       if((err = emcore_add_mail(mail_data, attachment_data, attachment_count, NULL, false)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_add_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       *output_mail_id = mail_data->mail_id;
+
+FINISH_OFF:
+       if (mail_data) {
+               emcore_free_mail_data(mail_data);
+               free(mail_data);                /* prevent 34648 */
+       }
+
+       if (attachment_data)
+               emcore_free_attachment_data(&attachment_data, attachment_count, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_move_mail_to_another_account(int input_mail_id, int input_source_mailbox_id, int input_target_mailbox_id, int input_task_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d] input_source_mailbox_id[%d] input_target_mailbox_id[%d] result_mail_id[%p] input_task_id [%d]", input_mail_id, input_source_mailbox_id, input_target_mailbox_id, input_task_id);
+       int err = EMAIL_ERROR_NONE;
+       int err_for_delete_mail = EMAIL_ERROR_NONE;
+       int moved_mail_id = 0;
+       emstorage_mailbox_tbl_t *source_mailbox = NULL;
+       emstorage_mailbox_tbl_t *target_mailbox = NULL;
+       email_account_t *source_account_ref = NULL;
+       email_account_t *target_account_ref = NULL;
+
+       if((err = emstorage_get_mailbox_by_id(input_source_mailbox_id, &source_mailbox)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed for source_mailbox [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if((err = emstorage_get_mailbox_by_id(input_target_mailbox_id, &target_mailbox)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed for target_mailbox [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Check account type */
+       /* POP  -> IMAP possible */
+       /* IMAP -> POP  possible, but the mail would not be on server */
+       /* EAS  -> X    impossible */
+       /* X    -> EAS  impossible */
+
+       source_account_ref = emcore_get_account_reference(source_mailbox->account_id);
+
+       if(source_account_ref == NULL || source_account_ref->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               EM_DEBUG_EXCEPTION("Invalid account");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       target_account_ref = emcore_get_account_reference(target_mailbox->account_id);
+
+       if(target_account_ref == NULL || target_account_ref->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               EM_DEBUG_EXCEPTION("Invalid account");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+
+       if((err = emcore_copy_mail_to_another_account_on_local_storeage(input_mail_id, source_mailbox, target_mailbox, input_task_id, &moved_mail_id)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_copy_mail_to_another_account_on_local_storeage failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(!emcore_set_flags_field(source_mailbox->account_id, &input_mail_id, 1, EMAIL_FLAGS_DELETED_FIELD, 1 , &err)) {
+               EM_DEBUG_EXCEPTION("emcore_set_flags_field failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(target_account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+               if((err = emcore_sync_mail_from_client_to_server(moved_mail_id)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_sync_mail_from_client_to_server failed [%d]", err);
+
+                       /* if append is failed, restore source mail and delete copied mail. */
+                       if(!emcore_set_flags_field(source_mailbox->account_id, &input_mail_id, 1, EMAIL_FLAGS_DELETED_FIELD, 0 , &err)) {
+                               EM_DEBUG_EXCEPTION("emcore_set_flags_field failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if(!emcore_delete_mail(target_mailbox->account_id, &moved_mail_id, 1, false, 0, 0, &err_for_delete_mail))
+                               EM_DEBUG_EXCEPTION("emcore_delete_mail failed [%d]", err_for_delete_mail);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if(!emcore_delete_mail(source_mailbox->account_id, &input_mail_id, 1, true, 0, 0, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_delete_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+
+FINISH_OFF:
+       if (source_mailbox)
+               emstorage_free_mailbox(&source_mailbox, 1, NULL);
+
+       if (target_mailbox)
+               emstorage_free_mailbox(&target_mailbox, 1, NULL);
+
+       if (source_account_ref) {
+               emcore_free_account(source_account_ref);
+               EM_SAFE_FREE(source_account_ref);
+       }
+
+       if (target_account_ref) {
+               emcore_free_account(target_account_ref);
+               EM_SAFE_FREE(target_account_ref);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_save_mail_file(int account_id, int mail_id, int attachment_id, char *src_file_path, char *file_name, char *full_path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], attachment_id[%d] , file_name[%p] , full_path[%p] , err_code[%p]", account_id, mail_id, attachment_id, file_name, full_path, err_code);
+
+       int ret = false, err = EMAIL_ERROR_NONE;
+
+       if (!file_name || !full_path || !src_file_path) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_create_dir(account_id, mail_id, attachment_id, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       if (!emstorage_get_save_name(account_id, mail_id, attachment_id, file_name, full_path, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (strcmp(src_file_path, full_path) != 0)  {
+               if (!emstorage_copy_file(src_file_path, full_path, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       return 1;
+}
+
+/* description : update mail information */
+INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count[%d], input_meeting_request[%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+
+       char                   filename_buf[1024]         = {0, };
+       char                  *body_text_file_name        = NULL;
+       int                    i                          = 0;
+       int                    err                        = EMAIL_ERROR_NONE;
+       int                    local_inline_content_count = 0;
+       emstorage_mail_tbl_t  *converted_mail_tbl_data    = NULL;
+       email_meeting_request_t *meeting_req = NULL;
+       struct stat            st_buf;
+
+       if (!input_mail_data || (input_attachment_count && !input_attachment_data_list) || (!input_attachment_count &&input_attachment_data_list))  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF2;
+       }
+
+       if(input_from_eas == 0) {
+               if (input_mail_data->file_path_plain)  {
+                       if (stat(input_mail_data->file_path_plain, &st_buf) < 0)  {
+                               EM_DEBUG_EXCEPTION("input_mail_data->file_path_plain, stat(\"%s\") failed...", input_mail_data->file_path_plain);
+                               err = EMAIL_ERROR_INVALID_MAIL;
+                               goto FINISH_OFF;
+                       }
+               }
+               
+               if (input_mail_data->file_path_html)  {
+                       if (stat(input_mail_data->file_path_html, &st_buf) < 0)  {
+                               EM_DEBUG_EXCEPTION("input_mail_data->file_path_html, stat(\"%s\") failed...", input_mail_data->file_path_html);
+                               err = EMAIL_ERROR_INVALID_MAIL;
+                               goto FINISH_OFF;
+                       }
+               }
+               
+               if (input_attachment_count && input_attachment_data_list)  {
+                       for (i = 0; i < input_attachment_count; i++)  {
+                               if (input_attachment_data_list[i].save_status) {
+                                       if (!input_attachment_data_list[i].attachment_path || stat(input_attachment_data_list[i].attachment_path, &st_buf) < 0)  {
+                                               EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", input_attachment_data_list[i].attachment_path);
+                                               err = EMAIL_ERROR_INVALID_ATTACHMENT;
+                                               goto FINISH_OFF;
+                                       }
+                               }
+                       }
+               }
+       }
+       
+       if(input_mail_data->mail_size == 0) {
+                emcore_calc_mail_size(input_mail_data, input_attachment_data_list, input_attachment_count, &(input_mail_data->mail_size));
+       }
+
+       if (input_mail_data->file_path_plain)  {   /*  Save plain text body. */
+               if ( (err = em_get_file_name_from_file_path(input_mail_data->file_path_plain, &body_text_file_name)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("em_get_file_name_from_file_path failed [%d]", err);
+                       err = EMAIL_ERROR_INVALID_FILE_PATH;
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_save_mail_file(input_mail_data->account_id, input_mail_data->mail_id, 0, input_mail_data->file_path_plain, body_text_file_name, filename_buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_save_mail_file failed [%d]", err);
+                       goto FINISH_OFF2;
+               }
+               EM_SAFE_FREE(input_mail_data->file_path_plain);
+               input_mail_data->file_path_plain = EM_SAFE_STRDUP(filename_buf);
+       }
+       
+       if (input_mail_data->file_path_html)  {   /*  Save HTML text body. */
+               EM_SAFE_FREE(body_text_file_name);
+               if ( (err = em_get_file_name_from_file_path(input_mail_data->file_path_html, &body_text_file_name)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("em_get_file_name_from_file_path failed [%d]", err);
+                       err = EMAIL_ERROR_INVALID_FILE_PATH;
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_save_mail_file(input_mail_data->account_id, input_mail_data->mail_id, 0, input_mail_data->file_path_html, body_text_file_name, filename_buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_save_mail_file failed [%d]", err);
+                       goto FINISH_OFF2;
+               }
+               EM_SAFE_FREE(input_mail_data->file_path_html);
+               input_mail_data->file_path_html = EM_SAFE_STRDUP(filename_buf);
+       }
+
+       if (input_mail_data->file_path_mime_entity)  {   /*  Save mime entity. */
+               if (!emcore_save_mail_file(input_mail_data->account_id, input_mail_data->mail_id, 0, input_mail_data->file_path_mime_entity, "mime_entity", filename_buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_save_mail_file failed [%d]", err);
+                       goto FINISH_OFF2;
+               }
+               EM_SAFE_FREE(input_mail_data->file_path_mime_entity);
+               input_mail_data->file_path_mime_entity = EM_SAFE_STRDUP(filename_buf);
+       }
+
+       if (input_attachment_data_list && input_attachment_count)  {
+               int i = 0;
+               int compare_result = 1;
+               email_attachment_data_t *temp_attachment_data = NULL;
+
+               for(i = 0; i < input_attachment_count; i++) {
+                       temp_attachment_data = input_attachment_data_list + i;
+                       if ( (err = emcore_mail_compare_filename_of_attachment_data(input_mail_data->mail_id, temp_attachment_data->attachment_id, temp_attachment_data, &compare_result)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emcore_mail_compare_filename_of_attachment_data failed [%d]", err);
+                               compare_result = 1;
+                       }
+       
+                       if (compare_result == 0) {
+                               EM_DEBUG_LOG("file name and attachment id are same, update exising attachment");
+                               if (!emcore_mail_update_attachment_data(input_mail_data->mail_id, temp_attachment_data))  {
+                                       EM_DEBUG_EXCEPTION("emcore_mail_update_attachment_data failed [%d]", err);
+                                       goto FINISH_OFF2;
+                               }
+                       }
+                       else {
+                               EM_DEBUG_LOG("save names are different");
+                               if(temp_attachment_data->attachment_id > 0) {
+                                       if (!emcore_delete_mail_attachment(temp_attachment_data->attachment_id, &err)) {
+                                               EM_DEBUG_EXCEPTION("emcore_delete_mail_attachment failed [%d]", err);
+                                               goto FINISH_OFF2;
+                                       }
+                               }
+
+                               if ( (err = emcore_mail_add_attachment_data(input_mail_data->mail_id, temp_attachment_data)) != EMAIL_ERROR_NONE)  {
+                                       EM_DEBUG_EXCEPTION("emcore_mail_add_attachment failed [%d]", err);
+                                       goto FINISH_OFF2;
+                               }
+                       }
+
+                       if (temp_attachment_data->inline_content_status)
+                               local_inline_content_count++;
+               }
+       }
+       
+       input_mail_data->attachment_count     = input_attachment_count;
+       input_mail_data->inline_content_count = local_inline_content_count;
+
+       if (!input_mail_data->date_time) {
+               /* time isn't set */
+               input_mail_data->date_time = time(NULL);
+       }
+
+       EM_DEBUG_LOG("preview_text[%p]", input_mail_data->preview_text);
+       if (input_mail_data->preview_text == NULL) {
+               if ( (err =emcore_get_preview_text_from_file(input_mail_data->file_path_plain, input_mail_data->file_path_html, MAX_PREVIEW_TEXT_LENGTH, &(input_mail_data->preview_text))) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_get_preview_text_from_file failed[%d]", err);
+                       if (err != EMAIL_ERROR_EMPTY_FILE)
+                               goto FINISH_OFF2;
+               }
+       }
+
+       if(!em_convert_mail_data_to_mail_tbl(input_mail_data, 1, &converted_mail_tbl_data,  &err)) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_data_to_mail_tbl failed[%d]", err);
+               goto FINISH_OFF2;
+       }
+       
+       /*  BEGIN TRANSACTION; */
+       emstorage_begin_transaction(NULL, NULL, NULL);
+       
+       if (!emstorage_change_mail_field(input_mail_data->mail_id, UPDATE_MAIL, converted_mail_tbl_data, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+       
+       if (input_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_REQUEST
+               || input_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_RESPONSE
+               || input_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST) {
+               /*  check where there is a meeting request in DB */
+               if (!emstorage_get_meeting_request(input_mail_data->mail_id, &meeting_req, false, &err) && err != EMAIL_ERROR_DATA_NOT_FOUND) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_meeting_request failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               EM_SAFE_FREE(meeting_req);
+               if (err == EMAIL_ERROR_DATA_NOT_FOUND) {        /*  insert */
+                       emstorage_mail_tbl_t *original_mail = NULL;
+
+                       if (!emstorage_get_mail_by_id(input_mail_data->mail_id, &original_mail, false, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if (original_mail)       {
+                       if (!emstorage_add_meeting_request(input_mail_data->account_id, original_mail->mailbox_id, input_meeting_request, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_add_meeting_request failed [%d]", err);
+
+                               goto FINISH_OFF;
+                       }
+                               emstorage_free_mail(&original_mail, 1, NULL);
+               }
+               }
+               else {  /*  update */
+                       if (!emstorage_update_meeting_request(input_meeting_request, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_update_meeting_request failed [%d]", err);
+
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+       
+FINISH_OFF: 
+       if (err == EMAIL_ERROR_NONE) {
+               /*  COMMIT TRANSACTION; */
+               if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+                       err = EMAIL_ERROR_DB_FAILURE;
+               }
+
+               if (input_mail_data->meeting_request_status && !emcore_notify_storage_event(NOTI_MAIL_UPDATE, input_mail_data->account_id, input_mail_data->mail_id, NULL, UPDATE_MEETING))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event failed [ NOTI_MAIL_UPDATE : UPDATE_MEETING_RESPONSE ] >>>> ");
+       }
+       else {
+               /*  ROLLBACK TRANSACTION; */
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       err = EMAIL_ERROR_DB_FAILURE;
+       }
+       
+FINISH_OFF2:
+
+       EM_SAFE_FREE(body_text_file_name);
+
+       if(meeting_req)
+               emstorage_free_meeting_request(meeting_req);
+
+       if(converted_mail_tbl_data)
+               emstorage_free_mail(&converted_mail_tbl_data, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+INTERNAL_FUNC int emcore_set_flags_field(int account_id, int mail_ids[], int num, email_flags_field_type field_type, int value, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], mail_ids[%p], num [%d], field_type [%d], value[%d], err_code[%p]", account_id, mail_ids, num, field_type, value, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       char *field_type_name[EMAIL_FLAGS_FIELD_COUNT] = { "flags_seen_field"
+               , "flags_deleted_field", "flags_flagged_field", "flags_answered_field"
+               , "flags_recent_field", "flags_draft_field", "flags_forwarded_field" };
+
+       if(field_type < 0 || field_type >= EMAIL_FLAGS_FIELD_COUNT || mail_ids == NULL || num <= 0 || account_id == 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto  FINISH_OFF;
+       }
+
+       if (!emstorage_set_field_of_mails_with_integer_value(account_id, mail_ids, num, field_type_name[field_type], value, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(field_type == EMAIL_FLAGS_SEEN_FIELD)
+               emcore_display_unread_in_badge();
+
+       ret = true;
+       
+FINISH_OFF: 
+       
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);     
+       return ret;
+}
+
+int emcore_mail_cmd_read_mail_pop3(void *stream, int msgno, int limited_size, int *downloded_size, int *result_total_body_size, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msgno[%d], limited_size[%d], err_code[%p]", stream, msgno, limited_size, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int total_body_size = 0;
+       char command[32];
+       char *response = NULL;
+       POP3LOCAL *pop3local;
+       
+       if (!stream || !result_total_body_size)  {
+               EM_DEBUG_EXCEPTION("stream[%p], total_body_size[%p]", stream, msgno, result_total_body_size);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       pop3local = (POP3LOCAL *)(((MAILSTREAM *)stream)->local);
+
+       if (!pop3local  || !pop3local->netstream)  {
+               err = EMAIL_ERROR_INVALID_STREAM;
+               goto FINISH_OFF;
+       }
+       memset(command, 0x00, sizeof(command));
+
+       SNPRINTF(command, sizeof(command), "LIST %d\015\012", msgno);
+
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG("[POP3] >>> [%s]", command);
+#endif
+
+       
+       /*  send command  :  LIST [msgno] - to get the size of the mail */
+       if (!net_sout(pop3local->netstream, command, (int)EM_SAFE_STRLEN(command)))  {
+               EM_DEBUG_EXCEPTION("net_sout failed...");
+
+               err = EMAIL_ERROR_INVALID_RESPONSE;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("Sending command success");
+
+       while (pop3local->netstream) {
+               /*  receive response */
+               if (!(response = net_getline(pop3local->netstream)))
+                       break;
+
+               if (response)
+                       EM_DEBUG_LOG("[POP3] <<< %s", response);
+
+               if (*response == '.')  {
+                       EM_SAFE_FREE(response);
+                       break;
+               }
+
+               if (*response == '+')  {                /*  "+ OK" */
+                       char *p = NULL;
+
+                       if (!(p = strchr(response + strlen("+OK "), ' ')))  {
+                               err = EMAIL_ERROR_INVALID_RESPONSE;
+                               goto FINISH_OFF;
+                       }
+
+                       total_body_size = atoi(p + 1);
+                       EM_DEBUG_LOG("Body size [%d]", total_body_size);
+
+                       if (result_total_body_size) {
+                               *result_total_body_size = total_body_size;
+                               break;
+                       }
+               }
+               else if (*response == '-')  {   /*  "- ERR" */
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+               else  {
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+
+               EM_SAFE_FREE(response);
+       }
+
+       memset(command, 0x00, sizeof(command));
+
+       if (limited_size && total_body_size > limited_size) {
+               int count_of_line = limited_size / 80;
+               SNPRINTF(command, sizeof(command), "TOP %d %d", msgno, count_of_line);
+       }
+       else
+               SNPRINTF(command, sizeof(command), "RETR %d", msgno);
+
+       EM_DEBUG_LOG("[POP3] >>> %s", command);
+
+       emcore_set_network_error(EMAIL_ERROR_NONE);             /*  set current network error as EMAIL_ERROR_NONE before network operation */
+       /*  get mail from mail server */
+       if (!pop3_send((MAILSTREAM *)stream, command, NULL))  {
+               EM_DEBUG_EXCEPTION("pop3_send failed...");
+
+               email_session_t *session = NULL;
+               
+               if (!emcore_get_current_session(&session))  {
+                       EM_DEBUG_EXCEPTION("emcore_get_current_session failed...");
+                       err = EMAIL_ERROR_SESSION_NOT_FOUND;
+                       goto FINISH_OFF;
+               }
+
+               if (session->network == EMAIL_ERROR_NONE)
+                       err = EMAIL_ERROR_UNKNOWN;
+               else
+                       err = session->network;
+
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+       
+FINISH_OFF: 
+       EM_SAFE_FREE(response);
+       
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("err [%d]", err);     
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_sync_flag_with_server(int mail_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%p], err_code[%p]", mail_id, err_code);
+               
+       if (mail_id < 1)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int status = EMAIL_DOWNLOAD_FAIL;
+       MAILSTREAM *stream = NULL;
+       email_internal_mailbox_t mailbox = {0};
+       emstorage_mail_tbl_t *mail = NULL;
+       email_account_t *ref_account = NULL;
+       int account_id = 0;
+       int msgno = 0;
+       char set_flags[100] = { 0, };
+       char clear_flags[100] = { 0, };
+       char tmp[100] = { 0, };
+       
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+       
+       if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       account_id = mail->account_id;
+
+       if (!(ref_account = emcore_get_account_reference(account_id)))   {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+       
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       /*  open mail server. */
+       if (!emcore_connect_to_remote_mailbox(account_id, mail->mailbox_id, (void **)&stream, &err) || !stream)  {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               status = EMAIL_LIST_CONNECTION_FAIL;
+               goto FINISH_OFF;
+       }
+
+
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       mailbox.mailbox_name = mail->mailbox_name;      
+       mailbox.account_id = account_id;
+       mailbox.mail_stream = stream;
+
+       /*  download all uids from server. */
+       if (!emcore_get_mail_msgno_by_uid(ref_account, &mailbox, mail->server_mail_id, &msgno, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_msgno_by_uid failed message_no  :  %d ", err);
+               goto FINISH_OFF;
+       }
+               
+       sprintf (tmp, "%d", msgno);
+
+       if (mail->flags_seen_field)
+               sprintf(set_flags, "\\Seen");
+       else
+               sprintf(clear_flags, "\\Seen");
+
+       if (mail->flags_answered_field)
+               sprintf(set_flags, "%s \\Answered", set_flags);
+       else
+               sprintf(clear_flags, "%s \\Answered", clear_flags);
+               
+       if (mail->flags_flagged_field)
+               sprintf(set_flags, "%s \\Flagged", set_flags);
+       else
+               sprintf(clear_flags, "%s \\Flagged", clear_flags);
+
+       if (mail->flags_forwarded_field)
+               sprintf(set_flags, "%s $Forwarded", set_flags);
+       else
+               sprintf(clear_flags, "%s $Forwarded", clear_flags);
+
+       if (EM_SAFE_STRLEN(set_flags) > 0)  {
+               EM_DEBUG_LOG(">>>> Calling mail_setflag [%s] ", set_flags);
+               mail_flag(stream, tmp, set_flags, ST_SET | ST_SILENT);
+               EM_DEBUG_LOG(">>>> End mail_setflag ");
+       }
+
+       if (EM_SAFE_STRLEN(clear_flags) > 0)  {
+               EM_DEBUG_LOG(">>>> Calling mail_clearflag [%s]", clear_flags);
+               mail_clearflag(stream, tmp, clear_flags);
+               EM_DEBUG_LOG(">>>> End mail_clearflag ");
+       }
+               
+       if (mail->lock_status) {
+               memset(set_flags, 0x00, 100);
+               sprintf(set_flags, "Sticky");
+               if (EM_SAFE_STRLEN(set_flags) > 0)  {
+                       EM_DEBUG_LOG(">>>> Calling mail_setflag [%s]", set_flags);
+                       mail_flag(stream, tmp, set_flags, ST_SET | ST_SILENT);
+                       EM_DEBUG_LOG(">>>> End mail_setflag ");
+               }
+       }
+
+       EM_DEBUG_LOG(">>>> Returning from emcore_sync_flag_with_server ");
+
+       if (!emcore_check_thread_status())  {
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF: 
+       
+       if (stream)
+               emcore_close_mailbox(account_id, stream);
+
+       if (mail)
+               emstorage_free_mail(&mail, 1, NULL);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("err [%d]", err);     
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_sync_seen_flag_with_server(int mail_ids[], int num, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], err_code[%p]", mail_ids[0], err_code);
+
+       if (mail_ids[0] < 1)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int status = EMAIL_DOWNLOAD_FAIL;
+       MAILSTREAM *stream = NULL;
+       email_internal_mailbox_t mailbox;
+       emstorage_mail_tbl_t *mail = NULL;
+       email_account_t *ref_account = NULL;
+       int account_id = 0;
+       int msgno = 0;
+       char set_flags[100];
+       char clear_flags[100];
+       char tmp[100];
+       int mail_id = 0;
+       int i = 0;
+
+       memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+
+       mail_id = mail_ids[0];
+
+       if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       account_id = mail->account_id;
+
+       if (!(ref_account = emcore_get_account_reference(account_id))) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+       
+       /*  open mail server. */
+       if (!emcore_connect_to_remote_mailbox(account_id, mail->mailbox_id, (void **)&stream, &err) || !stream)  {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               status = EMAIL_LIST_CONNECTION_FAIL;
+               goto FINISH_OFF;
+       }
+
+       mailbox.mailbox_name = mail->mailbox_name;
+       mailbox.account_id = account_id;
+       mailbox.mail_stream = stream;
+       
+       for (i = 0; i < num; i++)  {
+               mail_id = mail_ids[i];
+       
+               if (!emcore_check_thread_status())  {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_get_mail_by_id(mail_id, &mail, true, &err) || !mail)  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+       
+                       goto FINISH_OFF;
+               }
+               
+               if (!emcore_check_thread_status())  {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               /*  download message number from server. */
+               if (!emcore_get_mail_msgno_by_uid(ref_account, &mailbox, mail->server_mail_id, &msgno, &err))  {
+                       EM_DEBUG_LOG("emcore_get_mail_msgno_by_uid failed message_no  :  %d ", err);
+                       goto FINISH_OFF;
+               }
+               
+               memset(tmp, 0x00, 100);
+               sprintf (tmp, "%d", msgno);
+
+               memset(set_flags, 0x00, 100);
+               memset(clear_flags, 0x00, 100);
+
+               if (mail->flags_seen_field)
+                       sprintf(set_flags, "\\Seen");
+               else
+                       sprintf(clear_flags, "\\Seen");
+               EM_DEBUG_LOG("new_flag.seen :  %s ", set_flags);
+
+               if (EM_SAFE_STRLEN(set_flags) > 0)  {
+                       EM_DEBUG_LOG(">>>> Calling mail_setflag ");
+                       mail_flag(stream, tmp, set_flags, ST_SET | ST_SILENT);
+                       EM_DEBUG_LOG(">>>> End mail_setflag ");
+               }
+               else {
+                       EM_DEBUG_LOG(">>>> Calling mail_clearflag ");
+                       mail_clearflag(stream, tmp, clear_flags);
+                       EM_DEBUG_LOG(">>>> End mail_clearflag ");
+               }
+
+               EM_DEBUG_LOG(">>>> Returning from emcore_sync_flag_with_server ");
+
+               if (!emcore_check_thread_status())  {
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+       }
+       ret = true;
+
+FINISH_OFF:
+       
+       if (stream) emcore_close_mailbox(account_id, stream);
+       if (mail) emstorage_free_mail(&mail, 1, NULL);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+
+INTERNAL_FUNC void emcore_free_mail_data_list(email_mail_data_t **mail_list, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("count[%d]", count);
+       
+       if (count <= 0 || !mail_list || !*mail_list)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");                        
+               return;
+       }
+               
+       email_mail_data_t* p = *mail_list;
+       int i;
+       
+       for (i = 0; i < count; i++)
+               emcore_free_mail_data( p+i);
+
+       EM_SAFE_FREE(*mail_list);
+
+       EM_DEBUG_FUNC_END();
+}
+       
+INTERNAL_FUNC void emcore_free_mail_data(email_mail_data_t *mail_data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!mail_data) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               return;
+       }
+
+       EM_SAFE_FREE(mail_data->subject);
+       EM_SAFE_FREE(mail_data->server_mailbox_name);
+       EM_SAFE_FREE(mail_data->server_mail_id);
+       EM_SAFE_FREE(mail_data->message_id);
+       EM_SAFE_FREE(mail_data->full_address_from);
+       EM_SAFE_FREE(mail_data->full_address_reply);
+       EM_SAFE_FREE(mail_data->full_address_to);
+       EM_SAFE_FREE(mail_data->full_address_cc);
+       EM_SAFE_FREE(mail_data->full_address_bcc);
+       EM_SAFE_FREE(mail_data->full_address_return);
+       EM_SAFE_FREE(mail_data->email_address_sender);
+       EM_SAFE_FREE(mail_data->email_address_recipient);
+       EM_SAFE_FREE(mail_data->alias_sender);
+       EM_SAFE_FREE(mail_data->alias_recipient);
+       EM_SAFE_FREE(mail_data->file_path_plain);
+       EM_SAFE_FREE(mail_data->file_path_html);
+       EM_SAFE_FREE(mail_data->preview_text);
+
+       EM_DEBUG_FUNC_END();    
+}
+
+
+INTERNAL_FUNC int emcore_free_attachment_data(email_attachment_data_t **attachment_data_list, int attachment_data_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_data_list[%p], attachment_data_count [%d], err_code[%p]", attachment_data_list, attachment_data_count, err_code);       
+       
+       if (!attachment_data_list || !*attachment_data_list)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       
+       email_attachment_data_t* p = *attachment_data_list;
+       int i = 0;
+       
+       for (i = 0; i < attachment_data_count; i++) {
+               EM_SAFE_FREE(p[i].attachment_name);
+               EM_SAFE_FREE(p[i].attachment_path);
+               EM_SAFE_FREE(p[i].attachment_mime_type);
+       }
+
+       EM_SAFE_FREE(p); *attachment_data_list = NULL;
+
+       if(err_code)
+               *err_code = EMAIL_ERROR_NONE;
+       
+       EM_DEBUG_FUNC_END();    
+       return true;
+}
+
+
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+INTERNAL_FUNC int emcore_delete_pbd_activity(int account_id, int mail_id, int activity_id, int *err_code) 
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], err_code[%p]", account_id, mail_id, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || mail_id < 0) {
+               EM_DEBUG_EXCEPTION("account_id[%d], mail_id[%d], err_code[%p]", account_id, mail_id, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       emstorage_begin_transaction(NULL, NULL, NULL);
+       
+       if (!emstorage_delete_pbd_activity(account_id, mail_id, activity_id, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_delete_pbd_activity failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF: 
+       if (ret == true) {      /*  COMMIT TRANSACTION; */
+               if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+                       err = EMAIL_ERROR_DB_FAILURE;
+                       ret = false;
+               }
+       }
+       else {  /*  ROLLBACK TRANSACTION; */
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       err = EMAIL_ERROR_DB_FAILURE;
+       }       
+       
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_insert_pbd_activity(email_event_partial_body_thd *local_activity, int *activity_id, int *err_code) 
+{
+       EM_DEBUG_FUNC_BEGIN("local_activity[%p], activity_id[%p], err_code[%p]", local_activity, activity_id, err_code);
+
+       if (!local_activity || !activity_id) {
+               EM_DEBUG_EXCEPTION("local_activity[%p], activity_id[%p] err_code[%p]", local_activity, activity_id, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       emstorage_begin_transaction(NULL, NULL, NULL);
+       
+       if (!emstorage_add_pbd_activity(local_activity, activity_id, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_add_pbd_activity failed [%d]", err);
+               
+
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF: 
+       if (ret == true) {      /*  COMMIT TRANSACTION; */
+               if (emstorage_commit_transaction(NULL, NULL, NULL) == false) {
+                       err = EMAIL_ERROR_DB_FAILURE;
+                       ret = false;
+               }
+       }
+       else {  /*  ROLLBACK TRANSACTION; */
+               if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)
+                       err = EMAIL_ERROR_DB_FAILURE;
+       }       
+       
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+#endif
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+
+/* API to set or unset a field of flags on server in single IMAP request to server */
+
+INTERNAL_FUNC int emcore_sync_flags_field_with_server(int mail_ids[], int num, email_flags_field_type field_type, int value, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids [%p], num [%d], field_type [%d], value [%d], err_code [%p]", mail_ids, num, field_type, value, err_code);
+               
+       if (NULL == mail_ids || num <= 0 || field_type < 0 || field_type >= EMAIL_FLAGS_FIELD_COUNT)  {
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL) {
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               }
+               return false;
+       }
+       
+       MAILSTREAM *stream = NULL;
+       IMAPLOCAL *imaplocal = NULL;
+       char tag[MAX_TAG_SIZE] = {0, };
+       char cmd[MAX_IMAP_COMMAND_LENGTH] = {0, };
+       char *p = NULL;
+       char **string_list = NULL;      
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int command_success = false;
+       int account_id = 0;
+       int mail_id = 0;
+       int i = 0;
+       int id_set_count = 0;
+       int len_of_each_range = 0;
+       int string_count = 0;
+       email_account_t *temp_account = NULL;
+       email_id_set_t *id_set = NULL;
+       emstorage_mail_tbl_t *mail = NULL;
+       email_uid_range_set *uid_range_set = NULL;
+       email_uid_range_set *uid_range_node = NULL;
+       char *field_type_name[EMAIL_FLAGS_FIELD_COUNT] = { "\\Seen"
+               , "\\Deleted", "\\Flagged", "\\Answered"
+               , "\\Recent", "\\Draft", "$Forwarded" }; 
+       
+       mail_id = mail_ids[0];
+       
+       if (!emstorage_get_mail_field_by_id(mail_id, RETRIEVE_FLAG, &mail, true, &err) || !mail)                /*To DO :  This is a existing bug. on mail deletion before this call it will fail always */ {
+               EM_DEBUG_LOG("emstorage_get_mail_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       account_id = mail[0].account_id;
+
+       temp_account = emcore_get_account_reference(account_id);
+
+       if (!temp_account)   {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+       
+       if (temp_account->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               EM_DEBUG_EXCEPTION("Syncing seen flag is available only for IMAP4 server. The server type [%d]", temp_account->incoming_server_type);
+               err = EMAIL_ERROR_NOT_SUPPORTED;
+               goto FINISH_OFF;
+       }
+       
+       if (!emcore_connect_to_remote_mailbox(account_id, mail->mailbox_id, (void **)&stream, &err) || !stream)  {
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (false == emstorage_free_mail(&mail, 1, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_free_mail failed - %d ", err);
+               goto FINISH_OFF;
+       }
+
+       /* [h.gahlaut] Break the set of mail_ids into comma separated strings of given length */
+       /* Length is decided on the basis of remaining keywords in the Query to be formed later on in emstorage_get_id_set_from_mail_ids */
+       /* Here about 90 bytes are required for fixed keywords in the query-> SELECT local_uid, s_uid from mail_read_mail_uid_tbl where local_uid in (....) ORDER by s_uid */
+       /* So length of comma separated strings which will be filled in (.....) in above query can be maximum QUERY_SIZE - 90 */
+
+       if (false == emcore_form_comma_separated_strings(mail_ids, num, QUERY_SIZE - 90, &string_list, &string_count, &err))   {
+               EM_DEBUG_EXCEPTION("emcore_form_comma_separated_strings failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Now execute one by one each comma separated string of mail_ids */
+
+       for (i = 0; i < string_count; ++i) {
+               /* Get the set of mail_ds and corresponding server_mail_ids sorted by server mail ids in ascending order */
+
+               if (false == emstorage_get_id_set_from_mail_ids(string_list[i], &id_set, &id_set_count, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_id_set_from_mail_ids failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               
+               /* Convert the sorted sequence of server mail ids to range sequences of given length. A range sequence will be like A : B, C, D: E, H */
+               
+               len_of_each_range = MAX_IMAP_COMMAND_LENGTH - 40;               /*  1000 is the maximum length allowed RFC 2683. 40 is left for keywords and tag. */
+               
+               if (false == emcore_convert_to_uid_range_set(id_set, id_set_count, &uid_range_set, len_of_each_range, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_convert_to_uid_range_set failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               uid_range_node = uid_range_set;
+
+               while (uid_range_node != NULL) {
+                       /* Remove comma from end of uid_range */
+
+                       uid_range_node->uid_range[EM_SAFE_STRLEN(uid_range_node->uid_range) - 1] = '\0';
+                       
+                       /* Form the IMAP command */
+
+                       SNPRINTF(tag, MAX_TAG_SIZE, "%08lx", 0xffffffff & (stream->gensym++));
+
+                       if (value)
+                               SNPRINTF(cmd, MAX_IMAP_COMMAND_LENGTH, "%s UID STORE %s +FLAGS (%s)\015\012", tag, uid_range_node->uid_range, field_type_name[field_type]);
+                       else
+                               SNPRINTF(cmd, MAX_IMAP_COMMAND_LENGTH, "%s UID STORE %s -FLAGS (%s)\015\012", tag, uid_range_node->uid_range, field_type_name[field_type]);
+
+                       EM_DEBUG_LOG("[IMAP4] command %s", cmd);
+
+                       /* send command */
+
+                       if (!(imaplocal = stream->local) || !imaplocal->netstream)  {
+                               EM_DEBUG_EXCEPTION("invalid IMAP4 stream detected...");
+                               
+                               err = EMAIL_ERROR_UNKNOWN;              
+                               goto FINISH_OFF;
+                       }
+               
+                       if (!net_sout(imaplocal->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+                               EM_DEBUG_EXCEPTION("net_sout failed...");
+                               err = EMAIL_ERROR_CONNECTION_BROKEN;            
+                               goto FINISH_OFF;
+                       }
+
+                       /* Receive Response */
+
+                       command_success = false;
+                       
+                       while (imaplocal->netstream) {  
+                               if (!(p = net_getline(imaplocal->netstream)))  {
+                                       EM_DEBUG_EXCEPTION("net_getline failed...");
+                               
+                                       err = EMAIL_ERROR_INVALID_RESPONSE;     
+                                       goto FINISH_OFF;
+                               }
+                       
+                               EM_DEBUG_LOG("[IMAP4 Response ] %s", p);
+                               
+                               if (!strncmp(p, tag, EM_SAFE_STRLEN(tag)))  {
+                                       if (!strncmp(p + EM_SAFE_STRLEN(tag) + 1, "OK", 2))  {
+                                               /*Delete all local activities */
+                                               command_success = true;
+
+                                               EM_SAFE_FREE(p);        
+                                               break;
+                                       }
+                                       else  {
+                                               /* 'NO' or 'BAD' */
+                                               command_success = false;
+                                               err = EMAIL_ERROR_IMAP4_STORE_FAILURE;          
+                                               EM_SAFE_FREE(p);
+                                               goto FINISH_OFF;
+                                       }               
+                               }
+                               
+                               EM_SAFE_FREE(p);                
+                       }
+
+                       uid_range_node = uid_range_node->next;
+               }       
+
+               emcore_free_uid_range_set(&uid_range_set);
+
+               EM_SAFE_FREE(id_set);
+               
+               id_set_count = 0;
+       }
+
+       ret = true;
+
+FINISH_OFF: 
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       if (ret) {
+               emstorage_activity_tbl_t new_activity;
+               for (i = 0; i<num ; i++) {              
+                       memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
+                       new_activity.activity_type = ACTIVITY_MODIFYSEENFLAG;
+                       new_activity.account_id    = account_id;
+                       new_activity.mail_id       = mail_ids[i];
+               
+                       if (!emcore_delete_activity(&new_activity, &err))
+                               EM_DEBUG_EXCEPTION("Local Activity ACTIVITY_MOVEMAIL [%d] ", err);
+               }
+
+       }
+#endif
+
+       if (NULL != mail) {
+               if (false == emstorage_free_mail(&mail, 1, &err))                       
+                       EM_DEBUG_EXCEPTION("emstorage_free_mail failed - %d ", err);
+       }
+       
+       emcore_free_comma_separated_strings(&string_list, &string_count);
+
+       if (false == ret)
+               emcore_free_uid_range_set(&uid_range_set);
+
+       emcore_close_mailbox(0, stream);
+       stream = NULL;
+
+       if (temp_account) {
+               emcore_free_account(temp_account);
+               EM_SAFE_FREE(temp_account);
+       }
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+#endif
+
+INTERNAL_FUNC int emcore_mail_filter_by_rule(email_rule_t *filter_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_info[%p], err_code[%p]", filter_info, err_code);
+
+       int ret = false, err = EMAIL_ERROR_NONE;
+       int account_index, account_count, mail_id_index = 0;
+       email_account_t *account_ref = NULL, *account_list_ref = NULL;
+       int filtered_mail_id_count = 0, *filtered_mail_id_list = NULL, parameter_string_length = 0;
+       char *parameter_string = NULL, mail_id_string[10] = { 0x00, };
+       emstorage_mailbox_tbl_t *spam_mailbox = NULL;
+
+       if (!filter_info)  {
+               EM_DEBUG_EXCEPTION("filter_info[%p]", filter_info);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_account_reference_list(&account_list_ref, &account_count, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for (account_index = 0; account_index < account_count; account_index++) {
+               account_ref = account_list_ref + account_index;
+
+               if (!emstorage_get_mailbox_by_mailbox_type(account_ref->account_id, EMAIL_MAILBOX_TYPE_SPAMBOX, &spam_mailbox, false, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type for account_id[%d] failed [%d]", account_ref->account_id, err);
+               else if (spam_mailbox && spam_mailbox->mailbox_id > 0) {
+                       if (!emstorage_filter_mails_by_rule(account_ref->account_id, spam_mailbox->mailbox_id, (emstorage_rule_tbl_t *)filter_info, &filtered_mail_id_list, &filtered_mail_id_count, &err))
+                               EM_DEBUG_EXCEPTION("emstorage_filter_mails_by_rule failed [%d]", err);
+                       else {
+                               if (filtered_mail_id_count) {
+                                       parameter_string_length = 10 /*mailbox_id length*/ + 7 + (10 * filtered_mail_id_count);
+                                       parameter_string = em_malloc(sizeof(char) * parameter_string_length);
+
+                                       if (parameter_string == NULL) {
+                                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                               EM_DEBUG_EXCEPTION("em_malloc failed for parameter_string");
+                                               goto FINISH_OFF;
+                                       }
+                                       SNPRINTF(parameter_string, parameter_string_length, "[NA]%c%d%c", 0x01, spam_mailbox->mailbox_id, 0x01);
+                                       
+                                       for (mail_id_index = 0; mail_id_index < filtered_mail_id_count; mail_id_index++) {
+                                               memset(mail_id_string, 0, 10);
+                                               SNPRINTF(mail_id_string, 10, "%d", filtered_mail_id_list[mail_id_index]);
+                                               strcat(parameter_string, mail_id_string);
+                                               strcat(parameter_string, ",");
+                                       }
+
+                                       EM_DEBUG_LOG("filtered_mail_id_count [%d]", filtered_mail_id_count);
+                                       EM_DEBUG_LOG("param string [%s]", parameter_string);
+
+                                       if (!emcore_notify_storage_event(NOTI_MAIL_MOVE, account_ref->account_id, 0, parameter_string, 0)) 
+                                               EM_DEBUG_EXCEPTION("emcore_notify_storage_event failed [ NOTI_MAIL_MOVE ] >>>> ");
+
+                                       EM_SAFE_FREE(filtered_mail_id_list);
+                                       EM_SAFE_FREE(parameter_string);
+                               }
+                       }
+                       emstorage_free_mailbox(&spam_mailbox, 1, &err);
+                       spam_mailbox = NULL;
+               }
+       }
+
+       emcore_display_unread_in_badge();
+
+       ret = true;
+
+FINISH_OFF: 
+       EM_SAFE_FREE(account_list_ref);
+       EM_SAFE_FREE(filtered_mail_id_list);
+       EM_SAFE_FREE(parameter_string);
+
+
+       if (spam_mailbox)
+               emstorage_free_mailbox(&spam_mailbox, 1, &err);
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
diff --git a/email-core/email-core-mailbox-sync.c b/email-core/email-core-mailbox-sync.c
new file mode 100755 (executable)
index 0000000..57f7642
--- /dev/null
@@ -0,0 +1,4155 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-mailbox-sync.c
+ * Desc :  Mail Header Sync
+ *
+ * Auth :
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <vconf.h>
+
+#include "email-internal-types.h"
+
+#ifdef __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__
+#include <vconf/vconf-internal-email-keys.h>
+#endif /* __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__ */
+
+#include "c-client.h"
+#include "lnx_inc.h"
+
+#include "email-utilities.h"
+#include "email-convert.h"
+#include "email-core-mailbox-sync.h"
+#include "email-core-global.h"
+#include "email-core-imap-mailbox.h"
+#include "email-core-event.h"
+#include "email-core-mailbox.h"
+#include "email-core-mail.h"
+#include "email-core-mime.h"
+#include "email-core-utils.h"
+#include "email-core-smtp.h"
+#include "email-core-account.h"
+#include "email-storage.h"
+#include "email-core-signal.h"
+#include "flstring.h"
+#include "email-debug-log.h"
+
+#define MAX_CHARSET_VALUE 256
+
+static char g_append_uid_rsp[129]; /* added for getting server response  */
+
+extern void imap_parse_body_structure (MAILSTREAM *stream, BODY *body, unsigned char **txtptr, IMAPPARSEDREPLY *reply);
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+static void emcore_free_email_partial_buffer(email_partial_buffer **partial_buffer, int item_count);
+static email_partial_buffer *emcore_get_response_from_server (NETSTREAM *nstream, char *tag, IMAPPARSEDREPLY **reply, int input_download_size, int item_count);
+static int emcore_initiate_pbd(MAILSTREAM *stream, int account_id, int mail_id, char *uid, int mailbox_id, int *err_code);
+#endif
+
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+static char g_append_uid_rsp[129]; /* added for getting server response  */
+#endif
+
+
+int pop3_mail_calc_rfc822_size(MAILSTREAM *stream, int msgno, int *size, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       POP3LOCAL *pop3local = NULL;
+       char command[16];
+       char *response = NULL;
+
+       if (!stream || !size) {
+               EM_DEBUG_EXCEPTION(" stream[%p], msgno[%d], size[%p]\n", stream, msgno, size);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(pop3local = stream->local) || !pop3local->netstream) {
+               err = EMAIL_ERROR_INVALID_STREAM;
+               goto FINISH_OFF;
+       }
+
+       memset(command, 0x00, sizeof(command));
+
+       SNPRINTF(command, sizeof(command), "LIST %d\015\012", msgno);
+
+       /* EM_DEBUG_LOG(" [POP3] >>> %s", command); */
+
+       /*  send command  :  get rfc822 size by msgno */
+       if (!net_sout(pop3local->netstream, command, (int)EM_SAFE_STRLEN(command))) {
+               EM_DEBUG_EXCEPTION(" net_sout failed...");
+
+               err = EMAIL_ERROR_INVALID_RESPONSE;
+               goto FINISH_OFF;
+       }
+
+       /*  receive response */
+       if (!(response = net_getline(pop3local->netstream))) {
+               err = EMAIL_ERROR_CONNECTION_BROKEN;            /* EMAIL_ERROR_UNKNOWN; */
+               goto FINISH_OFF;
+       }
+
+       /* EM_DEBUG_LOG(" [POP3] <<< %s", response); */
+
+       if (*response == '+') {         /*  "+ OK" */
+               char *p = NULL;
+
+               if (!(p = strchr(response + strlen("+OK "), ' '))) {
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+
+               *size = atoi(p + 1);
+       }
+       else if (*response == '-') {            /*  "- ERR" */
+               err = EMAIL_ERROR_POP3_LIST_FAILURE;
+               goto FINISH_OFF;
+       }
+       else {
+               err = EMAIL_ERROR_INVALID_RESPONSE;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(response);
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int imap4_mail_calc_rfc822_size(MAILSTREAM *stream, int msgno, int *size, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       IMAPLOCAL *imaplocal = NULL;
+       char tag[32], command[128];
+       char *response = NULL;
+
+       if (!stream || !size) {
+               EM_DEBUG_EXCEPTION("stream[%p], msgno[%d], size[%p]", stream, msgno, size);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(imaplocal = stream->local) || !imaplocal->netstream) {
+               err = EMAIL_ERROR_INVALID_STREAM;
+               goto FINISH_OFF;
+       }
+
+       memset(tag, 0x00, sizeof(tag));
+       memset(command, 0x00, sizeof(command));
+
+       SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+       SNPRINTF(command, sizeof(command), "%s FETCH %d RFC822.SIZE\015\012", tag, msgno);
+
+       /* EM_DEBUG_LOG(" [IMAP4] >>> %s", command); */
+
+       /*  send command  :  get rfc822 size by msgno */
+       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command))) {
+               EM_DEBUG_EXCEPTION(" net_sout failed...");
+
+               err = EMAIL_ERROR_INVALID_RESPONSE;
+               goto FINISH_OFF;
+       }
+
+       while (imaplocal->netstream) {
+               char *s = NULL;
+               char *t = NULL;
+
+               /*  receive response */
+               if (!(response = net_getline(imaplocal->netstream)))
+                       break;
+
+               /* EM_DEBUG_LOG(" [IMAP4] <<< %s", response); */
+
+               if (!strncmp(response, tag, EM_SAFE_STRLEN(tag))) {
+                       if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
+                               EM_SAFE_FREE(response);
+                               break;
+                       }
+                       else {          /*  'NO' or 'BAD' */
+                               err = EMAIL_ERROR_IMAP4_FETCH_SIZE_FAILURE;             /* EMAIL_ERROR_INVALID_RESPONSE; */
+                               goto FINISH_OFF;
+                       }
+               }
+               else {          /*  untagged response */
+                       if (*response == '*') {
+                               if (!(t = strstr(response, "FETCH (RFC822.SIZE "))) {
+                                       EM_SAFE_FREE(response);
+                                       continue;
+                               }
+
+                               s = t + strlen("FETCH (RFC822.SIZE ");
+
+                               if (!(t = strchr(s, ' '))) {
+                                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                                       goto FINISH_OFF;
+                               }
+
+                               *t = '\0';
+
+                               *size = atoi(s);
+                       }
+               }
+
+               EM_SAFE_FREE(response);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(response);
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int pop3_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *err_code)
+{
+       EM_PROFILE_BEGIN(pop3MailboxGetuid);
+       EM_DEBUG_FUNC_BEGIN("stream[%p], uid_list[%p], err_code[%p]", stream, uid_list, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       POP3LOCAL *pop3local = NULL;
+       char command[64];
+       char *response = NULL;
+       emcore_uid_list *uid_elem = NULL;
+
+       if (!stream || !uid_list) {
+               EM_DEBUG_EXCEPTION("stream[%p], uid_list[%p]n", stream, uid_list);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(pop3local = stream->local) || !pop3local->netstream) {
+               EM_DEBUG_EXCEPTION("invalid POP3 stream detected...");
+               err = EMAIL_ERROR_INVALID_STREAM;
+               goto FINISH_OFF;
+       }
+
+       memset(command, 0x00, sizeof(command));
+
+       SNPRINTF(command, sizeof(command), "UIDL\015\012");
+
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG(" [POP3] >>> [%s]", command);
+#endif
+
+       /*  send command  :  get msgno/uid for all message */
+       if (!net_sout(pop3local->netstream, command, (int)EM_SAFE_STRLEN(command))) {
+               EM_DEBUG_EXCEPTION("net_sout failed...");
+               err = EMAIL_ERROR_CONNECTION_BROKEN;            /* EMAIL_ERROR_UNKNOWN; */
+               goto FINISH_OFF;
+       }
+
+       *uid_list = NULL;
+
+       while (pop3local->netstream) {
+               char *p = NULL;
+
+               /*  receive response */
+               if (!(response = net_getline(pop3local->netstream))) {
+                       EM_DEBUG_EXCEPTION("net_getline failed...");
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+
+#ifdef FEATURE_CORE_DEBUG
+               EM_DEBUG_LOG(" [POP3] <<< [%s]", response);
+#endif
+
+               if (*response == '-') {         /*  "-ERR" */
+                       err = EMAIL_ERROR_POP3_UIDL_FAILURE;            /* EMAIL_ERROR_INVALID_RESPONSE; */
+                       goto FINISH_OFF;
+               }
+
+               if (*response == '+') {         /*  "+OK" */
+                       free(response); response = NULL;
+                       continue;
+               }
+
+               if (*response == '.') {
+                       free(response); response = NULL;
+                       break;
+               }
+
+               if ((p = strchr(response, ' '))) {
+                       *p = '\0';
+
+                       if (!(uid_elem = em_malloc(sizeof(emcore_uid_list)))) {
+                               EM_DEBUG_EXCEPTION("malloc failed...");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       uid_elem->msgno = atoi(response);
+                       uid_elem->uid = EM_SAFE_STRDUP(p + 1);
+
+                       if (*uid_list  != NULL)
+                               uid_elem->next = *uid_list;             /*  prepend new data to table */
+
+                       *uid_list = uid_elem;
+               }
+               else {
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+
+               free(response); response = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (response  != NULL)
+               free(response);
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_PROFILE_END(pop3MailboxGetuid);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int imap4_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *err_code)
+{
+       EM_PROFILE_BEGIN(ImapMailboxGetUids);
+       EM_DEBUG_FUNC_BEGIN("stream[%p], uid_list[%p], err_code[%p]", stream, uid_list, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       IMAPLOCAL *imaplocal = NULL;
+       char tag[16], command[64];
+       char *response = NULL;
+       emcore_uid_list *uid_elem = NULL;
+
+       if (!stream || !uid_list) {
+               EM_DEBUG_EXCEPTION("stream[%p], uid_list[%p]", stream, uid_list);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(imaplocal = stream->local) || !imaplocal->netstream) {
+               EM_DEBUG_EXCEPTION("invalid IMAP4 stream detected...");
+               err = EMAIL_ERROR_INVALID_PARAM;                /* EMAIL_ERROR_UNKNOWN */
+               goto FINISH_OFF;
+       }
+
+       if (stream->nmsgs == 0){
+               err = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER;
+               goto FINISH_OFF;
+       }
+       memset(tag, 0x00, sizeof(tag));
+       memset(command, 0x00, sizeof(command));
+
+       SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+       SNPRINTF(command, sizeof(command), "%s FETCH 1:* (FLAGS UID)\015\012", tag);
+       EM_DEBUG_LOG("COMMAND [%s] \n", command);
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG(" [IMAP4] >>> [%s]", command);
+#endif
+
+       /*  send command  :  get msgno/uid for all message */
+       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command))) {
+               EM_DEBUG_EXCEPTION(" net_sout failed...\n");
+               err = EMAIL_ERROR_CONNECTION_BROKEN;
+               goto FINISH_OFF;
+       }
+
+       *uid_list = NULL;
+
+       while (imaplocal->netstream) {
+               char *p = NULL;
+               char *s = NULL;
+               int seen = 0;
+               int forwarded = 0;
+               int draft = 0;
+               /*  receive response */
+               if (!(response = net_getline(imaplocal->netstream))) {
+                       EM_DEBUG_EXCEPTION("net_getline failed...");
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+
+#ifdef FEATURE_CORE_DEBUG
+               EM_DEBUG_LOG(" [IMAP4] <<< [%s]", response);
+#endif
+
+               if (!strncmp(response, tag, EM_SAFE_STRLEN(tag))) {
+                       if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
+                               free(response); response = NULL;
+                               break;
+                       }
+                       else {          /*  'NO' or 'BAD' */
+                               err = EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE;              /* EMAIL_ERROR_INVALID_RESPONSE; */
+                               goto FINISH_OFF;
+                       }
+               }
+
+               if ((p = strstr(response, " FETCH ("))) {
+                       if (!strstr(p, "\\Deleted")) {  /*  undeleted only */
+                               *p = '\0'; p  += strlen(" FETCH ");
+
+                               seen = strstr(p, "\\Seen") ? 1  :  0;
+                               draft = strstr(p, "\\Draft") ? 1  :  0;
+                               forwarded = strstr(p, "$Forwarded") ? 1  :  0;
+
+                               if ((p = strstr(p, "UID "))) {
+                                       s = p + strlen("UID ");
+
+                                       while (isdigit(*s))
+                                               s++;
+
+                                       *s = '\0';
+
+                                       if (!(uid_elem = em_malloc(sizeof(emcore_uid_list)))) {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed...");
+                                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       uid_elem->msgno = atoi(response + strlen("* "));
+                                       uid_elem->uid = EM_SAFE_STRDUP(p + strlen("UID "));
+                                       uid_elem->flag.seen = seen;
+                                       uid_elem->flag.draft = draft;
+                                       uid_elem->flag.forwarded = forwarded;
+                                       if (*uid_list  != NULL)
+                                               uid_elem->next = *uid_list;             /*  prepend new data to list */
+
+                                       *uid_list = uid_elem;
+                               }
+                               else {
+                                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+               else {
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+
+               EM_SAFE_FREE(response);;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(response);
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_PROFILE_END(ImapMailboxGetUids);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+static char *__em_get_month_in_string(int month)
+{
+       EM_DEBUG_FUNC_BEGIN("month [%d]", month);
+
+       char *mon = NULL;
+
+       switch (month){
+           case 0:
+                       mon = strdup("jan");
+               break;
+           case 1:
+                       mon = strdup("feb");
+               break;
+           case 2:
+                       mon = strdup("mar");
+               break;
+           case 3:
+                       mon = strdup("apr");
+               break;
+           case 4:
+                       mon = strdup("may");
+               break;
+           case 5:
+                       mon = strdup("jun");
+               break;
+           case 6:
+                       mon = strdup("jul");
+               break;
+           case 7:
+                       mon = strdup("aug");
+               break;
+           case 8:
+                       mon = strdup("sep");
+               break;
+           case 9:
+                       mon = strdup("oct");
+               break;
+           case 10:
+                       mon = strdup("nov");
+               break;
+           case 11:
+                       mon = strdup("dec");
+               break;
+       }
+       return mon;
+}
+
+int imap4_mailbox_get_uids_by_timestamp(MAILSTREAM *stream, emcore_uid_list** uid_list,  int *err_code)
+{
+       EM_PROFILE_BEGIN(emCoreMailboxuidsbystamp);
+       EM_DEBUG_FUNC_BEGIN("stream[%p], uid_list[%p],  err_code[%p]", stream, uid_list, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       IMAPLOCAL *imaplocal = NULL;
+       char tag[16], command[64];
+       char *response = NULL;
+       emcore_uid_list *uid_elem = NULL;
+       char delims[] = " ";
+       char *result = NULL;
+
+       struct tm   *timeinfo = NULL;
+       time_t         RawTime = 0;
+       time_t         week_before_RawTime = 0;
+       char  date_string[16];
+       char *mon = NULL;
+
+       if (!stream || !uid_list) {
+               EM_DEBUG_EXCEPTION(" stream[%p], uid_list[%p]", stream, uid_list);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(imaplocal = stream->local) || !imaplocal->netstream) {
+               EM_DEBUG_EXCEPTION(" invalid IMAP4 stream detected...");
+               err = EMAIL_ERROR_INVALID_PARAM;                /* EMAIL_ERROR_UNKNOWN */
+               goto FINISH_OFF;
+       }
+
+       /* Fetch the System time and Retrieve the a Week before time */
+       /*      tzset(); */
+       time(&RawTime);
+
+       EM_DEBUG_LOG("RawTime Info [%lu]", RawTime);
+
+       timeinfo = localtime (&RawTime);
+
+       EM_DEBUG_LOG(">>>>>Current TIme %d %d %d %d %d %d", 1900+timeinfo->tm_year, timeinfo->tm_mon+1, timeinfo->tm_mday);
+
+       week_before_RawTime = RawTime - 604800;
+
+       /* Reading the current timeinfo */
+       timeinfo = localtime (&week_before_RawTime);
+
+       EM_DEBUG_LOG(">>>>>Mobile Date a Week before %d %d %d %d %d %d", 1900 + timeinfo->tm_year, timeinfo->tm_mon+1, timeinfo->tm_mday);
+
+       memset(&date_string, 0x00, 16);
+
+       mon = __em_get_month_in_string(timeinfo->tm_mon);
+
+       if (mon){
+               snprintf(date_string, 16, "%d-%s-%04d", timeinfo->tm_mday, mon, 1900 + timeinfo->tm_year);
+               EM_DEBUG_LOG("DATE IS [ %s ] ", date_string);
+               EM_SAFE_FREE(mon);
+       }
+
+       memset(tag, 0x00, sizeof(tag));
+       memset(command, 0x00, sizeof(command));
+
+       SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+       SNPRINTF(command, sizeof(command), "%s UID SEARCH 1:* SINCE %s\015\012", tag, date_string);
+       EM_DEBUG_LOG("COMMAND [%s] ", command);
+
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG(" [IMAP4] >>> [%s]", command);
+#endif
+
+       /*  send command  :  get msgno/uid for all message */
+       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command))) {
+               EM_DEBUG_EXCEPTION(" net_sout failed...");
+               err = EMAIL_ERROR_CONNECTION_BROKEN;            /* EMAIL_ERROR_UNKNOWN */
+               goto FINISH_OFF;
+       }
+
+       *uid_list = NULL;
+
+       while (imaplocal->netstream) {
+               char *p = NULL;
+               /*  receive response */
+               if (!(response = net_getline(imaplocal->netstream))) {
+                       EM_DEBUG_EXCEPTION(" net_getline failed...");
+                       err = EMAIL_ERROR_INVALID_RESPONSE;             /* EMAIL_ERROR_UNKNOWN; */
+                       goto FINISH_OFF;
+               }
+#ifdef FEATURE_CORE_DEBUG
+               EM_DEBUG_LOG(" [IMAP4] <<< [%s]", response);
+#endif
+
+               if (!strncmp(response, tag, EM_SAFE_STRLEN(tag))) {
+                       if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
+                               free(response); response = NULL;
+                               break;
+                       }
+                       else {  /*  'NO' or 'BAD' */
+                               err = EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE;              /* EMAIL_ERROR_INVALID_RESPONSE; */
+                               goto FINISH_OFF;
+                       }
+               }
+
+               if ((p = strstr(response, " SEARCH "))){
+                   *p = '\0'; p  += strlen(" SEARCH ");
+
+                   result = strtok(p, delims);
+
+                   while (result  != NULL)
+                   {
+                               EM_DEBUG_LOG("UID VALUE DEEP is [%s]", result);
+
+                               if (!(uid_elem = em_malloc(sizeof(emcore_uid_list)))) {
+                                       EM_DEBUG_EXCEPTION(" malloc failed...");
+                                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                       goto FINISH_OFF;
+                               }
+
+                               uid_elem->uid = EM_SAFE_STRDUP(result);
+
+                               if (*uid_list  != NULL)
+                                       uid_elem->next = *uid_list;
+                               *uid_list = uid_elem;
+                               result = strtok(NULL, delims);
+                   }
+
+                       EM_SAFE_FREE(response);
+                   return 1;
+               }
+               else {
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+               /* Delete the dead code */
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (response  != NULL)
+               free(response);
+
+       if (err_code  != NULL)
+               *err_code = err;
+       EM_PROFILE_END(emCoreMailboxuidsbystamp);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+#define PARSE_BUFFER_LENGTH 4096
+static int emcore_parse_header(char *rfc822_header, int *req_read_receipt, int *priority, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("rfc822_header[%p], req_read_receipt[%p], priority[%p], err_code[%p]", rfc822_header, req_read_receipt, priority,  err_code);
+
+       if (!rfc822_header || !priority)
+               return false;
+
+       if (err_code)
+               *err_code = EMAIL_ERROR_NONE;
+
+       EM_PROFILE_BEGIN(emCoreMailboxParseHeader);
+
+       char buf[PARSE_BUFFER_LENGTH];
+       int len, i, j;
+
+       EM_DEBUG_LOG("Buffer length [%d]", PARSE_BUFFER_LENGTH);
+
+       *priority = 3;
+
+       memset(buf, 0x00, PARSE_BUFFER_LENGTH);
+
+       for (len = EM_SAFE_STRLEN(rfc822_header), i = 0, j = 0; i < len; i++) {
+               if (rfc822_header[i] == CR && rfc822_header[i+1] == LF){
+                       if (j + 3 < PARSE_BUFFER_LENGTH) /* '3' include CR LF NULL */
+                               strncpy(buf + j, CRLF_STRING, PARSE_BUFFER_LENGTH - (j + 2)); /* '3' include CR LF */
+                       else
+                               EM_DEBUG_EXCEPTION("buf is too small.");
+
+                       i++;
+                       j = 0;
+
+                       /*  parsing data */
+                       em_upper_string(buf);
+
+                       /*  disposition_notification_to */
+                       if (buf[0] == 'D' && buf[11] == '-' && buf[12] == 'N' && buf[24] == '-' && buf[25] == 'T') {
+                               if (req_read_receipt)
+                                       *req_read_receipt = 1;
+                               memset(buf, 0x00, PARSE_BUFFER_LENGTH);
+                               continue;
+                       }
+
+                       /*  x-priority */
+                       if (buf[0] == 'X' && buf[2] == 'P' && buf[9] == 'Y'){
+                               size_t len_2 = EM_SAFE_STRLEN(buf);
+                               if (len_2 >= 12){
+                                       buf[len_2 - 2] = '\0';
+                                       *priority = atoi(buf + 11);
+                                       memset(buf, 0x00, PARSE_BUFFER_LENGTH);
+                                       continue;
+                               }
+                       }
+
+                       /*  x-msmail-priority */
+                       if (buf[0] == 'X' && buf[2] == 'M' && buf[9] == 'P' && buf[16] == 'Y'){
+                               if (strstr(buf, "HIGH"))
+                                       *priority = 1;
+                               if (strstr(buf, "NORMAL"))
+                                       *priority = 3;
+                               if (strstr(buf, "LOW"))
+                                       *priority = 5;
+                               memset(buf, 0x00, PARSE_BUFFER_LENGTH);
+                               continue;
+                       }
+
+                       memset(buf, 0x00, PARSE_BUFFER_LENGTH);
+                       continue;
+               }
+
+               if (j + 1 < PARSE_BUFFER_LENGTH)
+                       buf[j++] = rfc822_header[i];
+               else
+                       EM_DEBUG_EXCEPTION("buf is too small.");
+       }
+
+       EM_PROFILE_END(emCoreMailboxParseHeader);
+
+       if (err_code)
+               *err_code = EMAIL_ERROR_NONE;
+
+       return true;
+}
+
+
+static int emcore_get_mail_extra_info(MAILSTREAM *stream, int msgno, int *req_read_receipt, int *priority, int *err_code)
+{
+       EM_PROFILE_BEGIN(emCoreMailGetExtraInfo);
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msgno[%d], req_read_receipt[%p], priority[%p], err_code[%p]", stream, msgno, req_read_receipt, priority, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       char *rfc822_header = NULL;
+       unsigned long len = 0;
+
+       EM_PROFILE_BEGIN(MaiFetchHeader);
+#ifdef __FEATURE_HEADER_OPTIMIZATION__
+       /* Check if header already available in cache */
+       if (stream && stream->cache && stream->cache[msgno-1]->private.msg.header.text.data){
+               EM_DEBUG_LOG("I found the header in stream->cache!!");
+               rfc822_header = (char *) stream->cache[msgno-1]->private.msg.header.text.data;
+       }
+       else{
+               EM_DEBUG_LOG("I couldn't find the header. I'll fetch the header from server again.");
+               if (stream)
+                       rfc822_header = mail_fetch_header(stream, msgno, NULL, NULL, &len, FT_PEEK);
+       }
+
+#else
+       rfc822_header = mail_fetch_header(stream, msgno, NULL, NULL, &len, FT_PEEK);
+#endif
+       EM_PROFILE_END(MaiFetchHeader);
+
+       if (!rfc822_header || !*rfc822_header) {
+               EM_DEBUG_EXCEPTION("mail_fetch_header failed...");
+               err = EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE;              /* EMAIL_ERROR_UNKNOWN; */
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_parse_header(rfc822_header, req_read_receipt, priority, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_parse_header falied - %d", err);
+               goto FINISH_OFF;
+       }
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_PROFILE_END(emCoreMailGetExtraInfo);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+static int emcore_get_uids_to_download(MAILSTREAM *stream, email_account_t *account, emstorage_mailbox_tbl_t *input_mailbox_tbl, int limit_count, emcore_uid_list** uid_list, int *uids, int retrieve_mode ,  int *err_code)
+{
+       EM_PROFILE_BEGIN(emCoreGetUidsDownload);
+       EM_DEBUG_FUNC_BEGIN("account[%p], input_mailbox_tbl[%p], limit_count[%d], uid_list[%p], err_code[%p]", account, input_mailbox_tbl, limit_count, uid_list, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       emstorage_read_mail_uid_tbl_t *downloaded_uids = NULL;
+       int i = 0, j = 0, uid_count = 0, uid_to_be_downloaded_count = 0;
+       emcore_uid_list *uid_elem = NULL;
+       emcore_uid_list *head_uid_elem = NULL, *end =  NULL;
+       emcore_uid_list *next_uid_elem = NULL;
+       emstorage_mail_tbl_t *mail = NULL;
+
+       if (!account || !input_mailbox_tbl || !uid_list) {
+               EM_DEBUG_EXCEPTION("account[%p], input_mailbox_tbl[%p], uid_list[%p]", account, input_mailbox_tbl, uid_list);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       *uid_list = NULL;
+
+       if (account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) {
+               if (!pop3_mailbox_get_uids(stream, uid_list, &err)) {
+                       EM_DEBUG_EXCEPTION("pop3_mailbox_get_uids failed - %d", err);
+                       goto FINISH_OFF;
+               }
+       }
+       else {  /*  EMAIL_SERVER_TYPE_IMAP4 */
+               /*  sowmya.kr commented , since imap4_mailbox_get_uids_by_timestamp will fetch mails since last week and not all mails  */
+
+               EM_DEBUG_LOG("calling imap4_mailbox_get_uids");
+               if (!imap4_mailbox_get_uids(stream, uid_list, &err)) {
+                       EM_DEBUG_EXCEPTION("imap4_mailbox_get_uids failed [%d]", err);
+                       if (err  != EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER)
+                               goto FINISH_OFF;
+           }
+       }
+
+       if (!emstorage_get_downloaded_list(input_mailbox_tbl->account_id,
+        (account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) ? 0 : input_mailbox_tbl->mailbox_id,
+        &downloaded_uids, &j, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_downloaded_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG("Number of Mails in Downloaded Table [%d]", j);
+
+       uid_elem = *uid_list;
+       uid_count = 0;
+
+       if(!uid_elem) { /* If there is no mail in the input_mailbox_tbl, remove all mails in the input_mailbox_tbl */
+               for (i = 0; i < j; i++) {
+                       downloaded_uids[i].reserved = 0;
+               }
+       }
+
+       EM_PROFILE_BEGIN(emCoreGetUidsDownloadWhilwLoop);
+
+       while (uid_elem) {
+               next_uid_elem = uid_elem->next;
+
+               if ((account->retrieval_mode == EMAIL_IMAP4_RETRIEVAL_MODE_NEW) && (uid_elem->flag.seen != 0)){         /*  already seen */
+                       if (uid_elem->uid)
+                               free(uid_elem->uid);
+
+                       free(uid_elem);
+               }
+               else {
+                       int to_be_downloaded = 1;
+
+                       if (limit_count > 0 && uid_count >= limit_count){
+                               /*  EM_DEBUG_LOG("hit the limit[%d] for [%s]", limit_count, uid_elem->uid);              */
+                               to_be_downloaded = 0;
+                       }
+                       else{
+                               for (i = j; i > 0; i--) {
+                                       if (downloaded_uids[i - 1].reserved == 0 && !strcmp(uid_elem->uid, downloaded_uids[i - 1].s_uid)) {
+                                               downloaded_uids[i - 1].reserved = uid_elem->flag.seen ? 2 : 1;
+                                               to_be_downloaded = 0;
+                                               break;
+                                       }
+                               }
+                       }
+
+                       /*  EM_DEBUG_LOG("Is uid[%s] going to be downloded ? [%d]", uid_elem->uid, to_be_downloaded); */
+
+                       if (to_be_downloaded) {
+                               if (retrieve_mode == EMAIL_SYNC_OLDEST_MAILS_FIRST){
+                                       uid_elem->next = head_uid_elem;
+                                       head_uid_elem = uid_elem;
+                               }
+                               else{   /* if retrieve_mode is EMAIL_SYNC_LATEST_MAILS_FIRST, add uid elem to end so that latest mails are in front of list */
+                                       if (head_uid_elem == NULL){
+                                               uid_elem->next = head_uid_elem;
+                                               head_uid_elem = uid_elem;
+                                               end = head_uid_elem;
+                                       }
+                                       else{
+                                               end->next = uid_elem;
+                                               uid_elem->next = NULL;
+                                               end = uid_elem;
+                                       }
+                               }
+                               uid_to_be_downloaded_count++;
+
+                       }
+                       else {
+                               if (uid_elem->uid)
+                                       free(uid_elem->uid);
+                               free(uid_elem);
+                       }
+
+                       uid_count++;
+               }
+
+               uid_elem = next_uid_elem;
+       }
+
+       EM_PROFILE_END(emCoreGetUidsDownloadWhilwLoop);
+       EM_PROFILE_BEGIN(emCoreGetUidsDownloadForLoop);
+
+       for (i = 0; i < j; i++) {
+               /*  EM_DEBUG_LOG("input_mailbox_tbl[%s] reserved[%d]", input_mailbox_tbl->name, downloaded_uids[i].reserved); */
+               if (downloaded_uids[i].reserved == 0) {         /*  deleted on server */
+                       if (!emstorage_get_maildata_by_servermailid(input_mailbox_tbl->account_id, downloaded_uids[i].s_uid, &mail, true, &err)){
+                               EM_DEBUG_EXCEPTION("emstorage_get_maildata_by_servermailid for uid[%s] Failed [%d] \n ", downloaded_uids[i].s_uid, err);
+                               if (err == EMAIL_ERROR_MAIL_NOT_FOUND){
+                                       continue;
+                               }
+                       }
+
+                       if (account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+                               if (!emcore_delete_mails_from_local_storage(input_mailbox_tbl->account_id, &(mail->mail_id), 1, EMAIL_DELETED_FROM_SERVER, false, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_delete_mails_from_local_storage falied - %d", err);
+                                       goto FINISH_OFF;
+                               }
+                               /* emcore_delete_notification_for_read_mail(mail->mail_id); */
+                               emcore_display_unread_in_badge();
+                       }
+
+                       if (!emstorage_remove_downloaded_mail(input_mailbox_tbl->account_id, input_mailbox_tbl->mailbox_name, downloaded_uids[i].s_uid, true, &err)) {   /*  remove uid from uid list */
+                               EM_DEBUG_EXCEPTION("emstorage_remove_downloaded_mail failed - %d", err);
+
+                               /* goto FINISH_OFF; */
+                       }
+
+               }
+               else if (account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4 && downloaded_uids[i].reserved == 1) {
+                       /*  unseen on server */
+                       if  (!emstorage_get_mail_by_id(downloaded_uids[i].local_uid, &mail, true, &err)){
+                               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed for [%d] - [%d]", downloaded_uids[i].local_uid, err);
+                               continue;
+                       }
+
+                       if (mail) {
+                               if (mail->body_download_status && mail->flags_seen_field){
+                                       EM_DEBUG_LOG("Set flag as seen on server");
+                                       mail_setflag_full(stream, downloaded_uids[i].s_uid, "\\Seen", ST_UID);
+                               }
+                       }
+               }
+               if (mail != NULL)
+                       emstorage_free_mail(&mail, 1, NULL);
+               mail = NULL;
+       }
+       EM_PROFILE_END(emCoreGetUidsDownloadForLoop);
+
+       *uid_list = head_uid_elem;
+       *uids = uid_to_be_downloaded_count;
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == false){
+               if (head_uid_elem)
+                       emcore_free_uids(head_uid_elem, NULL);
+       }
+
+       if (downloaded_uids != NULL)
+               emstorage_free_read_mail_uid(&downloaded_uids, j, NULL);
+
+       if (mail != NULL)
+               emstorage_free_mail(&mail, 1, NULL);
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_PROFILE_END(emCoreGetUidsDownload);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/* insert received mail UID to read mail uid table */
+static int emcore_add_read_mail_uid(emstorage_mailbox_tbl_t *input_maibox_data, char *server_mailbox_name, int mail_id, char *uid, int rfc822_size, int rule_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_maibox_data[%p], server_mailbox_name[%s], uid[%s], rfc822_size[%d], rule_id[%d], err_code[%p]", input_maibox_data, server_mailbox_name, uid, rfc822_size, rule_id, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       emstorage_read_mail_uid_tbl_t  read_mail_uid = { 0 };
+       emstorage_mailbox_tbl_t       *mailbox_tbl = NULL;
+
+       if (!input_maibox_data || !uid) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       read_mail_uid.account_id = input_maibox_data->account_id;
+
+       if (!(input_maibox_data->mailbox_id) || !(server_mailbox_name)){
+               if (!emstorage_get_mailbox_by_mailbox_type(input_maibox_data->account_id, EMAIL_MAILBOX_TYPE_INBOX, &mailbox_tbl, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (input_maibox_data->mailbox_id)
+               read_mail_uid.mailbox_id = input_maibox_data->mailbox_id;
+       else
+               read_mail_uid.mailbox_id = mailbox_tbl->mailbox_id;
+
+       read_mail_uid.local_uid = mail_id;
+       EM_DEBUG_LOG("MAIL ID [%d] LOCAL_UID [%d]", mail_id, read_mail_uid.local_uid);
+
+       if (server_mailbox_name)
+               read_mail_uid.mailbox_name = server_mailbox_name;
+       else
+               read_mail_uid.mailbox_name = mailbox_tbl->mailbox_name;
+
+       read_mail_uid.s_uid = uid;
+       read_mail_uid.data1 = rfc822_size;
+       read_mail_uid.flag = rule_id;
+
+       if (!emstorage_add_downloaded_mail(&read_mail_uid, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_add_downloaded_mail failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int emcore_add_mail_to_mailbox(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_mail_tbl_t *input_new_mail_tbl_data, int *output_mail_id, int *output_thread_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_maibox_data[%p], input_new_mail_tbl_data[%p], uid_elem[%p], output_mail_id[%p], output_thread_id[%p]", mail_stream, input_maibox_data, input_new_mail_tbl_data, output_mail_id, output_thread_id);
+
+       int                   err = EMAIL_ERROR_NONE;
+       int                   thread_id = -1;
+       int                   thread_item_count = 0;
+       int                   latest_mail_id_in_thread = -1;
+
+       if (!input_maibox_data || !input_new_mail_tbl_data) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       input_new_mail_tbl_data->account_id            = input_maibox_data->account_id;
+       input_new_mail_tbl_data->mailbox_id            = input_maibox_data->mailbox_id;
+       input_new_mail_tbl_data->mailbox_name          = EM_SAFE_STRDUP(input_maibox_data->mailbox_name);
+       input_new_mail_tbl_data->mailbox_type          = input_maibox_data->mailbox_type;
+
+       emstorage_begin_transaction(NULL, NULL, NULL);
+
+       /* Get the Mail_id */
+       if (!emstorage_increase_mail_id(&(input_new_mail_tbl_data->mail_id), false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_increase_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (emstorage_get_thread_id_of_thread_mails(input_new_mail_tbl_data, &thread_id, &latest_mail_id_in_thread, &thread_item_count)  != EMAIL_ERROR_NONE)
+               EM_DEBUG_LOG(" emstorage_get_thread_id_of_thread_mails is failed.");
+
+       if (thread_id == -1){
+               input_new_mail_tbl_data->thread_id = input_new_mail_tbl_data->mail_id;
+               input_new_mail_tbl_data->thread_item_count = thread_item_count = 1;
+       }
+       else {
+               input_new_mail_tbl_data->thread_id = thread_id;
+               thread_item_count++;
+       }
+
+       if (!emstorage_add_mail(input_new_mail_tbl_data, 0, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_add_mail failed [%d]", err);
+               emstorage_rollback_transaction(NULL, NULL, NULL);
+               goto FINISH_OFF;
+       }
+
+       if (thread_item_count > 1){
+               if (!emstorage_update_latest_thread_mail(input_new_mail_tbl_data->account_id, input_new_mail_tbl_data->thread_id, 0, 0, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_update_latest_thread_mail failed [%d]", err);
+                       emstorage_rollback_transaction(NULL, NULL, NULL);
+                       goto FINISH_OFF;
+               }
+       }
+       if (output_thread_id)
+               *output_thread_id = input_new_mail_tbl_data->thread_id;
+
+       if (output_mail_id != NULL)
+               *output_mail_id = input_new_mail_tbl_data->mail_id;
+
+       EM_DEBUG_LOG("mail_table_data.mail_id [%d]", input_new_mail_tbl_data->mail_id);
+       EM_DEBUG_LOG("mail_table_data.thread_id [%d]", input_new_mail_tbl_data->thread_id);
+
+       if (!emcore_add_read_mail_uid(input_maibox_data, input_maibox_data->mailbox_name, input_new_mail_tbl_data->mail_id, input_new_mail_tbl_data->server_mail_id, input_new_mail_tbl_data->mail_size, 0, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_add_read_mail_uid failed [%d]", err);
+               emstorage_rollback_transaction(NULL, NULL, NULL);
+               goto FINISH_OFF;
+       }
+
+       emstorage_commit_transaction(NULL, NULL, NULL);
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+int emcore_check_rule(const char *input_full_address_from, const char *input_subject, emstorage_rule_tbl_t *rule, int rule_len, int *matched, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_full_address_from [%p], input_subject [%p], rule [%p], rule_len [%d], matched [%p], err_code [%p]", input_full_address_from, input_subject, rule, rule_len, matched, err_code);
+
+       int ret = false, err = EMAIL_ERROR_NONE, i;
+       size_t len = 0;
+       char *src = NULL;       /*  string which will be compared with rules */
+       char *from_address = NULL;
+       ADDRESS *addr = NULL;
+
+       if (!matched || !input_full_address_from || !input_subject) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       *matched = -1;
+
+       rfc822_parse_adrlist(&addr, (char*)input_full_address_from, NULL);
+
+       if(addr) {
+               EM_DEBUG_LOG("rule : full_address_from[%s], addr->mailbox[%s], addr->host[%s]", input_full_address_from, addr->mailbox, addr->host);
+
+               if (addr->mailbox)
+                       len = EM_SAFE_STRLEN(addr->mailbox);
+               if (addr->host)
+                       len  += EM_SAFE_STRLEN(addr->host);
+                       len  += 2;
+
+               if (!(from_address = em_malloc(len))) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed...");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               SNPRINTF(from_address, len, "%s@%s", addr->mailbox, addr->host);
+       }
+       else  {
+               EM_DEBUG_EXCEPTION("rfc822_parse_adrlist failed.");
+               err = EMAIL_ERROR_INVALID_ADDRESS;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < rule_len; i++) {
+               if (!(rule + i)) {
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+                       err = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("rule[%d].flag1(rule id[%d]) is %d", i, rule[i].rule_id, rule[i].flag1);
+
+               if (rule[i].flag1){
+                       /*  'ON' */
+                       EM_DEBUG_LOG("rule[%d].flag2(rule id[%d]) is %d", i, rule[i].rule_id, rule[i].flag2);
+                       switch (rule[i].type) {
+                               case EMAIL_FILTER_FROM:
+                                       src = from_address;
+                                       break;
+                               case EMAIL_FILTER_SUBJECT:
+                                       src = (char*)input_subject;
+                                       break;
+                               case EMAIL_FILTER_BODY:
+                                       err = EMAIL_ERROR_NOT_SUPPORTED;
+                                       goto FINISH_OFF;
+                                       break;
+                       }
+                       EM_DEBUG_LOG("rule src[%s], value[%s]\n", src, rule[i].value);
+
+                       if (src && rule[i].value) {
+                           if (RULE_TYPE_INCLUDES == rule[i].flag2) {
+                                       if (strstr(src, rule[i].value)) {
+                                               *matched = i;
+                                               break;
+                                       }
+                               }
+                               else if (RULE_TYPE_EXACTLY == rule[i].flag2) {
+                                       if (!strcmp(src, rule[i].value)) {
+                                               *matched = i;
+                                               break;
+                                       }
+                               }
+                       }
+               }
+               else
+                       EM_DEBUG_LOG("Invald src or rule[i].value");
+       }
+       ret = true;
+
+       EM_DEBUG_LOG("i [%d], matched [%d]", i, *matched);
+FINISH_OFF:
+
+       EM_SAFE_FREE(from_address);
+
+       if (addr  != NULL)
+               mail_free_address(&addr);
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+static int emcore_get_utf8_address(char **dest, ADDRESS *address, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("dest[%p], address[%p], err_code[%p]", dest, address, err_code);
+
+       if (!dest || !address)  {
+               EM_DEBUG_EXCEPTION("dest[%p], address[%p]", dest, address);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       gchar *concatenated = NULL;
+       gchar *utf8_address = NULL;
+       gchar *temp = NULL;
+       char *nickname = NULL;
+
+       while (address)  {
+               EM_DEBUG_LOG("address->mailbox[%s], address->host[%s]", address->mailbox, address->host);
+               if (!address->mailbox || !address->host) {
+                       address = address->next;
+                       continue;
+               }
+               EM_DEBUG_LOG("address->mailbox[%p]", address->personal);
+               if (address->personal)  {
+                       if (!(nickname = emcore_decode_rfc2047_text(address->personal, &err)))  {
+                               EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_text failed - %d", err);
+                               goto FINISH_OFF;
+                       }
+                       EM_DEBUG_LOG("nickname[%s]", nickname);
+                       if (*nickname != '\0')
+                               utf8_address = g_strdup_printf("\"%s\" <%s@%s>", nickname, address->mailbox ? address->mailbox : "", address->host ? address->host : "");
+                       else
+                               utf8_address = g_strdup_printf("<%s@%s>", address->mailbox ? address->mailbox : "", address->host ? address->host : "");
+
+                       EM_SAFE_FREE(nickname);
+               }
+               else
+                       utf8_address = g_strdup_printf("<%s@%s>", address->mailbox ? address->mailbox : "", address->host ? address->host : "");
+
+               EM_DEBUG_LOG("utf8_address[%s]", utf8_address);
+
+               if (concatenated != NULL)  {
+                       temp = concatenated;
+                       concatenated = g_strdup_printf("%s; %s", temp, utf8_address);
+                       g_free(temp);
+               }
+               else
+                       concatenated = g_strdup(utf8_address);
+
+               g_free(utf8_address);
+               utf8_address = NULL;
+
+               address = address->next;
+       }
+
+       *dest = concatenated;
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(nickname);
+       EM_DEBUG_FUNC_END("ret[%d]", ret);
+       return ret;
+}
+
+
+int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *input_envelope, emcore_uid_list *input_uid_elem, emstorage_mail_tbl_t **output_mail_tbl_data,  int *err_code)
+{
+       EM_PROFILE_BEGIN(emCoreParseEnvelope);
+       EM_DEBUG_FUNC_BEGIN("input_envelope[%p], input_uid_elem [%p], output_mail_tbl_data[%p],  err_code[%p]", input_envelope, input_uid_elem, output_mail_tbl_data, err_code);
+
+       int zone_hour = 0;
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int priority = 3;
+       int req_read_receipt = 0;
+       struct tm             temp_time_info;
+       MESSAGECACHE         *mail_cache_element = NULL;
+       emstorage_mail_tbl_t *temp_mail_tbl_data = NULL;
+
+       if (!output_mail_tbl_data) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(temp_mail_tbl_data = em_malloc(sizeof(emstorage_mail_tbl_t)))) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (!(mail_cache_element = mail_elt(mail_stream, input_uid_elem->msgno))) {
+               EM_DEBUG_EXCEPTION("mail_elt failed...");
+               err = EMAIL_ERROR_UNKNOWN;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_mail_extra_info(mail_stream, input_uid_elem->msgno, &req_read_receipt, &priority, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_extra_info failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (input_envelope->subject) {
+               temp_mail_tbl_data->subject = emcore_decode_rfc2047_text(input_envelope->subject, &err);
+               EM_DEBUG_LOG("subject[%s]", temp_mail_tbl_data->subject);
+       }
+
+       if (input_envelope->from) {
+               if (!emcore_get_utf8_address(&temp_mail_tbl_data->full_address_from, input_envelope->from, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("full_address_from[%s]", temp_mail_tbl_data->full_address_from);
+       }
+
+       if (input_envelope->to) {
+               EM_DEBUG_LOG("input_envelope->to");
+               if (!emcore_get_utf8_address(&temp_mail_tbl_data->full_address_to, input_envelope->to, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("full_address_to[%s]", temp_mail_tbl_data->full_address_to);
+       }
+
+       if (input_envelope->cc) {
+               EM_DEBUG_LOG("input_envelope->cc");
+               if (!emcore_get_utf8_address(&temp_mail_tbl_data->full_address_cc, input_envelope->cc, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("full_address_cc [%s]", temp_mail_tbl_data->full_address_cc);
+       }
+
+       if (input_envelope->bcc) {
+               if (!emcore_get_utf8_address(&temp_mail_tbl_data->full_address_bcc, input_envelope->bcc, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("full_address_bcc [%s]", temp_mail_tbl_data->full_address_bcc);
+       }
+
+       if (input_envelope->reply_to) {
+               if (!emcore_get_utf8_address(&temp_mail_tbl_data->full_address_reply, input_envelope->reply_to, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("full_address_reply [%s]\n", temp_mail_tbl_data->full_address_reply);
+       }
+
+       if (input_envelope->return_path) {
+               if (!emcore_get_utf8_address(&temp_mail_tbl_data->full_address_return , input_envelope->return_path, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_utf8_address failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               EM_DEBUG_LOG("full_address_return[%s]", temp_mail_tbl_data->full_address_return);
+       }
+
+       temp_mail_tbl_data->message_id            = EM_SAFE_STRDUP(input_envelope->message_id);
+
+       memset((void*)&temp_time_info, 0,  sizeof(struct tm));
+
+       EM_DEBUG_LOG("tm_hour[%d] zhours [%d] tm_min[%d] zminutes[%d] zoocident[%d]", mail_cache_element->hours, mail_cache_element->zhours,  mail_cache_element->minutes, mail_cache_element->zminutes, mail_cache_element->zoccident);
+
+       zone_hour = mail_cache_element->zhours * (mail_cache_element->zoccident?-1:1);
+
+       temp_time_info.tm_sec  = mail_cache_element->seconds;
+       temp_time_info.tm_min  = mail_cache_element->minutes + mail_cache_element->zminutes;
+       temp_time_info.tm_hour = mail_cache_element->hours - zone_hour;
+
+       if(temp_time_info.tm_hour < 0) {
+               temp_time_info.tm_mday = mail_cache_element->day - 1;
+               temp_time_info.tm_hour += 24;
+       }
+       else
+               temp_time_info.tm_mday = mail_cache_element->day;
+
+       temp_time_info.tm_mon  = mail_cache_element->month - 1;
+       temp_time_info.tm_year = mail_cache_element->year + 70;
+
+       temp_mail_tbl_data->date_time             = timegm(&temp_time_info);
+
+       temp_mail_tbl_data->server_mail_status    = 1;
+       temp_mail_tbl_data->server_mail_id        = EM_SAFE_STRDUP(input_uid_elem->uid);
+       temp_mail_tbl_data->mail_size             = mail_cache_element->rfc822_size;
+       temp_mail_tbl_data->flags_seen_field      = input_uid_elem->flag.seen;
+       temp_mail_tbl_data->flags_deleted_field   = mail_cache_element->deleted;
+       temp_mail_tbl_data->flags_flagged_field   = mail_cache_element->flagged;
+       temp_mail_tbl_data->flags_answered_field  = mail_cache_element->answered;
+       temp_mail_tbl_data->flags_recent_field    = mail_cache_element->recent;
+       temp_mail_tbl_data->flags_draft_field     = mail_cache_element->draft;
+       temp_mail_tbl_data->flags_forwarded_field = input_uid_elem->flag.forwarded;
+       temp_mail_tbl_data->priority              = priority;
+       temp_mail_tbl_data->report_status         = (req_read_receipt ? EMAIL_MAIL_REQUEST_MDN :  0);
+       temp_mail_tbl_data->attachment_count      = 0;
+
+       emcore_fill_address_information_of_mail_tbl(temp_mail_tbl_data);
+
+       *output_mail_tbl_data = temp_mail_tbl_data;
+       temp_mail_tbl_data = NULL;
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ret != true)
+               EM_SAFE_FREE(temp_mail_tbl_data);
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_PROFILE_END(emCoreParseEnvelope);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl, emstorage_mailbox_tbl_t *input_mailbox_tbl_spam, void *stream_recycle, emcore_uid_list **input_uid_list, int *unread_mail, int *err_code)
+{
+       EM_PROFILE_BEGIN(emCoreSyncHeader);
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_tbl[%p], input_mailbox_tbl_spam[%p], input_uid_list [%p], err_code[%p]", input_mailbox_tbl, input_mailbox_tbl_spam, input_uid_list, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE, err_2 = EMAIL_ERROR_NONE;
+       int err_from_vconf = 0;
+       int status = EMAIL_LIST_FAIL;
+       int download_limit_count;
+       email_account_t      *account_ref = NULL;
+       emstorage_rule_tbl_t *rule = NULL;
+       emcore_uid_list      *uid_list = NULL;
+       emcore_uid_list      *uid_elem = NULL;
+       emstorage_mail_tbl_t *new_mail_tbl_data = NULL;
+       ENVELOPE *env = NULL;
+       int account_id = 0, mail_id = 0, rule_len = 1000, total = 0, unread = 0, i = 0, percentage  = 0, thread_id = -1;
+       void *stream = NULL;
+       char *uid_range = NULL;
+       char mailbox_id_param_string[10] = {0,};
+
+       if (!input_mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM:input_mailbox_tbl[%p]", input_mailbox_tbl);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       account_id = input_mailbox_tbl->account_id;
+       account_ref = emcore_get_account_reference(account_id);
+       if (!account_ref) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - %d", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if(account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4 && input_mailbox_tbl->local_yn == 1) {
+               EM_DEBUG_EXCEPTION("local_yn flag is false for this mailbox");
+               err = EMAIL_ERROR_INVALID_MAILBOX;
+               goto FINISH_OFF;
+       }
+
+       FINISH_OFF_IF_CANCELED;
+
+#ifdef __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__
+       if ((err_from_vconf = vconf_set_int(VCONFKEY_EMAIL_SYNC_STATE, 1)) != 0 ) {
+               EM_DEBUG_LOG("vconf_set_int failed [%d]", err_from_vconf);
+       }
+#endif /* __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__ */
+
+#ifndef        __FEATURE_KEEP_CONNECTION__
+       /*  h.gahlaut :  Recycling of stream is taken care internally in emcore_connect_to_remote_mailbox so no need of this code here */
+       if (stream_recycle)
+               stream = stream_recycle; /*  set stream for recycling connection. */
+#endif
+
+       if (!emcore_connect_to_remote_mailbox(account_id, input_mailbox_tbl->mailbox_id, (void **)&stream, &err) || !stream){
+               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed - %d", err);
+               status = EMAIL_LIST_CONNECTION_FAIL;
+               goto FINISH_OFF;
+       }
+
+       FINISH_OFF_IF_CANCELED;
+
+       /*  save total mail count on server to DB */
+       if (!emstorage_update_mailbox_total_count(account_id, input_mailbox_tbl->mailbox_id, ((MAILSTREAM *)stream)->nmsgs, 1, &err)){
+               EM_DEBUG_EXCEPTION("emstorage_update_mailbox_total_count failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       /* if (((MAILSTREAM *)stream)->nmsgs > 0) */
+       {
+               email_option_t *opt_ref = &account_ref->options;
+               EM_DEBUG_LOG("block_address = %d, block_subject = %d", opt_ref->block_address, opt_ref->block_subject);
+
+               if (opt_ref->block_address || opt_ref->block_subject) {
+                       int is_completed = false;
+                       int type = 0;
+
+                       if (!opt_ref->block_address)
+                               type = EMAIL_FILTER_SUBJECT;
+                       else if (!opt_ref->block_subject)
+                               type = EMAIL_FILTER_FROM;
+
+                       if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_len, &is_completed, &rule, true, &err) || !rule)
+                               EM_DEBUG_EXCEPTION("emstorage_get_rule failed - %d", err);
+               }
+               download_limit_count = input_mailbox_tbl->mail_slot_size;
+               if (!emcore_get_uids_to_download(stream, account_ref, input_mailbox_tbl, download_limit_count,  &uid_list, &total, EMAIL_SYNC_LATEST_MAILS_FIRST, &err)){
+                       EM_DEBUG_EXCEPTION("emcore_get_uids_to_download failed [%d]", err);
+                       uid_list = NULL;
+                       goto FINISH_OFF;
+               }
+
+               FINISH_OFF_IF_CANCELED;
+
+               if (input_uid_list && *input_uid_list){
+                       emcore_free_uids(*input_uid_list, NULL);
+                       *input_uid_list = uid_list;
+               }
+               uid_elem = uid_list;
+               i = 0;
+               EM_PROFILE_BEGIN(emCoreSyncHeaderwhileloop);
+
+#ifdef  __FEATURE_HEADER_OPTIMIZATION__
+               /* g.shyamakshi@samsung.com : Bulk fetch of headers only if the recieving server type is IMAP */
+
+               EM_DEBUG_LOG("((MAILSTREAM *)stream)->nmsgs [%d]", ((MAILSTREAM *)stream)->nmsgs);
+               EM_DEBUG_LOG("uid_list [%p]", uid_list);
+               if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4 && uid_list  != NULL){
+                       emcore_uid_list *uid_list_prev = NULL;
+                       emcore_uid_list *uid_list_fast = uid_list;
+                       int index = 0;
+                       int msg_count = total;
+                       int uid_range_size = msg_count * 8 + 1000;
+
+                       EM_DEBUG_LOG("memory allocation for uid_range [%d, %d]", msg_count, uid_range_size);
+                       uid_range = malloc(sizeof(char) * uid_range_size);
+
+                       if (uid_range == NULL){
+                               EM_DEBUG_EXCEPTION("memory allocation for uid_range failed");
+                               err  = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       uid_list_prev = uid_list_fast;
+
+                       if (uid_list_fast->next == NULL){
+                               /* Single list entry */
+                               snprintf(uid_range, uid_range_size, "%d", atoi(uid_list_fast->uid));
+                       }
+                       else{
+                               /* forming range of uids to be passed */
+                               while (uid_list_fast  != NULL){
+                                       /* uid_list_fast = uid_list_fast->next; */
+
+                                       if ((uid_list_fast->next != NULL) && (((atoi(uid_list_prev->uid)) - (atoi(uid_list_fast->next->uid))) == 1)){
+                                               index += snprintf(uid_range+index, uid_range_size, "%d", atoi(uid_list_prev->uid));
+
+                                               uid_list_fast = uid_list_fast->next;
+                                               uid_list_prev = uid_list_fast;
+
+                                               /* to make UID range string "abc, XX : YY" */
+                                               while (uid_list_fast  != NULL){
+                                                       if (uid_list_fast->next == NULL)
+                                                               break;
+                                                       if (((atoi(uid_list_prev->uid)) - (atoi(uid_list_fast->next->uid))) == 1){
+                                                               uid_list_fast = uid_list_fast->next;
+                                                               uid_list_prev = uid_list_fast;
+                                                       }
+                                                       else
+                                                               break;
+                                               }
+                                               if ((uid_list_fast  != NULL) && (uid_list_fast->next  != NULL))
+                                                       index  += snprintf(uid_range+index, uid_range_size, ":%d,", atoi(uid_list_prev->uid));
+                                               else
+                                                       index  += snprintf(uid_range+index, uid_range_size, ":%d", atoi(uid_list_prev->uid));
+
+                                               uid_list_fast = uid_list_fast->next;
+                                               uid_list_prev = uid_list_fast;
+                                       }
+                                       else{
+                                               if (uid_list_fast->next  != NULL)
+                                                       index  += snprintf(uid_range+index, uid_range_size, "%d,", atoi(uid_list_prev->uid));
+                                               else
+                                                       index  += snprintf(uid_range+index, uid_range_size, "%d", atoi(uid_list_prev->uid));
+                                               uid_list_fast = uid_list_fast->next;
+                                               uid_list_prev = uid_list_fast;
+                                       }
+                               }
+                       }
+
+                       /* h.gahlaut :  [Start] */
+                       /* Adding this check here to check if application has called cancel job. */
+                       /* This checking should be done because fetching 50 headers will take time  */
+                       FINISH_OFF_IF_CANCELED;
+
+                       EM_DEBUG_LOG("index [%d]", index);
+
+                       /*  h.gahlaut :  [End] */
+                       uid_elem = uid_list;
+                       if (stream && uid_elem){
+                               EM_DEBUG_LOG("msgno : %d", uid_elem->msgno);
+                               ((MAILSTREAM *)stream)->nmsgs = uid_elem->msgno;
+                       }
+                       else{
+                               EM_DEBUG_LOG("Uid List Null");
+                       }
+                       EM_DEBUG_LOG("Calling ... mail_fetch_fast. uid_range [%s]", uid_range);
+                       mail_fetch_fast(stream, uid_range, FT_UID | FT_PEEK | FT_NEEDENV);
+                       EM_SAFE_FREE(uid_range);
+               }
+#endif
+
+               /*  h.gahlaut@samsung.com :  Clear the event queue of partial body download thread before starting fetching new headers  */
+#ifndef __PARTIAL_BODY_FOR_POP3__
+               if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4){
+#endif /*  __PARTIAL_BODY_FOR_POP3__ */
+                       /*  Partial body download feature is only for IMAP accounts  */
+                       if (false == emcore_clear_partial_body_thd_event_que(&err))
+                               EM_DEBUG_LOG("emcore_clear_partial_body_thd_event_que failed [%d]", err);
+#ifndef __PARTIAL_BODY_FOR_POP3__
+               }
+#endif /*  __PARTIAL_BODY_FOR_POP3__ */
+               while (uid_elem) {
+                       EM_PROFILE_BEGIN(emCoreSyncHeaderEachMail);
+                       EM_DEBUG_LOG("mail_fetchstructure_full  :  uid_elem->msgno[%d]", uid_elem->msgno);
+
+                       env = NULL;
+
+                       if (uid_elem->msgno > ((MAILSTREAM *)stream)->nmsgs)
+                               EM_DEBUG_EXCEPTION("Warnings! msgno[%d] can't be greater than nmsgs[%d]. It might cause crash.", uid_elem->msgno, ((MAILSTREAM *)stream)->nmsgs);
+                       else{
+
+#ifdef __FEATURE_HEADER_OPTIMIZATION__
+                               if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) /* Fetch env from cache in case of IMAP */
+                                       env = mail_fetchstructure_full(stream, uid_elem->msgno, NULL, FT_PEEK, 0);
+                               else /* Fetch header from network in case of POP */
+                                       env = mail_fetchstructure_full(stream, uid_elem->msgno, NULL, FT_PEEK, 1);
+#else
+                               env = mail_fetchstructure_full(stream, uid_elem->msgno, NULL, FT_PEEK);
+#endif
+                       }
+                       FINISH_OFF_IF_CANCELED;
+
+                       if (env != NULL){
+                               int matched = -1;
+
+                               if (!emcore_make_mail_tbl_data_from_envelope(stream, env, uid_elem, &new_mail_tbl_data, &err) || !new_mail_tbl_data) {
+                                       EM_DEBUG_EXCEPTION("emcore_make_mail_tbl_data_from_envelope failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+
+                               if (rule && input_mailbox_tbl_spam && !emcore_check_rule(new_mail_tbl_data->full_address_from, new_mail_tbl_data->subject, rule, rule_len, &matched, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_check_rule failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+
+                               if (matched >= 0 && input_mailbox_tbl_spam){    /*  add filtered mails to SPAMBOX */
+                                       EM_DEBUG_LOG("mail[%d] added to spambox", mail_id);
+
+                                       if ( (err = emcore_add_mail_to_mailbox(input_mailbox_tbl_spam, new_mail_tbl_data, &mail_id, &thread_id)) != EMAIL_ERROR_NONE) {
+                                               EM_DEBUG_EXCEPTION("emcore_add_mail_to_mailbox falied [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+
+                                       if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4){
+                                               if (!emcore_move_mail_on_server(account_id, input_mailbox_tbl->mailbox_id,  &mail_id, 1, input_mailbox_tbl_spam->mailbox_name, &err)){
+                                                       EM_DEBUG_EXCEPTION("emcore_move_mail_on_server falied [%d]", err);
+                                                       goto FINISH_OFF;
+                                               }
+                                       }
+                               } else {
+                                       /*  add mails to specified mail box */
+                                       EM_DEBUG_LOG("mail[%d] moved to input_mailbox_tbl [%s]", mail_id, input_mailbox_tbl->mailbox_name);
+                                       if ( (err = emcore_add_mail_to_mailbox(input_mailbox_tbl, new_mail_tbl_data, &mail_id, &thread_id)) != EMAIL_ERROR_NONE) {
+                                               EM_DEBUG_EXCEPTION("emcore_add_mail_to_mailbox falied [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+
+                                       /*h.gahlaut :  Start partial body dowload using partial body thread only for IMAP accounts*/
+#ifndef __PARTIAL_BODY_FOR_POP3__
+                                       if (account_ref->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+#endif /*  __PARTIAL_BODY_FOR_POP3__ */
+                                               if (account_ref->auto_download_size != 0) {
+                                                       if (false == emcore_initiate_pbd(stream, account_id, mail_id, uid_elem->uid, input_mailbox_tbl->mailbox_id, &err))
+                                                               EM_DEBUG_LOG("Partial body download initiation failed [%d]", err);
+                                               }
+#ifndef __PARTIAL_BODY_FOR_POP3__
+                                       }
+#endif /*  __PARTIAL_BODY_FOR_POP3__ */
+/*
+                                       if (!uid_elem->flag.seen && input_mailbox_tbl->mailbox_type != EMAIL_MAILBOX_TYPE_SPAMBOX)
+                                               emcore_add_notification_for_unread_mail(new_mail_tbl_data);
+*/
+                                       FINISH_OFF_IF_CANCELED;
+
+                                       if (!uid_elem->flag.seen)
+                                               unread++;
+
+                                       percentage = ((i+1) * 100) / total ;
+                                       EM_DEBUG_LOG("Header Percentage Completed [%d] : [%d/%d]  mail_id [%d]", percentage, i+1, total, mail_id);
+                                       SNPRINTF(mailbox_id_param_string, 10, "%d", input_mailbox_tbl->mailbox_id);
+
+                                       if (!emcore_notify_storage_event(NOTI_MAIL_ADD, account_id, mail_id, mailbox_id_param_string, thread_id))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_storage_event [NOTI_MAIL_ADD] failed");
+                               }
+
+                               /* Set contact log */
+                               switch (input_mailbox_tbl->mailbox_type) {
+                               case EMAIL_MAILBOX_TYPE_INBOX :
+                                       if ((err = emcore_set_received_contacts_log(new_mail_tbl_data)) != EMAIL_ERROR_NONE) {
+                                               EM_DEBUG_EXCEPTION("emcore_set_received_contacts_log failed : [%d]", err);
+                                       }
+                                       break;
+                               case EMAIL_MAILBOX_TYPE_SENTBOX:
+                               case EMAIL_MAILBOX_TYPE_OUTBOX:
+                                       if ((err = emcore_set_sent_contacts_log(new_mail_tbl_data)) != EMAIL_ERROR_NONE) {
+                                               EM_DEBUG_EXCEPTION("emcore_set_sent_contacts_log failed : [%d]", err);
+                                       }
+                                       break;
+                               default:
+                                       EM_DEBUG_LOG("Mailbox type : [%d]", input_mailbox_tbl->mailbox_type);
+                                       break;
+                               }
+
+                               /*  Release for envelope is not required and it may cause crash. Don't free the memory for envelope here. */
+                               /*  Envelope data will be freed by garbage collector in mail_close_full */
+                               if (new_mail_tbl_data){
+                                       emstorage_free_mail(&new_mail_tbl_data, 1, NULL);
+                                       new_mail_tbl_data = NULL;
+                               }
+
+                               FINISH_OFF_IF_CANCELED;
+                       }
+
+                       uid_elem = uid_elem->next;
+                       i++;
+                       EM_PROFILE_END(emCoreSyncHeaderEachMail);
+               }
+               EM_PROFILE_END(emCoreSyncHeaderwhileloop);
+       }
+
+       ret = true;
+FINISH_OFF:
+
+       *unread_mail = unread;
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
+       if (!emcore_remove_overflowed_mails(input_mailbox_tbl, &err_2))
+               EM_DEBUG_EXCEPTION("emcore_remove_overflowed_mails failed - %d", err_2);
+
+       if (input_mailbox_tbl)
+               emstorage_stamp_last_sync_time_of_mailbox(input_mailbox_tbl->mailbox_id, 1);
+
+#ifdef __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__
+       if ((err_from_vconf = vconf_set_int(VCONFKEY_EMAIL_SYNC_STATE, 0)) != 0 ) {
+               EM_DEBUG_LOG("vconf_set_int failed [%d]", err_from_vconf);
+       }
+#endif /* __FEATURE_SUPPORT_SYNC_STATE_ON_NOTI_BAR__ */
+
+       if (new_mail_tbl_data)
+               emstorage_free_mail(&new_mail_tbl_data, 1, NULL);
+
+       if (uid_list != NULL){
+               emcore_free_uids(uid_list, NULL);
+               /*  uid_list point to the same memory with input_mailbox_tbl->user_data.  */
+               /*  input_mailbox_tbl->user_data should be set NULL if uid_list is freed */
+               *input_uid_list = NULL;
+       }
+
+       EM_SAFE_FREE(uid_range);
+
+       if (rule  != NULL)
+               emstorage_free_rule(&rule, rule_len, NULL);
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+       if (stream  != NULL) {
+#else /*  __FEATURE_KEEP_CONNECTION__   */
+       if (stream  != NULL && stream_recycle == NULL)  {
+#endif /*  __FEATURE_KEEP_CONNECTION__  */
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+       }
+
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_PROFILE_END(emCoreSyncHeader);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+emcore_uid_list *__ReverseList(emcore_uid_list *uid_list)
+{
+       emcore_uid_list *temp, *current, *result;
+
+       temp = NULL;
+       result = NULL;
+       current = uid_list;
+
+       while (current != NULL){
+               temp = current->next;
+               current->next = result;
+               result = current;
+               current = temp;
+       }
+       uid_list = result;
+       return uid_list;
+}
+
+
+
+int emcore_download_uid_all(email_internal_mailbox_t *mailbox, emcore_uid_list** uid_list, int *total, emstorage_read_mail_uid_tbl_t *downloaded_uids, int count, emcore_get_uids_for_delete_t for_delete, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox[%p], uid_list[%p], total[%p], downloaded_uids[%p], count[%d], for_delete[%d], err_code[%p]", mailbox, uid_list, total, downloaded_uids, count, for_delete, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       MAILSTREAM *stream = NULL;
+       email_account_t *ref_account = NULL;
+       emcore_uid_list *uid_elem = NULL;
+       emcore_uid_list *fetch_data_p = NULL;
+       void *tmp_stream = NULL;
+       char cmd[64] = {0x00, };
+       char *p = NULL;
+
+       if (!mailbox || !uid_list) {
+               EM_DEBUG_EXCEPTION("mailbox[%p], uid_list[%p], total[%p], downloaded_uids[%p], count[%d], for_delete[%d]", mailbox, uid_list, total, downloaded_uids, count, for_delete);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(ref_account = emcore_get_account_reference(mailbox->account_id))) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - %d", mailbox->account_id);
+
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!mailbox->mail_stream) {
+               if (!emcore_connect_to_remote_mailbox(mailbox->account_id, mailbox->mailbox_id, (void **)&tmp_stream, &err)){
+                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed...");
+
+                       goto FINISH_OFF;
+               }
+
+               stream = (MAILSTREAM *)tmp_stream;
+       }
+       else
+               stream = mailbox->mail_stream;
+
+       if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_POP3) {              /*  POP3 */
+               POP3LOCAL *pop3local = NULL;
+
+               if (!stream || !(pop3local = stream->local) || !pop3local->netstream) {
+                       err = EMAIL_ERROR_INVALID_PARAM;                /* EMAIL_ERROR_UNKNOWN; */
+                       goto FINISH_OFF;
+               }
+
+               /*  send UIDL */
+               memset(cmd, 0x00, sizeof(cmd));
+
+               SNPRINTF(cmd, sizeof(cmd), "UIDL\015\012");
+
+#ifdef FEATURE_CORE_DEBUG
+               EM_DEBUG_LOG("[POP3] >>> [%s]", cmd);
+#endif
+
+               if (!net_sout(pop3local->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+                       EM_DEBUG_EXCEPTION("net_sout failed...");
+
+                       err = EMAIL_ERROR_CONNECTION_BROKEN;
+                       goto FINISH_OFF;
+               }
+
+               /*  get uid from replied data */
+               while (pop3local->netstream) {
+                       char *s = NULL;
+
+                       if (!(p = net_getline(pop3local->netstream)))
+                               break;
+
+#ifdef FEATURE_CORE_DEBUG
+                       EM_DEBUG_LOG(" [POP3] <<< [%s]", p);
+#endif
+
+                       /*  replied error "-ERR" */
+                       if (*p == '-') {
+                               err = EMAIL_ERROR_MAIL_NOT_FOUND;
+                               goto FINISH_OFF;
+                       }
+
+                       /*  replied success "+OK" */
+                       if (*p == '+') {
+                               free(p); p = NULL;
+                               continue;
+                       }
+
+                       /*  end of command */
+                       if (*p == '.')
+                               break;
+
+                       /* EM_DEBUG_LOG("UID list [%s]", p); */
+
+                       uid_elem = (emcore_uid_list *)malloc(sizeof(emcore_uid_list));
+                       if (!uid_elem) {
+                               EM_DEBUG_EXCEPTION("malloc falied...");
+
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       memset(uid_elem, 0x00, sizeof(emcore_uid_list));
+
+                       /*  format  :  "1 AAA6FHEAAAQrB6c1ymXxty04yks7hcQ7" */
+
+                       /*  save uid                     */
+                       s = strstr(p, " ");
+                       if (s) {
+                               *s = '\0';
+                               uid_elem->msgno = atoi(p);
+                               uid_elem->uid = EM_SAFE_STRDUP(s+1);
+                       }
+
+                       /*  check downloaded_uids */
+                       if (downloaded_uids) {
+                               int i;
+                               for (i = 0; i < count; ++i) {
+                                       if (!strcmp(uid_elem->uid, downloaded_uids[i].s_uid)) {
+                                               downloaded_uids[i].flag = 1;
+                                               break;
+                                       }
+                               }
+                       }
+
+                       if (*uid_list) {
+                               fetch_data_p = *uid_list;
+
+                               while (fetch_data_p->next)
+                                       fetch_data_p = fetch_data_p->next;
+
+                               fetch_data_p->next = uid_elem;
+                       }
+                       else
+                               *uid_list = uid_elem;
+
+                       if (total)
+                               ++(*total);
+
+                       free(p); p = NULL;
+               }
+       }
+       else {          /*  IMAP */
+               IMAPLOCAL *imaplocal = NULL;
+               char tag[16];
+               char *s = NULL;
+               char *t = NULL;
+
+               if (!stream || !(imaplocal = stream->local) || !imaplocal->netstream) {
+                       err = EMAIL_ERROR_INVALID_PARAM;                /* EMAIL_ERROR_UNKNOWN; */
+                       goto FINISH_OFF;
+               }
+
+               /*  send FETCH UID */
+               memset(tag, 0x00, sizeof(tag));
+               memset(cmd, 0x00, sizeof(cmd));
+
+               SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+               SNPRINTF(cmd, sizeof(cmd), "%s UID FETCH %d:* (FLAGS)\015\012", tag, 1);
+#ifdef FEATURE_CORE_DEBUG
+               EM_DEBUG_LOG("[IMAP] >>> %s", cmd);
+#endif
+               if (!net_sout(imaplocal->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+                       EM_DEBUG_EXCEPTION("net_sout failed...");
+
+                       err = EMAIL_ERROR_CONNECTION_BROKEN;
+                       goto FINISH_OFF;
+               }
+
+               /*  get uid from replied data */
+               while (imaplocal->netstream) {
+                       if (!(p = net_getline(imaplocal->netstream)))
+                               break;
+
+                       /* EM_DEBUG_LOG(" [IMAP] <<< %s", p); */
+
+                       /*  tagged line - end of command */
+                       if (!strncmp(p, tag, EM_SAFE_STRLEN(tag)))
+                               break;
+
+                       /*  check that reply is reply to our command */
+                       /*  format  :  "* 9 FETCH (UID 68)" */
+                       if (!strstr(p, "FETCH (FLAGS")) {
+                               free(p); p = NULL;
+                               continue;
+                       }
+
+                       if (for_delete == EM_CORE_GET_UIDS_FOR_NO_DELETE) {
+                               if ((ref_account->retrieval_mode == EMAIL_IMAP4_RETRIEVAL_MODE_NEW) && (strstr(p, "\\Seen"))) {
+                                       free(p); p = NULL;
+                                       continue;
+                               }
+                       }
+
+                       uid_elem = (emcore_uid_list *)malloc(sizeof(emcore_uid_list));
+                       if (!uid_elem) {
+                               EM_DEBUG_EXCEPTION("malloc failed...");
+
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       memset(uid_elem, 0x00, sizeof(emcore_uid_list));
+                       /*  parse uid, sequence, flags from replied data */
+
+                       /*  parse uid from replied data */
+                       s = p+2;
+                       t = strchr(s, ' ');
+
+                       if (!t) {
+                               err = EMAIL_ERROR_INVALID_RESPONSE;
+                               goto FINISH_OFF;
+                       }
+
+                       *t = '\0';
+
+                       /*  save sequence */
+                       uid_elem->msgno = atoi(s);
+
+                       if (strstr(++t, "\\Deleted"))
+                               uid_elem->flag.deleted = 1;
+
+                       /*  parse uid */
+                       s  = strstr(++t, "UID ");
+                       if (s) {
+                               s  += strlen("UID ");
+                               t  = strchr(s, ')');
+
+                               if (!t) {
+                                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                                       goto FINISH_OFF;
+                               }
+
+                               *t = '\0';
+                       }
+                       else {
+                               err = EMAIL_ERROR_INVALID_RESPONSE;
+                               goto FINISH_OFF;
+                       }
+
+                       /*  save uid */
+                       uid_elem->uid = EM_SAFE_STRDUP(s);
+
+                       /*  check downloaded_uids */
+                       if (downloaded_uids) {
+                               int i;
+                               for (i = 0; i < count; ++i) {
+                                       if (uid_elem->uid && !strcmp(uid_elem->uid, downloaded_uids[i].s_uid)) {
+                                               downloaded_uids[i].flag = 1;
+                                               free(uid_elem->uid);
+                                               free(uid_elem); uid_elem = NULL;
+                                               break;
+                                       }
+                               }
+                       }
+
+                       if (uid_elem) {
+                               if (*uid_list) {
+                                       fetch_data_p = *uid_list;
+
+                                       while (fetch_data_p->next)
+                                               fetch_data_p = fetch_data_p->next;
+
+                                       fetch_data_p->next = uid_elem;
+                               }
+                               else {
+                                       *uid_list = uid_elem;
+                               }
+
+                               if (total)
+                                       ++(*total);
+                       }
+
+                       free(p); p = NULL;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (uid_elem && ret == false)
+               free(uid_elem);
+
+       if (p)
+               free(p);
+
+       if (mailbox && !mailbox->mail_stream) {
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+       }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int emcore_download_imap_msgno(email_internal_mailbox_t *mailbox, char *uid, int *msgno, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox[%p], uid[%p], msgno[%p], err_code[%p]", mailbox, uid, msgno, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       MAILSTREAM *stream = NULL;
+       IMAPLOCAL *imaplocal = NULL;
+       email_account_t *ref_account = NULL;
+       void *tmp_stream = NULL;
+       char tag[32], cmd[64];
+       char *p = NULL;
+
+       if (!mailbox || !uid) {
+               EM_DEBUG_EXCEPTION("mailbox[%p], uid[%p], msgno[%p]", mailbox, uid, msgno);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(ref_account = emcore_get_account_reference(mailbox->account_id))) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", mailbox->account_id);
+
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (ref_account->incoming_server_type  != EMAIL_SERVER_TYPE_IMAP4) {
+               err = EMAIL_ERROR_INVALID_ACCOUNT;              /* EMAIL_ERROR_INVALID_PARAM; */
+               goto FINISH_OFF;
+       }
+
+       if (!mailbox->mail_stream) {
+               if (!emcore_connect_to_remote_mailbox(mailbox->account_id, mailbox->mailbox_id, (void **)&tmp_stream, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed - %d", err);
+
+                       goto FINISH_OFF;
+               }
+
+               stream = (MAILSTREAM *)tmp_stream;
+       }
+       else
+               stream = mailbox->mail_stream;
+
+       if (!stream || !(imaplocal = stream->local) || !imaplocal->netstream) {
+               err = EMAIL_ERROR_INVALID_PARAM;                /* EMAIL_ERROR_UNKNOWN; */
+               goto FINISH_OFF;
+       }
+
+       /*  send SEARCH UID */
+       memset(tag, 0x00, sizeof(tag));
+       memset(cmd, 0x00, sizeof(cmd));
+
+       SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+       SNPRINTF(cmd, sizeof(cmd), "%s SEARCH UID %s\015\012", tag, uid);
+
+       if (!net_sout(imaplocal->netstream, cmd, (int)EM_SAFE_STRLEN(cmd))) {
+               EM_DEBUG_EXCEPTION("net_sout failed...");
+
+               err = EMAIL_ERROR_CONNECTION_BROKEN;
+               goto FINISH_OFF;
+       }
+
+       /*  get message number from replied data */
+       while (imaplocal->netstream) {
+               if (!(p = net_getline(imaplocal->netstream)))
+                       break;
+
+               /*  tagged line - end of command */
+               if (!strncmp(p, tag, EM_SAFE_STRLEN(tag)))
+                       break;
+
+               /*  check that reply is reply to our command */
+               /*  format :  "* SEARCH 68", if not found, "* SEARCH" */
+               if (!strstr(p, "SEARCH ") || (p[9] < '0' || p[9] > '9')) {
+                       free(p); p = NULL;
+                       continue;
+               }
+
+               if (msgno)
+                       *msgno = atoi(p+9);
+
+               free(p); p = NULL;
+
+               ret = true;
+       }
+
+       if (ret  != true)
+               err = EMAIL_ERROR_MAIL_NOT_FOUND;
+
+FINISH_OFF:
+       if (p)
+               free(p);
+
+       if (mailbox && !mailbox->mail_stream){
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+       }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int emcore_get_msgno(emcore_uid_list *uid_list, char *uid, int *msgno, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("uid_list[%p], uid[%s], msgno[%p], err_code[%p]", uid_list, uid, msgno, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_MAIL_NOT_FOUND;           /* EMAIL_ERROR_NONE; */
+
+       if (!uid || !msgno || !uid_list) {
+               EM_DEBUG_EXCEPTION("uid_list[%p], uid[%p], msgno[%p]", uid_list, uid, msgno);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG(" >> uid[%s]", uid);
+
+       while (uid_list) {
+               if (!strcmp(uid_list->uid, uid)) {
+                       *msgno = uid_list->msgno;
+
+                       EM_DEBUG_LOG("*msgno[%d]", *msgno);
+
+                       err = EMAIL_ERROR_NONE;
+
+                       ret = true;
+                       break;
+               }
+
+               uid_list = uid_list->next;
+       }
+
+FINISH_OFF:
+       if (err_code  != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int emcore_get_uid(emcore_uid_list *uid_list, int msgno, char **uid, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false, err = EMAIL_ERROR_NONE;
+
+       if (!uid || msgno <= 0 || !uid_list){
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       while (uid_list) {
+               if (uid_list->msgno == msgno) {
+                       if (uid) {
+                               if (!(*uid = EM_SAFE_STRDUP(uid_list->uid))) {
+                                       EM_DEBUG_EXCEPTION("strdup failed...");
+                                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                       goto FINISH_OFF;
+                               }
+
+                               ret = true;
+                               break;
+                       }
+               }
+
+               uid_list = uid_list->next;
+       }
+
+       if (ret  != true)
+               err = EMAIL_ERROR_MAIL_NOT_FOUND;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int emcore_free_uids(emcore_uid_list *uid_list, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("uid_list[%p], err_code[%p]", uid_list, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emcore_uid_list *p = NULL;
+
+       if (!uid_list) {
+               EM_DEBUG_EXCEPTION(" uid_list[%p]\n", uid_list);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       while (uid_list) {
+               p = uid_list;
+               uid_list = uid_list->next;
+               EM_SAFE_FREE(p->uid);
+               free(p);
+               p = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+/* callback for GET_APPENDUID - shasikala.p */
+void mail_appenduid(char *mailbox, unsigned long uidvalidity, SEARCHSET *set)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox - %s", mailbox);
+    EM_DEBUG_LOG("UID - %ld", set->first);
+
+    memset(g_append_uid_rsp, 0x00, 129);
+
+    sprintf(g_append_uid_rsp, "%ld", set->first);
+    EM_DEBUG_LOG("append uid - %s", g_append_uid_rsp);
+}
+
+INTERNAL_FUNC int emcore_sync_mail_from_client_to_server(int mail_id)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id [%d]", mail_id);
+
+       int                             err                  = EMAIL_ERROR_NONE;
+       int                             len                  = 0;
+       int                             read_size            = 0;
+       int                             attachment_tbl_count = 0;
+       char                           *fname                = NULL;
+       char                           *long_enc_path        = NULL;
+       char                           *data                 = NULL;
+       char                            set_flags[100]       = { 0, };
+       ENVELOPE                       *envelope             = NULL;
+       FILE                           *fp                   = NULL;
+       STRING                          str;
+       MAILSTREAM                     *stream               = NULL;
+       email_account_t                *account_ref          = NULL;
+       emstorage_mail_tbl_t           *mail_table_data      = NULL;
+       emstorage_attachment_tbl_t     *attachment_tbl_data  = NULL;
+       emstorage_mailbox_tbl_t        *mailbox_tbl          = NULL;
+
+       /*  get a mail from mail table */
+       if (!emstorage_get_mail_by_id(mail_id, &mail_table_data, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       account_ref = emcore_get_account_reference(mail_table_data->account_id);
+
+       if(account_ref == NULL || account_ref->incoming_server_type != EMAIL_SERVER_TYPE_IMAP4) {
+               EM_DEBUG_EXCEPTION("This account doesn't support sync");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_attachment_list(mail_id, false, &attachment_tbl_data, &attachment_tbl_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("mailbox_name [%s]", mail_table_data->mailbox_name);
+       if (!emstorage_get_mailbox_by_name(mail_table_data->account_id, 0, mail_table_data->mailbox_name, &mailbox_tbl, false, &err) || !mailbox_tbl){
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_name failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mailbox_tbl->local_yn == 0) {
+               EM_DEBUG_EXCEPTION("The mailbox [%s] is not on server.", mail_table_data->mailbox_name);
+               err = EMAIL_ERROR_INVALID_MAILBOX;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_long_encoded_path(mail_table_data->account_id, mail_table_data->mailbox_name, '/', &long_enc_path, &err)) {
+               EM_DEBUG_EXCEPTION(">>emcore_get_long_encoded_path  :  Failed [%d] ", err);
+               goto FINISH_OFF;
+       }
+
+       if (!long_enc_path) {
+           EM_DEBUG_EXCEPTION(">>long_enc_path  :  NULL ");
+           goto FINISH_OFF;
+       }
+
+       if (!emcore_make_rfc822_file_from_mail(mail_table_data, attachment_tbl_data, attachment_tbl_count, &envelope, &fname, NULL, &err)){
+           EM_DEBUG_EXCEPTION(" emcore_make_rfc822_file_from_mail failed [%d]", err);
+           goto FINISH_OFF;
+       }
+
+       if (fname){
+           if (!(fp = fopen(fname, "a+"))) {
+               EM_DEBUG_EXCEPTION("fopen failed - %s", fname);
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+           }
+       }
+
+       if (!fp) {
+           EM_DEBUG_EXCEPTION("fp is NULL..!");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+           goto FINISH_OFF;
+       }
+
+       rewind(fp);
+
+       /* get file length */
+       if(fseek(fp, 0, SEEK_END) != 0 || (len = ftell(fp)) == -1) {
+               EM_DEBUG_EXCEPTION("fseek or ftell failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (fname)
+               EM_DEBUG_LOG("Composed file name [%s] and file size [%d]", fname, len);
+
+       rewind(fp);
+
+       stream = NULL;
+       if (!emcore_connect_to_remote_mailbox(mail_table_data->account_id, 0, (void **)&stream, &err)){
+           EM_DEBUG_EXCEPTION("emcore_move_mail_on_server failed :  Mailbox open[%d]", err);
+           goto FINISH_OFF;
+       }
+
+       /* added for copying server UID to DB */
+       mail_parameters(stream, SET_APPENDUID, mail_appenduid);
+
+       data = (char *)malloc(len + 1);
+       /* copy data from file to data */
+       read_size = fread(data, sizeof (char), len, fp);
+       if (read_size  != len){
+           /* read faiil. */
+           EM_DEBUG_EXCEPTION("Read from file failed");
+       }
+
+       INIT(&str, mail_string, data, len);
+
+       sprintf(set_flags, "\\Seen");
+
+       if (mail_table_data->flags_seen_field){
+               if (!mail_append_full(stream, long_enc_path, set_flags, NULL, &str)) {
+                   EM_DEBUG_EXCEPTION("mail_append  failed -");
+                   err = EMAIL_ERROR_IMAP4_APPEND_FAILURE;
+                   goto FINISH_OFF;
+               }
+       }
+       else{
+               if (!mail_append_full(stream, long_enc_path, NULL, NULL, &str)) {
+                       EM_DEBUG_EXCEPTION("mail_append  failed -");
+                       err = EMAIL_ERROR_IMAP4_APPEND_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       /* Update read_mail_uid tbl */
+       if (!emcore_add_read_mail_uid(mailbox_tbl, mail_table_data->mailbox_name, mail_table_data->mail_id, g_append_uid_rsp, mail_table_data->mail_size, 0, &err)) {
+               EM_DEBUG_EXCEPTION(" emcore_add_read_mail_uid failed [%d]", err);
+               emstorage_rollback_transaction(NULL, NULL, NULL);
+               goto FINISH_OFF;
+       }
+
+
+FINISH_OFF:
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       if (ret){
+               emstorage_activity_tbl_t new_activity;
+               memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
+               new_activity.activity_type = ACTIVITY_SAVEMAIL;
+               new_activity.account_id    = account_id;
+               new_activity.mail_id       = mail_id;
+               new_activity.dest_mbox     = NULL;
+               new_activity.server_mailid = NULL;
+               new_activity.src_mbox      = NULL;
+
+               if (!emcore_delete_activity(&new_activity, &err)){
+                       EM_DEBUG_EXCEPTION(">>>>>>Local Activity [ACTIVITY_SAVEMAIL] [%d] ", err);
+               }
+       }
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+
+       EM_SAFE_FREE(data);
+       EM_SAFE_FREE(long_enc_path);
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
+       if (fp)
+               fclose(fp);
+
+       if (envelope)
+               mail_free_envelope(&envelope);
+
+       if (mail_table_data)
+               emstorage_free_mail(&mail_table_data, 1, NULL);
+
+       if (attachment_tbl_data)
+               emstorage_free_attachment(&attachment_tbl_data, attachment_tbl_count, NULL);
+
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       if (fname) {
+               remove(fname);
+               EM_SAFE_FREE(fname);
+       }
+
+       if (stream){
+               emcore_close_mailbox(0, stream);
+               stream = NULL;
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+#endif
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+static int emcore_initiate_pbd(MAILSTREAM *stream, int account_id, int mail_id, char *uid, int input_maibox_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], mail_id[%d], uid[%p], input_maibox_id[%d]", account_id, mail_id, uid, input_maibox_id);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t *account_ref = NULL;
+       emstorage_mailbox_tbl_t* mailbox = NULL;
+
+       if (account_id < FIRST_ACCOUNT_ID || mail_id < 0 || NULL == uid || 0 == input_maibox_id){
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       account_ref = emcore_get_account_reference(account_id);
+
+       email_event_partial_body_thd pbd_event;
+
+       memset(&pbd_event, 0x00, sizeof(email_event_partial_body_thd));
+
+       pbd_event.account_id = account_id;
+       if (account_ref && account_ref->incoming_server_type == EMAIL_SERVER_TYPE_POP3)
+               pbd_event.activity_type = ACTIVITY_PARTIAL_BODY_DOWNLOAD_POP3_WAIT;
+       else
+               pbd_event.activity_type = ACTIVITY_PARTIAL_BODY_DOWNLOAD_IMAP4;
+
+       if ( (err = emstorage_get_mailbox_by_id(input_maibox_id, &mailbox)) != EMAIL_ERROR_NONE || !mailbox) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       pbd_event.mailbox_id     = input_maibox_id;
+       pbd_event.mail_id        = mail_id;
+       pbd_event.server_mail_id = strtoul(uid, NULL, 0);
+       pbd_event.mailbox_name   = EM_SAFE_STRDUP(mailbox->mailbox_name);
+
+       EM_DEBUG_LOG("input_mailbox_name name [%d]", pbd_event.mailbox_id);
+       EM_DEBUG_LOG("uid [%s]", uid);
+       EM_DEBUG_LOG("pbd_event.account_id[%d], pbd_event.mail_id[%d], pbd_event.server_mail_id [%d]", pbd_event.account_id, pbd_event.mail_id , pbd_event.server_mail_id);
+
+       if (!emcore_insert_pbd_activity(&pbd_event, &pbd_event.activity_id, &err)){
+               EM_DEBUG_EXCEPTION("Inserting Partial Body Download activity failed with error[%d]", err);
+               goto FINISH_OFF;
+       }
+       else{
+               if (false == emcore_is_partial_body_thd_que_full()){
+                       /* h.gahaut :  Before inserting the event into event queue activity_type should be made 0
+                       Because partial body thread differentiates events coming from DB and event queue
+                       on the basis of activity_type and event_type fields */
+
+                       pbd_event.activity_type = 0;
+                       pbd_event.event_type = EMAIL_EVENT_BULK_PARTIAL_BODY_DOWNLOAD;
+
+                       if (!emcore_insert_partial_body_thread_event(&pbd_event, &err)){
+                               EM_DEBUG_EXCEPTION("Inserting Partial body thread event failed with error[%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       /*h.gahlaut :  Partial body thread has created a copy of event for itself so this local event should be freed here*/
+                       if (!emcore_free_partial_body_thd_event(&pbd_event, &err))
+                               EM_DEBUG_EXCEPTION("Freeing Partial body thread event failed with error[%d]", err);
+               }
+               else{
+                       EM_DEBUG_LOG(" Activity inserted only in DB .. Queue is Full");
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (mailbox) {
+               emstorage_free_mailbox(&mailbox, 1, &err);
+       }
+
+       if (account_ref) {
+               emcore_free_account(account_ref);
+               EM_SAFE_FREE(account_ref);
+       }
+
+       if (NULL  != err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+static int emcore_parse_bodystructure(void *stream, IMAPPARSEDREPLY *reply_from_server, char *bodystructure, BODY **body, struct _m_content_info **cnt_info, int *total_mail_size, unsigned long *uid_no)
+{
+       EM_DEBUG_FUNC_BEGIN("stream:[%p], reply_from_server:[%p], bodystructure:[%p]", stream, reply_from_server, bodystructure);
+
+       int err = EMAIL_ERROR_NONE;
+
+       if (!stream || !reply_from_server || !bodystructure) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       int p_total_mail_size = 0;
+       unsigned long p_uid_no = 0;
+       char *uid_string = NULL;
+       char *bodystructure_start = NULL;
+       char *bodystructure_string = NULL;
+       char *bodystructure_uid_start = NULL;
+       BODY *p_body = NULL;
+       struct _m_content_info *p_cnt_info = NULL;
+
+       /* Get the body strcuture string */
+       bodystructure_start = strstr(bodystructure, "BODYSTRUCTURE (") + strlen("BODYSTRUCTURE");
+       if (bodystructure_start == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid bodystructure");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       bodystructure_string = strdup(bodystructure_start);
+
+       /* Get the UID */
+       bodystructure_uid_start = strcasestr(bodystructure, "UID ") + strlen("UID ");
+
+       uid_string = em_malloc((bodystructure_start - bodystructure_uid_start) + 1);
+       if (uid_string == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memcpy(uid_string, bodystructure_uid_start, bodystructure_start - bodystructure_uid_start);
+
+       p_uid_no = strtoul(uid_string, NULL, 0);
+       EM_DEBUG_LOG("UID number : [%d]", p_uid_no);
+
+       /* Parse the bodystructure string */
+       p_body = mail_newbody();
+       if (p_body == NULL) {
+               EM_DEBUG_EXCEPTION("New body creationg failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       imap_parse_body_structure(stream, p_body, (unsigned char **)&bodystructure_string, reply_from_server);
+
+       /* Get the total mail size */
+       if (emcore_set_fetch_body_section(p_body, true, &p_total_mail_size, &err) < 0) {
+               EM_DEBUG_EXCEPTION("emcore_set_fetch_body_section failed:[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Fill the content_info structure */
+       if (!(p_cnt_info = em_malloc(sizeof(struct _m_content_info)))) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (emcore_get_body(stream, 0, 0, 0, p_body, p_cnt_info, &err) < 0 || !p_cnt_info) {
+               EM_DEBUG_EXCEPTION("emcore_get_body failed[%d]", err);
+               err = EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE;
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(uid_string);
+//     EM_SAFE_FREE(bodystructure_string);
+
+       if (err != EMAIL_ERROR_NONE) {
+               if (p_cnt_info)
+                       emcore_free_content_info(p_cnt_info);
+
+               if (body)
+                       mail_free_body(&p_body);
+       } else {
+               if (cnt_info)
+                       *cnt_info = p_cnt_info;
+
+               if (body)
+                       *body = p_body;
+
+               if (total_mail_size)
+                       *total_mail_size = p_total_mail_size;
+
+               if (uid_no)
+                       *uid_no = p_uid_no;
+       }
+
+       EM_DEBUG_FUNC_END("Err:[%d]", err);
+       return err;
+}
+
+static int emcore_update_attachment_except_inline(struct _m_content_info *cnt_info, int account_id, int mail_id, int mailbox_id, int *output_total_attachment_size, int *output_attachment_count)
+{
+       EM_DEBUG_FUNC_BEGIN("cnt_info : [%p], account_id : [%d], mail_id : [%d], mailbox_id : [%d]", cnt_info, account_id, mail_id, mailbox_id);
+       int err = EMAIL_ERROR_NONE;
+
+       if (!cnt_info || !account_id || !mail_id || !mailbox_id) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+
+       }
+
+       if (!cnt_info->file || !cnt_info->file->name) {
+               EM_DEBUG_LOG("Not include attachment");
+               return err;
+       }
+
+       int attachment_count = 0;
+       int total_attach_size = 0;
+       int inline_attachment_count = 0;
+       emstorage_attachment_tbl_t attachment_tbl = {0};
+       struct attachment_info *attach_info = NULL;
+
+       attachment_tbl.account_id = account_id;
+       attachment_tbl.mail_id = mail_id;
+       attachment_tbl.mailbox_id = mailbox_id;
+       attachment_tbl.attachment_save_status = 0;
+
+       for (attachment_count = 1, attach_info = cnt_info->file; attach_info; attach_info = attach_info->next, attachment_count++) {
+               if (attach_info->type == INLINE_ATTACHMENT) {
+                       EM_DEBUG_LOG("INLINE ATTACHMENT");
+                       inline_attachment_count++;
+                       continue;
+               }
+
+               total_attach_size                              += attach_info->size;
+               attachment_tbl.attachment_size                  = attach_info->size;
+               attachment_tbl.attachment_path                  = attach_info->save;
+               attachment_tbl.attachment_name                  = attach_info->name;
+               attachment_tbl.attachment_drm_type              = attach_info->drm;
+               attachment_tbl.attachment_mime_type             = attach_info->attachment_mime_type;
+#ifdef __ATTACHMENT_OPTI__
+               attachment_tbl.encoding                         = attach_info->encoding;
+               attachment_tbl.section                          = attach_info->section;
+#endif
+
+               EM_DEBUG_LOG("attachment_count [%d]", attachment_count);
+
+               if (!emstorage_add_attachment(&attachment_tbl, 0, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_add_attachment failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+
+       if (output_attachment_count)
+               *output_attachment_count = attachment_count - inline_attachment_count;
+
+       if (output_total_attachment_size)
+               *output_total_attachment_size = total_attach_size;
+
+       EM_DEBUG_FUNC_END("err : [%d]", err);
+       return err;
+}
+#define UID_RANGE_STRING_LENGTH 3000
+#define TEMP_STRING_LENGTH             50
+
+static int emcore_parse_html_part_for_partial_body(char *start_header, char *boundary_string, char *bufsendforparse, char *text_html, int body_size)
+{
+       EM_DEBUG_FUNC_BEGIN("start_header [%s], boundary_string [%s], bufsendforparse [%s], text_html [%s], body_size [%d]", start_header, boundary_string, bufsendforparse, text_html, body_size);
+
+       int   err = EMAIL_ERROR_NONE;
+       int   html_uidno = 0;
+       int   iEncodingHeader = 0;
+       int   enc_type = ENCOTHER, dec_len = 0, html_length = 0;
+       char  EncodingHeader[40] = {0};
+       char  Encoding[30] = {0};
+       char *pEncodingHeaderEnd = NULL;
+       char *txt_html = NULL;
+       char *pHeaderStart = NULL;
+       char *start = NULL, *end = NULL;
+       char *temp_enc1 = NULL;
+
+       EM_DEBUG_LOG("Content-Type : text/html or message/rfc822 or text/rfc822-headers");
+
+       pHeaderStart = start_header;
+       pHeaderStart = pHeaderStart-2;
+       do{
+               pHeaderStart--;
+       } while (*pHeaderStart != LF && bufsendforparse < pHeaderStart);
+
+       pHeaderStart++;
+
+       memcpy(EncodingHeader, pHeaderStart, 25);
+
+       if (strcasecmp(EncodingHeader, "Content-Transfer-Encoding") == 0){
+               pEncodingHeaderEnd = strstr(pHeaderStart, CRLF_STRING);
+               memcpy(Encoding, pHeaderStart + 27, pEncodingHeaderEnd - (pHeaderStart+27));
+               iEncodingHeader = 1;
+       }
+
+       /* HTML Content found */
+
+       if(!start_header) { /*prevent 27448*/
+               EM_DEBUG_EXCEPTION("start_header NULL");
+               return false;
+       }
+       txt_html = start_header;
+       txt_html = strstr(txt_html, CRLF_STRING CRLF_STRING);
+
+       if (txt_html != NULL){
+               txt_html += 4; /*  txt_html points at html content */
+               start = txt_html;
+               char multipart_boundary[100] = {0};
+               char *multipart_related_boundry = NULL;
+               char *multipart_related_boundry_end = NULL;
+               if (iEncodingHeader == 1)
+                       multipart_related_boundry = pHeaderStart;
+               else
+                       multipart_related_boundry = start_header;
+
+               multipart_related_boundry = multipart_related_boundry - 3;
+               multipart_related_boundry_end = multipart_related_boundry;
+
+               while (bufsendforparse < multipart_related_boundry && *multipart_related_boundry != LF && *multipart_related_boundry != NULL_CHAR)
+                       multipart_related_boundry -= 1;
+
+               multipart_related_boundry  += 1;
+               memcpy(multipart_boundary, multipart_related_boundry, multipart_related_boundry_end - multipart_related_boundry);
+
+               EM_DEBUG_LOG("multipart_boundary [%s], boundary_string [%s]", multipart_boundary, boundary_string);
+
+               if (strcmp(multipart_boundary, boundary_string) == 0)
+                       end = strstr(txt_html, boundary_string);
+               else
+                       end = strstr(txt_html, multipart_boundary);
+
+               memset(multipart_boundary, 0, EM_SAFE_STRLEN(multipart_boundary));
+
+               EM_DEBUG_LOG("end [%p], txt_html [%p]", end, txt_html);
+
+               if (end == NULL) {
+                       EM_DEBUG_LOG("HTML body contents exceeds limited Bytes");
+
+                       end = txt_html + body_size - (txt_html - bufsendforparse);
+                       html_uidno = 1;
+               }
+               else if(end == txt_html) { /* empty multipart */
+                       EM_DEBUG_LOG("Emtpy HTML multipart");
+                       return false;
+               }
+               else {
+                       if ((*(end-2) == CR) && (*(end-1) == LF))
+                               end -= 2;
+                       else if ((*(end-2) == CR) && (*(end-1) == LF)
+                                   && (*(end-4) == CR) && (*(end-3) == LF))
+                               end -= 4;
+                       else
+                               EM_DEBUG_EXCEPTION(" Content not per as grammar.");
+               }
+
+               EM_DEBUG_LOG("end [%p], txt_html [%p]", end, txt_html);
+
+               EM_DEBUG_LOG("iEncodingHeader [%d]", iEncodingHeader);
+
+               if (iEncodingHeader == 1){
+                       enc_type = ENCOTHER;
+                       if (strncasecmp(Encoding, "base64", strlen("base64")) == 0)
+                               enc_type = ENCBASE64;
+                       else if (strncasecmp(Encoding, "quoted-printable", strlen("quoted-printable")) == 0)
+                               enc_type = ENCQUOTEDPRINTABLE;
+
+                       EM_DEBUG_LOG("enc_type [%d]", enc_type);
+
+                       memcpy(text_html, start, end - txt_html);
+
+                       if (emcore_decode_body_text(text_html, end - txt_html, enc_type , &dec_len, &err) < 0)
+                               EM_DEBUG_EXCEPTION("emcore_decode_body_text failed [%d]", err);
+               }
+       else if ((temp_enc1 = (char *)strcasestr(start_header, "Content-transfer-encoding:")) && (temp_enc1 < end)){ /*prevent 27448*/
+                       if (temp_enc1)
+                               start_header = temp_enc1;
+
+                       start_header += strlen("Content-Transfer-Encoding:");
+                       start_header = em_skip_whitespace_without_strdup(start_header);
+
+                       if (!start_header)
+                               EM_DEBUG_EXCEPTION(" Invalid parsing ");
+                       else{
+                               enc_type = ENCOTHER;
+                               if (strncasecmp(start_header, "base64", strlen("base64")) == 0)
+                                       enc_type = ENCBASE64;
+                               else if (strncasecmp(start_header, "quoted-printable", strlen("quoted-printable")) == 0)
+                                       enc_type = ENCQUOTEDPRINTABLE;
+
+                               EM_DEBUG_LOG("enc_type [%d]", enc_type);
+
+                               memcpy(text_html, start, end - txt_html);
+
+                               if (emcore_decode_body_text(text_html, end - txt_html, enc_type , &dec_len, &err) < 0)
+                                       EM_DEBUG_EXCEPTION("emcore_decode_body_text failed [%d]", err);
+                               html_length = dec_len;
+                       }
+
+                       EM_DEBUG_LOG("Decoded length = %d", dec_len);
+                       EM_DEBUG_LOG("start - %s", start);
+               }
+               else{
+                       memcpy(text_html, start, end-txt_html);
+                       html_length = (end-txt_html);
+               }
+
+               /* EM_DEBUG_LOG(" Content-Type:  text/html [%s]\n", text_html);                                                          */
+       }
+       else
+               EM_DEBUG_EXCEPTION(" Invalid html body content ");
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+
+
+/*For the following scenario
+*------= SAMSUNG_mySingle_MIME_MULTIPART_BOUNDARY
+*Content-Transfer-Encoding :  base64
+*Content-Type :  text/plain; charset = "windows-1252"
+*MIME-Version :  1.0
+*Message-ID:  <11512468.945901271910226702.JavaMail.weblogic@epml03>
+*/
+
+#define CONTENT_TRANSFER_ENCODING "Content-Transfer-Encoding"
+
+static int emcore_parse_plain_part_for_partial_body(char *header_start_string, char *start_header, char *boundary_string, char *bufsendforparse, char *text_plain, int body_size)
+{
+       EM_DEBUG_FUNC_BEGIN("header_start_string[%s], start_header[%s], boundary_string [%s], bufsendforparse [%s], text_plain [%s]", header_start_string, start_header, boundary_string, bufsendforparse, text_plain);
+       int   err = EMAIL_ERROR_NONE, iEncodingHeader = 0, enc_type = ENCOTHER;
+       int  dec_len = 0, strcmpret = -1;
+       char *pHeaderStart = NULL, *pEncodingHeaderEnd = NULL;
+       char  EncodingHeader[40] = {0, };
+       char  Encoding[30] = {0, };
+       char *temp_text_boundary = NULL;
+       char *start = NULL, *end = NULL, *txt_plain = NULL, *temp_enc1 = NULL;
+
+       EM_DEBUG_LOG("Content-Type : text/plain");
+
+       pHeaderStart = header_start_string;
+       temp_text_boundary = start_header;
+
+       memcpy(EncodingHeader, pHeaderStart, 25);
+
+       if (strcasecmp(EncodingHeader, "Content-Transfer-Encoding") == 0){
+               pEncodingHeaderEnd = strstr(pHeaderStart, CRLF_STRING);
+               memcpy(Encoding, pHeaderStart + 27, pEncodingHeaderEnd - (pHeaderStart + 27));
+               iEncodingHeader = 1;
+       }
+
+       /*  Plain text content found  */
+       if(!start_header) { /*prevent 27450*/
+               EM_DEBUG_EXCEPTION("start_header NULL");
+               return false;
+       }
+       txt_plain = start_header;
+       txt_plain = strstr(txt_plain, CRLF_STRING CRLF_STRING);
+
+       if (txt_plain != NULL){
+               txt_plain += EM_SAFE_STRLEN(CRLF_STRING CRLF_STRING); /*  txt_plain points at plain text content  */
+
+               /* Fix is done for mail having "Content-Type: text/plain" but there is no content but having only attachment. */
+
+               strcmpret = strncmp(txt_plain, boundary_string, EM_SAFE_STRLEN(boundary_string));
+               if (strcmpret == 0){
+               }
+               else{
+                       start = txt_plain;
+                       end = strstr(txt_plain, boundary_string);
+
+                       if (end == NULL){
+                               EM_DEBUG_LOG("Text body contents exceeds limited Bytes");
+                               end = txt_plain + body_size - (txt_plain - bufsendforparse);
+                       }
+                       else{
+                               /* EM_DEBUG_LOG("pbd_event[temp_count].partial_body_complete - %d", partial_body_complete); */
+
+                               if ((*(end-2) == CR) && (*(end-1) == LF))
+                                       end -= 2;
+                               else if ((*(end-2) == CR) && (*(end-1) == LF)
+                                           && (*(end-4) == CR) && (*(end-3) == LF))
+                                       end -= 4;
+                               else
+                                       EM_DEBUG_EXCEPTION(" Content not per as grammar.");
+                       }
+
+                       if (iEncodingHeader == 1){
+                               enc_type = ENCOTHER;
+                               if (strncasecmp(Encoding, "base64", strlen("base64")) == 0)
+                                       enc_type = ENCBASE64;
+                               else if (strncasecmp(Encoding, "quoted-printable", strlen("quoted-printable")) == 0)
+                                       enc_type = ENCQUOTEDPRINTABLE;
+
+                               EM_DEBUG_LOG("enc_type [%d]", enc_type);
+
+                               memcpy(text_plain, start, end - txt_plain);
+
+                               if (emcore_decode_body_text(text_plain, end - txt_plain, enc_type , &dec_len, &err) < 0)
+                                       EM_DEBUG_EXCEPTION("emcore_decode_body_text failed [%d]", err);
+                       }
+                       else if (start_header && ((temp_enc1 = (char *)strcasestr(start_header, "Content-transfer-encoding:"))  != NULL) && !(temp_enc1 && temp_enc1 >= end)){
+                               if (temp_enc1)
+                                       start_header = temp_enc1;
+
+                               start_header += strlen("Content-Transfer-Encoding:");
+                               start_header = em_skip_whitespace_without_strdup(start_header);
+
+                               if (!start_header)
+                                       EM_DEBUG_EXCEPTION(" Invalid parsing ");
+                               else{
+                                       enc_type = ENCOTHER;
+                                       if (strncasecmp(start_header, "base64", strlen("base64")) == 0)
+                                               enc_type = ENCBASE64;
+                                       else if (strncasecmp(start_header, "quoted-printable", strlen("quoted-printable")) == 0)
+                                               enc_type = ENCQUOTEDPRINTABLE;
+
+                                       EM_DEBUG_LOG("enc_type [%d]", enc_type);
+                                       memcpy(text_plain, start, end - txt_plain);
+                                       if (emcore_decode_body_text(text_plain, end - txt_plain, enc_type , &dec_len, &err) < 0)
+                                               EM_DEBUG_EXCEPTION("emcore_decode_body_text failed [%d]", err);
+                               }
+
+                               EM_DEBUG_LOG("Decoded length = %d", dec_len);
+                               /*  EM_DEBUG_LOG("start - %s", start); */ /* print raw MIME content. */
+                       }
+                       else
+                               memcpy(text_plain, start, end-txt_plain);
+
+                       /* EM_DEBUG_LOG(" Content-type: text/plain [%s]\n", text_plain); */
+               }
+       }
+       else
+               EM_DEBUG_EXCEPTION(" Invalid text body content ");
+
+       EM_DEBUG_FUNC_END();
+       return 1;
+}
+
+
+
+/*  Content-Type:  IMAGE/octet-stream; name = Default.png */
+/*  Content-Transfer-Encoding:  BASE64 */
+/*  Content-ID:  <4b0d6810b17291f9438783a8eb9d5228@com.samsung.slp.email> */
+/*  Content-Disposition:  inline; filename = Default.png */
+
+static void emcore_free_email_image_data(email_image_data **image_data, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("image_data : [%p], count : [%d]", image_data, count);
+
+       if ((image_data == NULL) || (*image_data == NULL) || (count <= 0)) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               return;
+       }
+
+       email_image_data *p = *image_data;
+       int i = 0;
+
+       for (i = 0; i < count; i++) {
+               EM_SAFE_FREE(p[i].text_image);
+               EM_SAFE_FREE(p[i].content_id);
+               EM_SAFE_FREE(p[i].mime_type);
+       }
+
+       EM_SAFE_FREE(p);
+       *image_data = NULL;
+
+       EM_DEBUG_FUNC_END();
+}
+
+static int emcore_parse_image_part_for_partial_body(char *header_start_string, char *start_header, char *boundary_string, char *bufsendforparse, email_image_data *image_data, int body_size)
+{
+       EM_DEBUG_FUNC_BEGIN("boundary_string : [%s]", boundary_string);
+
+       int   err = EMAIL_ERROR_NONE;
+       char *multiple_image = NULL;
+       int   donot_parse_next_image = 0;
+       char *image_boundary = NULL;
+       char *image_boundary_end = NULL;
+       char *temp_image_boundary = NULL;
+       int   i = 0, ch_image = 0, cidno = 0;
+       int   enc_type = ENCOTHER, dec_len = 0, image_length = 0;
+       char *p = header_start_string;
+       char *start = NULL, *end = NULL, *txt_image = NULL;
+       char *temp_image = NULL;
+       char *temp_cid1 = NULL;
+       char *cid_end = NULL;
+       char *temp_enc1 = NULL;
+       char *p_boundary_string = NULL;
+
+       if(image_data == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       image_boundary     = start_header;
+       image_boundary_end = image_boundary - 2;
+       image_boundary     = image_boundary - 2;
+
+       EM_DEBUG_LOG("Content-type: image");
+
+       while (*image_boundary != LF)
+               image_boundary--;
+
+       image_boundary++;
+
+       temp_image_boundary = em_malloc((image_boundary_end - image_boundary) + 1);
+       if (temp_image_boundary == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               return false;
+       }
+
+       if (image_boundary  != NULL && image_boundary_end != NULL)
+               memcpy(temp_image_boundary, image_boundary, image_boundary_end-image_boundary);
+
+       if ((char *)strcasestr((const char *)temp_image_boundary, "Content-type:") == NULL)
+               p_boundary_string = strdup(temp_image_boundary);
+       else
+               p_boundary_string = EM_SAFE_STRDUP(boundary_string);
+
+       EM_SAFE_FREE(temp_image_boundary);
+
+       do {
+               if (multiple_image != NULL){
+                       p = multiple_image;
+                       start_header = multiple_image;
+               }
+
+               emcore_get_content_type_from_mime_string(start_header, &(image_data[i].mime_type));
+
+               if ((strcasestr(p, "Content-Disposition: attachment")) || (!strcasestr(p, "Content-ID: <"))){
+                       EM_DEBUG_EXCEPTION(" Body has attachment no need to parse ");
+                       end = NULL;
+                       multiple_image = NULL;
+               }
+               else {  /*  HTML Content found */
+                       ch_image = 0;
+                       cidno = 0;
+                       int   boundarylen = -1;
+                       char *cid = NULL;
+                       char *temp_name = NULL;
+                       char *decoded_filename = NULL;
+
+                       memset(image_data[i].image_file_name, 0, 100);
+
+                       if(!start_header) { /*prevent 27449*/
+                               EM_DEBUG_EXCEPTION("start_header NULL");
+                               EM_SAFE_FREE(p_boundary_string);
+                               return false;
+                       }
+
+                       txt_image  = start_header;
+                       temp_image = start_header;
+
+                       temp_name = strstr(txt_image, "name=");
+                       if (temp_name  != NULL){
+                               temp_image = temp_name;
+                               if (*(temp_image+5) == '"')
+                                       temp_image = temp_image+5;
+
+                               while (*temp_image  != CR){
+                                       temp_image++;
+                                       memcpy(image_data[i].image_file_name+ch_image, temp_image, 1);
+                                       ch_image++;
+                               }
+
+                               if ((*(temp_name+4) == '=') && (*(temp_name+5) == '\"'))
+                                       image_data[i].image_file_name[ch_image-2] = '\0';
+
+                               if ((*(temp_name+4) == '=') && (*(temp_name+5) != '\"'))
+                                       image_data[i].image_file_name[ch_image-1] = '\0';
+
+                               decoded_filename = emcore_decode_rfc2047_text(image_data[i].image_file_name, &err);
+                               if(decoded_filename) {
+                                       memset(image_data[i].image_file_name, 0, 100);
+                                       memcpy(image_data[i].image_file_name, decoded_filename, EM_SAFE_STRLEN(decoded_filename));
+                                       EM_SAFE_FREE(decoded_filename);
+                               }
+                       }
+
+                       if (((temp_cid1 = (char *)strcasestr((const char *)start_header, "Content-ID: <")) != NULL)){
+                               if (temp_cid1){
+                                       cid = temp_cid1;
+                                       temp_image = temp_cid1;
+                               }
+
+                               cid += 13;
+                               cid_end = strstr(temp_image, "\076");           /*  076 == '>' */
+
+                               image_data[i].content_id = (char *)em_malloc(cid_end-cid+5);
+                               if (image_data[i].content_id != NULL){
+                                       strcpy(image_data[i].content_id, "cid:");
+                                       memcpy(image_data[i].content_id+4, cid, cid_end-cid);
+                               }
+                               else
+                                       EM_DEBUG_EXCEPTION("em_malloc() failed");
+
+                               if (image_data[i].image_file_name[0] == '\0')
+                                       memcpy(image_data[i].image_file_name, cid, cid_end - cid);
+                       }
+
+                       txt_image = strstr(txt_image, CRLF_STRING CRLF_STRING);
+
+                       if (txt_image != NULL){
+                               txt_image += 4; /*  txt_image points at image content */
+                               start = txt_image;
+                               end = strstr(txt_image, p_boundary_string);
+
+
+                               if (end == NULL){
+                                       EM_DEBUG_LOG("HTML body contents exceeds limited Bytes");
+                                       /*  end points to end of partial body data */
+                                       end = txt_image + body_size - (txt_image-bufsendforparse);
+                               }
+                               else{
+                                       boundarylen = EM_SAFE_STRLEN(p_boundary_string);
+                                       end -= 2;
+                               }
+
+                               if ((temp_enc1 = (char *)strcasestr((const char *)start_header, "Content-transfer-encoding:"))  != NULL){ /*prevent 27449*/
+                                       if (temp_enc1)
+                                               start_header = temp_enc1;
+
+                                       start_header  += strlen("Content-Transfer-Encoding:");
+                                       start_header = em_skip_whitespace_without_strdup(start_header);
+
+                                       if (!start_header)
+                                               EM_DEBUG_EXCEPTION(" Invalid parsing ");
+                                       else{
+                                               enc_type = ENCOTHER;
+                                               if (strncasecmp(start_header, "base64", strlen("base64")) == 0)
+                                                       enc_type = ENCBASE64;
+                                               else if (strncasecmp(start_header, "quoted-printable", strlen("quoted-printable")) == 0)
+                                                       enc_type = ENCQUOTEDPRINTABLE;
+
+                                               EM_DEBUG_LOG("enc_type [%d]", enc_type);
+
+                                               image_data[i].text_image = (char *)em_malloc((end-txt_image)+1);
+                                               if (image_data[i].text_image){
+                                                       memcpy(image_data[i].text_image, start, end-txt_image);
+                                                       if (emcore_decode_body_text(image_data[i].text_image, end-txt_image, enc_type , &(image_data[i].dec_len), &err) < 0)
+                                                               EM_DEBUG_EXCEPTION("emcore_decode_body_text failed [%d]", err);
+                                                       else
+                                                               image_length = image_data[i].dec_len;
+                                               }
+                                               else
+                                                       EM_DEBUG_EXCEPTION("em_malloc() failed");
+                                       }
+
+                                       EM_DEBUG_LOG("Decoded length [%d]", dec_len);
+                               }
+                               else{
+                                       image_data[i].text_image = (char *)em_malloc(end-txt_image);
+                                       if (image_data[i].text_image)
+                                               memcpy(image_data[i].text_image, start, end - txt_image);
+                                       else
+                                               EM_DEBUG_EXCEPTION("em_malloc() failed");
+                               }
+                       }
+                       else{
+                               donot_parse_next_image = 1;
+                               EM_DEBUG_EXCEPTION(" Invalid html body content ");
+                       }
+               }
+
+               if (end != NULL) {
+                       multiple_image = (char *)strcasestr((const char *)end, "Content-type: image");
+                       i++;
+               }
+       } while (multiple_image != NULL && donot_parse_next_image != 1 && (i < IMAGE_DISPLAY_PARTIAL_BODY_COUNT));
+
+       EM_SAFE_FREE(p_boundary_string);
+       
+       EM_DEBUG_FUNC_END();
+       return 1;
+}
+
+static int emcore_find_boundary_string_of_the_part(const char *whole_string, const char *first_line_of_part, char **result_boundary_string, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("whole_string[%p], first_line_of_part[%p], result_boundary_string[%p]", whole_string, first_line_of_part, result_boundary_string);
+       int ret = false, err = EMAIL_ERROR_NONE;
+       char *boundary_cur = NULL, *boundary_end = NULL, *boundary_string = NULL;
+
+       if(!whole_string || !first_line_of_part || !result_boundary_string) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if(first_line_of_part - 2 > whole_string) {
+               boundary_cur = (char*)first_line_of_part - 2; /* 2 means CRLF. */
+               boundary_end = boundary_cur;
+
+               do{
+                       boundary_cur--;
+               } while (whole_string < boundary_cur && *boundary_cur != LF && *boundary_cur != NULL_CHAR);
+
+               boundary_cur++;
+
+               if(boundary_end > boundary_cur && boundary_cur > whole_string) {
+                       EM_DEBUG_LOG("boundary_end - boundary_cur + 15 [%d]", boundary_end - boundary_cur + 15);
+                       boundary_string = em_malloc(boundary_end - boundary_cur + 15);
+                       if(!boundary_string) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+                       memcpy(boundary_string, boundary_cur, boundary_end - boundary_cur);
+                       EM_DEBUG_LOG("boundary_string [%s]", boundary_string);
+                       *result_boundary_string = boundary_string;
+               }
+               else {
+                       EM_DEBUG_EXCEPTION("There is no string before the part");
+                       err = EMAIL_ERROR_ON_PARSING;
+                       goto FINISH_OFF;
+               }
+       }
+       else {
+               EM_DEBUG_EXCEPTION("There is no string before the part");
+               err = EMAIL_ERROR_ON_PARSING;
+               goto FINISH_OFF;
+       }
+       ret = true;
+FINISH_OFF:
+
+       if(error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END("ret[%d], err[%d]", ret, err);
+       return ret;
+}
+
+static int emcore_parse_body_for_imap(char *body_str, int body_size, struct _m_content_info *cnt_info, int encoding_type, char **output_text_plain, char **output_text_html, email_image_data **output_image_data)
+{
+       EM_DEBUG_FUNC_BEGIN("body_str:[%p], cnt_info:[%p], encoding_type:[%d]", body_str, cnt_info, encoding_type);
+       int err = EMAIL_ERROR_NONE;
+
+       if (!body_str || strlen(body_str) == 0 || !cnt_info) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       if (!output_text_plain || !output_text_html || !output_image_data) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       int dec_len = 0;
+       int no_alternative_part_flag = 0;
+       int no_html = 0;
+       char *boundary_start = NULL;
+       char *boundary_end = NULL;
+       char *boundary_string = NULL;
+       char *p_body_str = NULL;
+       char *start_header = NULL;
+       char *text_plain = NULL;
+       char *text_html = NULL;
+       email_image_data *image_data = NULL;
+
+       char *temp_alternative_plain_header = NULL;
+       char *temp_content_type = NULL;
+
+       p_body_str = EM_SAFE_STRDUP(body_str);
+
+       text_plain = em_malloc(body_size + 1);
+       text_html  = em_malloc(body_size + 1);
+
+       if (!text_plain || !text_html) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (!strcasestr(p_body_str, "Content-Type: ") && (cnt_info->text.plain || cnt_info->text.html)) {
+               /*  Encoded Content-Type: text/html or Content-Type: text/plain  */
+               /*  No Partial body has No headers with Content-Type: text/html or Content-Type: text/plain  */
+
+               EM_DEBUG_LOG("mbody->encoding [%d] ", encoding_type);
+
+               if (emcore_decode_body_text(p_body_str, EM_SAFE_STRLEN(p_body_str), encoding_type, &dec_len, &err) < 0) {
+                       EM_DEBUG_EXCEPTION("emcore_decode_body_text failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("Decoded length [%d]", dec_len);
+
+               if (dec_len > 0) {
+                       if (cnt_info->text.plain) {
+                               memcpy(text_plain, p_body_str, dec_len);
+                       }
+
+                       if (cnt_info->text.html) {
+                               memcpy(text_html, p_body_str, dec_len);
+                       }
+               }
+       } else {   /*  Partial body has headers with Content-Type: text/html or Content-Type: text/plain */
+               no_alternative_part_flag = 0;
+               if (((temp_alternative_plain_header = (char *)strcasestr(p_body_str, "Content-type: multipart/alternative")) != NULL)) {        /*  Found 'alternative' */
+                       if (((temp_content_type = (char *)strcasestr(p_body_str, "Content-type: text/plain")) != NULL)) {
+                               if (temp_content_type < temp_alternative_plain_header) {
+                                       /*  This part is text/plain not alternative. */
+                                       no_html = 1;
+                                       no_alternative_part_flag = 1;
+                               } else {
+                                       EM_DEBUG_LOG(" Content-type: multipart/alternative ");
+                                       boundary_start = strstr(temp_alternative_plain_header, "--");
+                                       if(!boundary_start) goto FINISH_OFF; /*prevent 37946 */
+                                       boundary_end = strcasestr(boundary_start, "Content-type:");
+                                       if(!boundary_end) goto FINISH_OFF; /*prevent 37946 */
+
+                                       boundary_string = em_malloc(boundary_end - (boundary_start + strlen("--")));
+                                       if (boundary_string == NULL) {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       memcpy(boundary_string, boundary_start, boundary_end - (boundary_start + strlen("--")));
+                               }
+                       }
+               } else
+                       no_alternative_part_flag = 1;
+
+               if (no_alternative_part_flag) {
+                       boundary_start = strstr(p_body_str, "--");
+                       if(!boundary_start) goto FINISH_OFF; /*prevent 37946 */
+                       boundary_end = strcasestr(boundary_start, "Content-type:");
+                       if(!boundary_end) goto FINISH_OFF; /*prevent 37946 */
+
+                       boundary_string = em_malloc(boundary_end - (boundary_start + strlen("--")));
+                       if (boundary_string == NULL) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       memcpy(boundary_string, boundary_start, boundary_end - (boundary_start + strlen("--")));
+               }
+
+               if (boundary_string && boundary_end) { /*prevent 37946 */
+                       EM_DEBUG_LOG("boundary_string : [%s]", boundary_string);
+
+                       if (((start_header = (char *)strcasestr(boundary_end, "Content-Type: text/html"))  != NULL) && (no_html  != 1) &&(((char *)strcasestr(boundary_end, "Content-Type: message/rfc822")) == NULL) &&
+                               (((char *)strcasestr(boundary_end, "Content-Type: text/rfc822-headers")) == NULL))
+                               emcore_parse_html_part_for_partial_body(start_header, boundary_string, p_body_str, text_html, body_size);
+
+                       if (((start_header = (char *)strcasestr(boundary_end, "Content-Type: text/plain"))  != NULL)) {
+                               char *internal_boundary_string = NULL;
+
+                               if(!emcore_find_boundary_string_of_the_part(p_body_str, start_header, &internal_boundary_string, &err)) {
+                                       EM_DEBUG_EXCEPTION("internal_boundary_string failed [%d]", err);
+                               }
+
+                               if(!internal_boundary_string)
+                                       internal_boundary_string = EM_SAFE_STRDUP(boundary_string);
+
+                               emcore_parse_plain_part_for_partial_body(boundary_end, start_header, internal_boundary_string, p_body_str, text_plain, body_size);
+                               EM_SAFE_FREE(internal_boundary_string);
+                       }
+
+                       if (((start_header = (char *)strcasestr((const char *)boundary_end, "Content-type: image/jpeg")) != (char *)NULL) ||
+                               ((start_header = (char *)strcasestr((const char *)boundary_end, "Content-Type: image/jpg"))  != (char *)NULL) ||
+                               ((start_header = (char *)strcasestr((const char *)boundary_end, "Content-Type: image/gif"))  != (char *)NULL) ||
+                               ((start_header = (char *)strcasestr((const char *)boundary_end, "Content-Type: image/bmp"))  != (char *)NULL) ||
+                               ((start_header = (char *)strcasestr((const char *)boundary_end, "Content-Type: image/png"))  != (char *)NULL)) {
+                               image_data = em_malloc(sizeof(email_image_data) * IMAGE_DISPLAY_PARTIAL_BODY_COUNT);
+                               if (image_data == NULL) {
+                                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                                       goto FINISH_OFF;
+                               }
+
+                               emcore_parse_image_part_for_partial_body(boundary_end, start_header, boundary_string, p_body_str, image_data, body_size);
+                       }
+               }
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(p_body_str);
+       EM_SAFE_FREE(boundary_string);
+
+       if (err != EMAIL_ERROR_NONE) {
+               EM_SAFE_FREE(text_plain);
+               EM_SAFE_FREE(text_html);
+
+               if (image_data)
+                       emcore_free_email_image_data(&image_data, IMAGE_DISPLAY_PARTIAL_BODY_COUNT);
+       } else {
+               *output_text_plain = text_plain;
+               *output_text_html = text_html;
+               *output_image_data = image_data;
+       }
+
+       EM_DEBUG_FUNC_END("err : [%d]", err);
+       return err;
+}
+
+#define TAG_LENGTH 16
+#define COMMAND_LENGTH 2000
+static int emcore_download_bulk_partial_mail_body_for_imap(MAILSTREAM *stream, int input_download_size, email_event_partial_body_thd *pbd_event, int item_count, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p], input_download_size[%d], pbd_event [%p], item_count [%d], error [%p]", stream, input_download_size, pbd_event, item_count, error);
+
+       int ret = false, err = EMAIL_ERROR_NONE;
+       int j = 0, i = 0;
+       int i32_index = 0;
+       int total_mail_size = 0, total_attachment_size = 0;
+       int temp_count = 0, attachment_num = 0;
+       unsigned long uidno = 0;
+       char buf[512] = {0, };
+       char *text_plain    = NULL;
+       char *text_html     = NULL;
+       char uid_range_string_to_be_downloaded[UID_RANGE_STRING_LENGTH] = {0, };
+       char imap_tag[TAG_LENGTH] = {0, };
+       char command[COMMAND_LENGTH] = {0, };
+       char *temp_data_html = NULL;
+       char uid_string[TEMP_STRING_LENGTH] = {0, };
+       IMAPLOCAL *imaplocal = NULL;
+       IMAPPARSEDREPLY *reply_from_server = NULL;
+       emstorage_mail_tbl_t *mail = NULL;
+       email_partial_buffer *imap_response = NULL;
+       BODY *body = NULL;
+       struct _m_content_info *cnt_info = NULL;
+       emstorage_attachment_tbl_t attachment_tbl;
+       email_event_partial_body_thd *stSectionNo = NULL;
+       email_image_data  *image_data = NULL;
+
+       if (!(stream) || !(imaplocal = stream->local) || !imaplocal->netstream || !pbd_event) {
+               EM_DEBUG_EXCEPTION("invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_FUNC_END("ret [%d]", ret);
+               return ret;
+       }
+
+       EM_DEBUG_LOG("Start of emcore_get_section_for_partial_download, item_count = %d ", item_count);
+
+       /* For constructing UID list which is having 10 UID or less at a time */
+       for (j = 0, stSectionNo = pbd_event; (stSectionNo  != NULL && j < item_count); j++)
+       {
+               EM_DEBUG_LOG("pbd_event[%d].account_id [%d], mail_id [%d], server_mail_id [%d], activity_id [%d]", \
+                       j, stSectionNo[j].account_id, stSectionNo[j].mail_id, stSectionNo[j].server_mail_id, stSectionNo[j].activity_id);
+
+               if (i32_index >= UID_RANGE_STRING_LENGTH){
+                       EM_DEBUG_EXCEPTION("String length exceeded its limitation!");
+                       goto FINISH_OFF;
+               }
+
+               if (j == item_count - 1)
+                       i32_index += SNPRINTF(uid_range_string_to_be_downloaded + i32_index, UID_RANGE_STRING_LENGTH, "%lu", stSectionNo[j].server_mail_id);
+               else
+                       i32_index += SNPRINTF(uid_range_string_to_be_downloaded + i32_index, UID_RANGE_STRING_LENGTH, "%lu,", stSectionNo[j].server_mail_id);
+       }
+
+       SNPRINTF(imap_tag, TAG_LENGTH, "%08lx", 0xffffffff & (stream->gensym++));
+       SNPRINTF(command, COMMAND_LENGTH, "%s UID FETCH %s (BODYSTRUCTURE BODY.PEEK[TEXT]<0.%d>)\015\012", imap_tag, uid_range_string_to_be_downloaded, input_download_size);
+
+       EM_DEBUG_LOG("command : %s", command);
+
+       /*  Sending out the IMAP request */
+       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command))) {
+               EM_DEBUG_EXCEPTION("net_sout failed...");
+               err = EMAIL_ERROR_CONNECTION_BROKEN;
+               goto FINISH_OFF;
+       }
+
+       /*  responce from the server */
+       imap_response = emcore_get_response_from_server(imaplocal->netstream, imap_tag, &reply_from_server, input_download_size, item_count);
+
+       if (!imap_response || !reply_from_server ){
+               EM_DEBUG_EXCEPTION(" Invalid response from emcore_get_response_from_server");
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < item_count ; i++) {
+               total_mail_size = 0;
+               total_attachment_size = 0;
+               attachment_num = 0;
+               uidno = 0;
+
+               if ((err = emcore_parse_bodystructure(stream, reply_from_server, imap_response[i].header, &body, &cnt_info, &total_mail_size, &uidno)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_parse_bodystructure failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               /* Search the account id of pbd_event */
+               for (temp_count = 0; temp_count <= item_count && pbd_event[temp_count].server_mail_id != uidno; temp_count++)
+                       continue;
+
+               if (temp_count > item_count) {
+                       EM_DEBUG_EXCEPTION("Can't find proper server_mail_id");
+                       goto FINISH_OFF;
+               }
+
+               /* Start to parse the body */
+               EM_DEBUG_LOG("Start partial body");
+
+               /* Check the body download status and body size */
+               SNPRINTF(uid_string, sizeof(uid_string), "%ld", uidno);
+               if (!emstorage_get_maildata_by_servermailid(pbd_event[temp_count].account_id, uid_string, &mail, true, &err) || !mail) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mail_data_by_servermailid failed : [%d]", err);
+                       if (err == EMAIL_ERROR_MAIL_NOT_FOUND || !mail)
+                               goto FINISH_OFF;
+               }
+
+               if (mail->body_download_status == EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED) {
+                       EM_DEBUG_LOG("Downloaded mail");
+                       continue;
+               }
+
+               /* Update the attachment info except inline attachment */
+               if ((err = emcore_update_attachment_except_inline(cnt_info, pbd_event[temp_count].account_id, mail->mail_id, pbd_event[temp_count].mailbox_id, &total_attachment_size, &attachment_num)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_update_attachment_except_inline failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("total_mail_size:[%d], total_attachment_size:[%d], attachment_num:[%d]", total_mail_size, total_attachment_size, attachment_num);
+               mail->mail_size               = total_mail_size;
+               mail->attachment_count = attachment_num;
+
+               if (imap_response[i].body_len == 0) {
+                       EM_DEBUG_LOG("BODY size is zero");
+                       continue;
+               }
+
+               if ((err = emcore_parse_body_for_imap(imap_response[i].body, imap_response[i].body_len, cnt_info, body->encoding, &text_plain, &text_html, &image_data)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_parse_body_for_imap failed");
+                       goto FINISH_OFF;
+               }
+
+               memset(buf, 0x00, sizeof(buf));
+
+               if (!emstorage_create_dir(pbd_event[temp_count].account_id, mail->mail_id, 0, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+
+               if (!emstorage_get_save_name(pbd_event[temp_count].account_id, mail->mail_id, 0, cnt_info->text.plain_charset ? cnt_info->text.plain_charset : "UTF-8", buf, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+
+               if (!emstorage_create_file(text_plain, EM_SAFE_STRLEN(text_plain), buf, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
+
+               mail->file_path_plain = EM_SAFE_STRDUP(buf);
+               EM_DEBUG_LOG("mail->file_path_plain [%s]", mail->file_path_plain);
+
+               if (image_data != NULL && image_data[0].text_image != NULL && image_data[0].text_image[0] != NULL_CHAR) {
+                       char *result_string_of_replcaing = NULL;
+                       int store_file = 0;
+                       int content_index = 0;
+
+                       temp_data_html = em_malloc(imap_response[i].body_len + 1);
+                       if(!temp_data_html) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       memset(buf, 0x00, sizeof(buf));
+                       if (text_html != NULL)
+                               memcpy(temp_data_html, text_html, EM_SAFE_STRLEN(text_html));
+                               /* EM_SAFE_STRNCPY(temp_data_html, text_html, text_html); */
+
+                       do {
+                               if (!emstorage_create_dir(pbd_event[temp_count].account_id, mail->mail_id, 0, &err))
+                                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+
+                               if (!emstorage_get_save_name(pbd_event[temp_count].account_id, mail->mail_id, 0, image_data[store_file].image_file_name, buf, &err))
+                                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+
+                               if (!emstorage_create_file(image_data[store_file].text_image, image_data[store_file].dec_len, buf, &err))
+                                       EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
+
+                               if (mail->body_download_status  != EMAIL_BODY_DOWNLOAD_STATUS_PARTIALLY_DOWNLOADED){
+                                       memset(&attachment_tbl, 0x00, sizeof(emstorage_attachment_tbl_t));
+                                       attachment_tbl.mail_id                          = mail->mail_id;
+                                       attachment_tbl.account_id                       = pbd_event[temp_count].account_id;
+                                       attachment_tbl.mailbox_id                       = pbd_event[temp_count].mailbox_id;
+                                       attachment_tbl.attachment_name                  = image_data[store_file].image_file_name;
+                                       attachment_tbl.attachment_size                  = image_data[store_file].dec_len;
+                                       attachment_tbl.attachment_path                  = buf;
+                                       attachment_tbl.attachment_save_status           = 1;
+                                       attachment_tbl.attachment_inline_content_status = 1; /*  set to 1 for inline image */
+                                       attachment_tbl.attachment_mime_type             = image_data[store_file].mime_type;
+                                       mail->attachment_count++;
+                                       mail->inline_content_count++;
+                                       if (!emstorage_add_attachment (&attachment_tbl, false, false, &err))
+                                               EM_DEBUG_EXCEPTION("emstorage_add_attachment failed - %d", err);
+                               }
+
+                               store_file++;
+                       } while (image_data[store_file].text_image  != NULL && image_data[store_file].text_image[0]  != NULL_CHAR && (store_file < IMAGE_DISPLAY_PARTIAL_BODY_COUNT));
+
+                       while (image_data[content_index].text_image  != NULL && image_data[content_index].text_image[0]  != NULL_CHAR &&
+                                 image_data[content_index].content_id && image_data[content_index].content_id[0]  != NULL_CHAR && (content_index < IMAGE_DISPLAY_PARTIAL_BODY_COUNT)){   /*  Finding CID in HTML and replacing with image name. */
+                               result_string_of_replcaing = em_replace_string((char *)temp_data_html, (char *)image_data[content_index].content_id, (char *)image_data[content_index].image_file_name);
+
+                               EM_SAFE_STRNCPY(temp_data_html, result_string_of_replcaing, EM_SAFE_STRLEN(result_string_of_replcaing));
+                               EM_SAFE_FREE(result_string_of_replcaing);
+
+                               if (strstr(temp_data_html, image_data[content_index].content_id)  != NULL)
+                                       continue; /*  Replace content id on HTML with same file name one more time. */
+
+                               content_index++;
+                       }
+
+                       memset(text_html, 0, imap_response[i].body_len + 1);
+
+                       if (temp_data_html != NULL)
+                               memcpy(text_html, temp_data_html, EM_SAFE_STRLEN(temp_data_html));
+
+                       EM_SAFE_FREE(temp_data_html);
+               }
+
+               if (EM_SAFE_STRLEN(text_html) > 0) {
+                       memset(buf, 0x00, sizeof(buf));
+                       char html_body[MAX_CHARSET_VALUE] = {0x00, };
+                       if (cnt_info->text.plain_charset != NULL){
+                               if (EM_SAFE_STRLEN(cnt_info->text.plain_charset) < MAX_CHARSET_VALUE)
+                                       memcpy(html_body, cnt_info->text.plain_charset, EM_SAFE_STRLEN(cnt_info->text.plain_charset));
+                               else
+                                       memcpy(html_body, "UTF-8", strlen("UTF-8"));
+                       }
+                       if (html_body[0]  != NULL_CHAR)
+                               strcat(html_body, HTML_EXTENSION_STRING);
+                       else
+                               memcpy(html_body, "UTF-8.htm", strlen("UTF-8.htm"));
+
+                       if (!emstorage_create_dir(pbd_event[temp_count].account_id, mail->mail_id, 0, &err))
+                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+
+                       if (!emstorage_get_save_name(pbd_event[temp_count].account_id, mail->mail_id, 0, html_body, buf, &err))
+                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+
+                       if (!emstorage_create_file(text_html, EM_SAFE_STRLEN(text_html), buf, &err))
+                               EM_DEBUG_EXCEPTION("emstorage_create_file failed [%d]", err);
+
+                       mail->file_path_html = EM_SAFE_STRDUP(buf);
+
+                       /* free the plain, html, image data */
+                       EM_SAFE_FREE(text_plain);
+                       EM_SAFE_FREE(text_html);
+                       if (image_data)
+                               emcore_free_email_image_data(&image_data, IMAGE_DISPLAY_PARTIAL_BODY_COUNT);
+
+               }
+
+               mail->body_download_status = (total_mail_size - total_attachment_size < input_download_size) ? 1 : 2;
+               EM_DEBUG_LOG("mail->body_download_status [%d]", mail->body_download_status);
+
+               /* Get preview text */
+               if ( (err = emcore_get_preview_text_from_file(mail->file_path_plain, mail->file_path_html, MAX_PREVIEW_TEXT_LENGTH, &(mail->preview_text))) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_EXCEPTION("emcore_get_preview_text_from_file() failed[%d]", err);
+
+               /* Update body contents */
+               if (!emstorage_change_mail_field(mail->mail_id, UPDATE_PARTIAL_BODY_DOWNLOAD, mail, true, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed - %d", err);
+
+               if (mail)
+                       emstorage_free_mail(&mail, 1, NULL);
+
+               if (false == emcore_delete_pbd_activity(pbd_event[temp_count].account_id, pbd_event[temp_count].mail_id, pbd_event[temp_count].activity_id, &err)){
+                       EM_DEBUG_EXCEPTION("emcore_delete_pbd_activity failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (error)
+               *error = err;
+
+       if (true != ret)
+               EM_DEBUG_EXCEPTION("Failed download for the uid list %s", command);
+
+       if(reply_from_server) {
+               EM_SAFE_FREE(reply_from_server->key);
+               EM_SAFE_FREE(reply_from_server->line);
+               EM_SAFE_FREE(reply_from_server->tag);
+               EM_SAFE_FREE(reply_from_server->text);
+               EM_SAFE_FREE(reply_from_server);
+       }
+
+       EM_SAFE_FREE(text_plain);
+       EM_SAFE_FREE(text_html);
+
+       if (image_data)
+               emcore_free_email_image_data(&image_data, IMAGE_DISPLAY_PARTIAL_BODY_COUNT);
+
+       if (cnt_info)
+               emcore_free_content_info(cnt_info);
+
+       if (body)
+               mail_free_body(&body);
+
+       if (mail)
+               emstorage_free_mail(&mail, 1, NULL);
+
+       if (imap_response)
+               emcore_free_email_partial_buffer(&imap_response, item_count);
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_download_bulk_partial_mail_body_for_pop3(MAILSTREAM *stream, int input_download_size, email_event_partial_body_thd *pbd_event, int item_count, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p], pbd_event [%p], item_count [%d], error [%p]", stream, pbd_event, item_count, error);
+       int ret = false, err = EMAIL_ERROR_NONE;
+       int i;
+
+       if (!stream || !pbd_event) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < item_count; i++) {
+               EM_DEBUG_LOG("pbd_event[%d].account_id [%d], mail_id [%d], server_mail_id [%d], activity_id [%d]", \
+                       i, pbd_event[i].account_id, pbd_event[i].mail_id, pbd_event[i].server_mail_id, pbd_event[i].activity_id);
+
+               if (!emcore_download_body_multi_sections_bulk(stream, pbd_event[i].account_id, pbd_event[i].mail_id, false, false, input_download_size, 0 , &err)){
+                       EM_DEBUG_EXCEPTION("emcore_download_body_multi_sections_bulk failed");
+                       goto FINISH_OFF;
+               }
+
+               if (false == emcore_delete_pbd_activity(pbd_event[i].account_id, pbd_event[i].mail_id, pbd_event[i].activity_id, &err)){
+                       EM_DEBUG_EXCEPTION("emcore_delete_pbd_activity failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (error)
+               *error = err;
+
+       EM_DEBUG_FUNC_END("ret [%d] err [%d]", ret, err);
+       return ret;
+}
+
+
+
+INTERNAL_FUNC int emcore_download_bulk_partial_mail_body(MAILSTREAM *stream, email_event_partial_body_thd *pbd_event, int item_count, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p], pbd_event [%p], item_count [%d], error [%p]", stream, pbd_event, item_count, error);
+       int ret = false, err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *pbd_account_tbl = NULL;
+       int auto_download_size = 0;
+
+       if (!stream || !pbd_event) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_account_by_id(pbd_event[0].account_id, EMAIL_ACC_GET_OPT_DEFAULT, &pbd_account_tbl, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       auto_download_size = (pbd_account_tbl->auto_download_size<4096)?4096:pbd_account_tbl->auto_download_size;
+
+       switch (pbd_account_tbl->incoming_server_type){
+               case EMAIL_SERVER_TYPE_IMAP4:
+                       ret = emcore_download_bulk_partial_mail_body_for_imap(stream, auto_download_size, pbd_event, item_count, &err);
+                       break;
+               case EMAIL_SERVER_TYPE_POP3:
+                       ret = emcore_download_bulk_partial_mail_body_for_pop3(stream, auto_download_size, pbd_event, item_count, &err);
+                       break;
+               default:
+                       err = EMAIL_ERROR_NOT_SUPPORTED;
+                       ret = false;
+                       break;
+       }
+
+       ret = true;
+FINISH_OFF:
+       if (error)
+               *error = err;
+
+       emstorage_free_account(&pbd_account_tbl, 1, NULL);
+
+       EM_DEBUG_FUNC_END("ret [%d] err [%d]", ret, err);
+       return ret;
+}
+
+static void emcore_free_email_partial_buffer(email_partial_buffer **partial_buffer, int item_count)
+{
+       EM_DEBUG_FUNC_BEGIN("count : [%d]", item_count);
+
+       if (item_count <= 0 || !partial_buffer || !*partial_buffer) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return;
+       }
+
+       email_partial_buffer *p = *partial_buffer;
+       int i;
+
+       for (i = 0; i < item_count ; i++, p++) {
+               EM_SAFE_FREE(p->header);
+               EM_SAFE_FREE(p->body);
+       }
+
+       EM_SAFE_FREE(*partial_buffer);
+       EM_DEBUG_FUNC_END();
+}
+
+static email_partial_buffer *emcore_get_response_from_server (NETSTREAM *nstream, char *tag, IMAPPARSEDREPLY **reply, int input_download_size, int item_count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!nstream || !tag || !reply){
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return NIL;
+       }
+
+       email_partial_buffer *retPartialBuffer = NULL;
+       IMAPPARSEDREPLY *ret_reply = NULL;
+       char *pre_content = NULL;
+       char *pline = NULL;
+       char *p = NULL;
+       int body_size = 0;
+       int header_len = 0;
+       int count = 0;
+       int ret = false;
+       int header_start = false;
+
+       retPartialBuffer = (email_partial_buffer *)em_malloc(sizeof(email_partial_buffer) * item_count);
+       if (NULL == retPartialBuffer){
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               return NIL;
+       }
+
+       while (nstream){
+               if (!(pline = net_getline(nstream))) {
+                       EM_DEBUG_EXCEPTION("net_getline failed...");
+                       goto FINISH_OFF;
+               }
+
+               /* Search the start of header */
+               if (strcasestr(pline, "BODYSTRUCTURE") != NULL) {
+                       header_len = EM_SAFE_STRLEN(pline);
+                       header_start = true;
+               }
+
+               /* Search the end of header */
+               if ((p = strcasestr(pline, "BODY[TEXT]")) != NULL && header_len > 0) {
+                       /* Get the header content */
+                       retPartialBuffer[count].header_len = (p - pline) + EM_SAFE_STRLEN(pre_content);
+                       retPartialBuffer[count].header = em_malloc(retPartialBuffer[count].header_len + 1);
+                       if (retPartialBuffer[count].header == NULL) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               goto FINISH_OFF;
+                       }
+
+                       if (pre_content != NULL)
+                               SNPRINTF(retPartialBuffer[count].header, retPartialBuffer[count].header_len, "%s%s", pre_content, pline);
+                       else
+                               SNPRINTF(retPartialBuffer[count].header, retPartialBuffer[count].header_len, "%s", pline);
+
+                       /* Get the body content */
+                       p += strlen("BODY[TEXT]<0> {");
+                       body_size = atoi(p);
+                       retPartialBuffer[count].body_len = (body_size > input_download_size) ? input_download_size : body_size ;
+                       retPartialBuffer[count].body = em_malloc(retPartialBuffer[count].body_len + 1);
+                       if (retPartialBuffer[count].body == NULL) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               goto FINISH_OFF;
+                       }
+
+                       if (net_getbuffer(nstream, retPartialBuffer[count].body_len, retPartialBuffer[count].body) <= 0) {
+                               EM_DEBUG_EXCEPTION("net_getbuffer failed");
+                               goto FINISH_OFF;
+                       }
+
+                       count++;
+                       header_start = false;
+               }
+
+               if (header_start)
+                       pre_content = EM_SAFE_STRDUP(pline);
+
+               if (0 == strncmp(pline, tag, EM_SAFE_STRLEN(tag))) {
+
+                       ret_reply = em_malloc(sizeof(IMAPPARSEDREPLY));
+                       if (!ret_reply){
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               goto FINISH_OFF;
+                       }
+
+                       if(reply)
+                               *reply = ret_reply;
+
+                       if (0 == strncmp(pline + EM_SAFE_STRLEN(tag) + 1, "OK", 2)) {
+                               ret_reply->line = (unsigned char*)EM_SAFE_STRDUP(tag);
+                               ret_reply->tag  = (unsigned char*)EM_SAFE_STRDUP(tag);
+                               ret_reply->key  = (unsigned char*)strdup("OK");
+                               ret_reply->text = (unsigned char*)strdup("Success");
+                               EM_SAFE_FREE(pline);
+                               break;
+                       }
+                       else {
+                               EM_DEBUG_EXCEPTION("Tagged Response not OK. IMAP4 Response -> [%s]", pline);
+                               ret_reply->line = (unsigned char*)EM_SAFE_STRDUP(tag);
+                               ret_reply->tag  = (unsigned char*)EM_SAFE_STRDUP(tag);
+                               ret_reply->key  = (unsigned char*)strdup("NO");
+                               ret_reply->text = (unsigned char*)strdup("Fail");
+
+                               goto FINISH_OFF;
+
+                       }
+               }
+               EM_SAFE_FREE(pline);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(pline);
+       EM_SAFE_FREE(pre_content);
+
+       if (!ret) {
+               emcore_free_email_partial_buffer(&retPartialBuffer, item_count);
+       }
+
+       EM_DEBUG_FUNC_END("retPartialBuffer [%p]", retPartialBuffer);
+       return retPartialBuffer;
+}
+
+#endif /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
+/* EOF */
diff --git a/email-core/email-core-mailbox.c b/email-core/email-core-mailbox.c
new file mode 100755 (executable)
index 0000000..afc73a7
--- /dev/null
@@ -0,0 +1,1283 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-mailbox.c
+ * Desc :  Local Mailbox Management
+ *
+ * Auth : 
+ *
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <sys/types.h>
+#include "email-types.h"
+#include "email-utilities.h"
+#include "email-convert.h"
+#include "email-debug-log.h"
+#include "email-core-global.h"
+#include "email-core-utils.h"
+#include "email-core-mailbox.h"
+#include "email-core-event.h"
+#include "email-network.h"
+#include "email-core-mail.h"
+#include "email-core-imap-mailbox.h"   
+#include "email-storage.h"
+#include "email-core-account.h" 
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+static void *g_receiving_thd_stream = NULL;                    /* Stores the recv thd stream for next time reuse */
+static int prev_acc_id_recv_thd = 0;                           /* Stores the account id for which recv thd stream is open */
+extern int recv_thread_run;
+
+static void *g_partial_body_thd_stream = NULL;         /* Stores the pb thd stream for next time reuse */
+static int prev_acc_id_pb_thd = 0;                                     /* Stores the account id for which pb thd stream is open */
+
+__thread email_connection_info_t *g_connection_info_list = NULL;
+
+static pthread_mutex_t _close_stream_lock = PTHREAD_MUTEX_INITIALIZER; /* Mutex to protect closing stream */
+#endif /*  __FEATURE_KEEP_CONNECTION__ */
+
+
+/*  Binding IMAP mailbox with its function */
+static email_mailbox_type_item_t  g_mailbox_type[MAX_MAILBOX_TYPE] = {
+                               {EMAIL_MAILBOX_TYPE_INBOX,   "INBOX" },
+                               /*  Naver */
+                               {EMAIL_MAILBOX_TYPE_INBOX,   "Inbox" },
+                               {EMAIL_MAILBOX_TYPE_SENTBOX, "Sent Messages"} , 
+                               {EMAIL_MAILBOX_TYPE_SPAMBOX, "&wqTTOLpUx3zVaA-"} , 
+                               {EMAIL_MAILBOX_TYPE_DRAFT,   "Drafts"} ,
+                               {EMAIL_MAILBOX_TYPE_TRASH,   "Deleted Messages" } ,
+                               /*  AOL */
+                               {EMAIL_MAILBOX_TYPE_SENTBOX, "Sent"} , 
+                               {EMAIL_MAILBOX_TYPE_SPAMBOX, "Spam" }, 
+                               {EMAIL_MAILBOX_TYPE_DRAFT,   "Drafts"} ,
+                               {EMAIL_MAILBOX_TYPE_TRASH,   "Trash"},
+                               /* DAUM */
+                               {EMAIL_MAILBOX_TYPE_SPAMBOX, "&wqTTONO4ycDVaA-"},
+                               /* ETC */
+                               {EMAIL_MAILBOX_TYPE_SENTBOX, "mail/sent-mail"}, 
+                               {EMAIL_MAILBOX_TYPE_SPAMBOX, "mail/spam-mail" }, 
+                               {EMAIL_MAILBOX_TYPE_DRAFT,   "mail/saved-drafts"} ,
+                               {EMAIL_MAILBOX_TYPE_TRASH,   "mail/mail-trash"},
+};
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+email_connection_info_t* emcore_get_connection_info_by_account_id(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d]", account_id);
+       email_connection_info_t *connection_info = g_connection_info_list;
+
+       while(connection_info) {
+               if(connection_info->account_id == account_id)
+                       break;
+               connection_info = connection_info->next;
+       }
+       
+       EM_DEBUG_FUNC_END("connection_info [%p]", connection_info);
+       return connection_info;
+}
+
+int emcore_append_connection_info(email_connection_info_t *new_connection_info)
+{
+       EM_DEBUG_FUNC_BEGIN("new_connection_info [%p]", new_connection_info);
+       email_connection_info_t *connection_info = g_connection_info_list;
+
+       if(!new_connection_info) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if(emcore_get_connection_info_by_account_id(new_connection_info->account_id)) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_ALREADY_EXISTS");
+               return EMAIL_ERROR_ALREADY_EXISTS;
+       }
+
+       if(connection_info) {
+               while(connection_info) {
+                       if(connection_info->next == NULL) {
+                               connection_info->next = new_connection_info;
+                               new_connection_info->next = NULL;
+                       }
+                       connection_info = connection_info->next;
+               }
+       }
+       else {
+               new_connection_info->next = NULL;
+               g_connection_info_list = new_connection_info;
+       }
+       
+       EM_DEBUG_FUNC_END("EMAIL_ERROR_NONE");
+       return EMAIL_ERROR_NONE;
+}
+
+INTERNAL_FUNC int emcore_remove_connection_info(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d]", account_id);
+       email_connection_info_t *connection_info = g_connection_info_list, *prev_connection_info = NULL;
+
+       while(connection_info) {
+               if(connection_info->account_id == account_id) {
+                       if(prev_connection_info) {
+                               prev_connection_info->next = connection_info->next;
+                       }
+                       else {
+                               g_connection_info_list = connection_info->next;
+                       }
+                       EM_SAFE_FREE(connection_info);
+                       break;
+               }
+               prev_connection_info = connection_info;
+               connection_info = connection_info->next;
+       }
+       
+       EM_DEBUG_FUNC_END("");
+       return EMAIL_ERROR_NONE;
+}
+
+#endif /* __FEATURE_KEEP_CONNECTION__ */
+
+
+/* description
+ *    get local mailbox list
+ */
+INTERNAL_FUNC int emcore_get_mailbox_list(int account_id, email_mailbox_t **mailbox_list,      int *p_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_list[%p], p_count[%p], err_code[%p]", account_id, mailbox_list, p_count, err_code);
+       
+       if (account_id <= 0 || !mailbox_list || !p_count)  {
+               EM_DEBUG_EXCEPTION("PARAM Failed account_id[%d], mailbox_list[%p], p_count[%p]", account_id, mailbox_list, p_count);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *local_mailbox_list = NULL;
+       email_account_t *ref_account = NULL;
+       int i, count = 512;
+       
+       /* get mailbox list from mailbox table */
+       
+       if (!(ref_account = emcore_get_account_reference(account_id)))  {
+               EM_DEBUG_EXCEPTION(" emcore_get_account_reference failed - %d", account_id);
+               error = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+       
+       if (!emstorage_get_mailbox_list(ref_account->account_id, EMAIL_MAILBOX_ALL, EMAIL_MAILBOX_SORT_BY_NAME_ASC, &count, &local_mailbox_list, true, &error))  {      
+               EM_DEBUG_EXCEPTION(" emstorage_get_mailbox failed - %d", error);
+       
+               goto FINISH_OFF;
+       }
+       
+       if (count > 0)  {
+               if (!(*mailbox_list = em_malloc(sizeof(email_mailbox_t) * count)))  {
+                       EM_DEBUG_EXCEPTION(" mailloc failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               
+               memset(*mailbox_list, 0x00, (sizeof(email_mailbox_t) * count));
+               
+               for (i = 0; i < count; i++)  {
+                       em_convert_mailbox_tbl_to_mailbox(local_mailbox_list + i, (*mailbox_list) + i);
+                       /*
+                       (*mailbox_list)[i].mailbox_id = local_mailbox_list[i].mailbox_id;
+                       (*mailbox_list)[i].account_id = account_id;
+                       (*mailbox_list)[i].mailbox_name = local_mailbox_list[i].mailbox_name; local_mailbox_list[i].mailbox_name = NULL;
+                       (*mailbox_list)[i].alias = local_mailbox_list[i].alias; local_mailbox_list[i].alias = NULL;
+                       (*mailbox_list)[i].local = local_mailbox_list[i].local_yn;              
+                       (*mailbox_list)[i].mailbox_type = local_mailbox_list[i].mailbox_type;   
+                       (*mailbox_list)[i].unread_count = local_mailbox_list[i].unread_count;
+                       (*mailbox_list)[i].total_mail_count_on_local = local_mailbox_list[i].total_mail_count_on_local;
+                       (*mailbox_list)[i].total_mail_count_on_server = local_mailbox_list[i].total_mail_count_on_server;
+                       (*mailbox_list)[i].mail_slot_size = local_mailbox_list[i].mail_slot_size;
+                       (*mailbox_list)[i].no_select = local_mailbox_list[i].no_select;
+                       (*mailbox_list)[i].last_sync_time = local_mailbox_list[i].last_sync_time;
+                       */
+               }
+       }
+       else
+               mailbox_list = NULL;
+
+       * p_count = count;
+
+       ret = true;
+
+FINISH_OFF: 
+       if (local_mailbox_list != NULL)
+               emstorage_free_mailbox(&local_mailbox_list, count, NULL);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+       
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+/* description
+ *    get imap sync mailbox list
+ */
+int emcore_get_mailbox_list_to_be_sync(int account_id, email_mailbox_t **mailbox_list, int *p_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_list[%p], p_count[%p], err_code[%p]", account_id, mailbox_list, p_count, err_code);
+       
+       if (account_id <= 0 || !mailbox_list || !p_count)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_list[%p], p_count[%p]", account_id, mailbox_list, p_count);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       email_mailbox_t *tmp_mailbox_list = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl_list = NULL;
+       email_account_t *ref_account = NULL;
+       int i, count = 512;
+       
+       /* get mailbox list from mailbox table */
+       if (!(ref_account = emcore_get_account_reference(account_id)))  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - %d", account_id);
+               error = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+       
+       if (!emstorage_get_mailbox_list(ref_account->account_id, 0, EMAIL_MAILBOX_SORT_BY_TYPE_ASC, &count, &mailbox_tbl_list, true, &error))  {        
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox failed - %d", error);
+       
+               goto FINISH_OFF;
+       }
+       
+       if (count > 0)  {
+               if (!(tmp_mailbox_list = em_malloc(sizeof(email_mailbox_t) * count)))  {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               
+               memset(tmp_mailbox_list, 0x00, (sizeof(email_mailbox_t) * count));
+               
+               for (i = 0; i < count; i++)  {
+                       em_convert_mailbox_tbl_to_mailbox(mailbox_tbl_list + i, tmp_mailbox_list + i);
+                       /*
+                       tmp_mailbox_list[i].mailbox_id = mailbox_tbl_list[i].mailbox_id;
+                       tmp_mailbox_list[i].account_id = account_id;
+                       tmp_mailbox_list[i].mailbox_name = mailbox_tbl_list[i].mailbox_name; mailbox_tbl_list[i].mailbox_name = NULL;
+                       tmp_mailbox_list[i].mailbox_type = mailbox_tbl_list[i].mailbox_type; 
+                       tmp_mailbox_list[i].alias = mailbox_tbl_list[i].alias; mailbox_tbl_list[i].alias = NULL;
+                       tmp_mailbox_list[i].local = mailbox_tbl_list[i].local_yn;
+                       tmp_mailbox_list[i].unread_count = mailbox_tbl_list[i].unread_count;
+                       tmp_mailbox_list[i].total_mail_count_on_local = mailbox_tbl_list[i].total_mail_count_on_local;
+                       tmp_mailbox_list[i].total_mail_count_on_server = mailbox_tbl_list[i].total_mail_count_on_server;
+                       tmp_mailbox_list[i].mail_slot_size = mailbox_tbl_list[i].mail_slot_size;
+                       */
+               }
+       }
+       else
+               tmp_mailbox_list = NULL;
+       *p_count = count;
+       ret = true;
+       
+FINISH_OFF: 
+       
+       *mailbox_list = tmp_mailbox_list;
+       
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+       
+       if (mailbox_tbl_list != NULL)
+               emstorage_free_mailbox(&mailbox_tbl_list, count, NULL);
+       
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_get_mail_count(email_mailbox_t *mailbox, int *total, int *unseen, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox[%p], total[%p], unseen[%p], err_code[%p]", mailbox, total, unseen, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (!mailbox)  {
+               EM_DEBUG_EXCEPTION(" mailbox[%p], total[%p], unseen[%p]", mailbox, total, unseen);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       if (!emstorage_get_mail_count(mailbox->account_id, mailbox->mailbox_name, total, unseen, true, &err))  {
+               EM_DEBUG_EXCEPTION(" emstorage_get_mail_count failed - %d", err);
+
+               goto FINISH_OFF;
+       }
+
+       
+       ret = true;
+       
+FINISH_OFF: 
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_create_mailbox(email_mailbox_t *new_mailbox, int on_server, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("new_mailbox[%p], err_code[%p]", new_mailbox, err_code);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t local_mailbox;
+       
+       if (new_mailbox == NULL || new_mailbox->mailbox_name == NULL)  {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if  (on_server) {
+               /* Create a mailbox from Sever */
+               if (!emcore_create_imap_mailbox(new_mailbox, &err)) {
+                       EM_DEBUG_EXCEPTION(">>>>> mailbox Creation in Server FAILED >>> ");
+                       goto FINISH_OFF;
+               }
+               else
+                       EM_DEBUG_LOG(">>>>> mailbox Creation in Server SUCCESS >>> ");  
+       }
+
+       memset(&local_mailbox, 0x00, sizeof(emstorage_mailbox_tbl_t));
+       EM_DEBUG_LOG("box name[%s] local yn[%d] mailbox_type[%d]", new_mailbox->mailbox_name, local_mailbox.local_yn, new_mailbox->mailbox_type);
+
+       /* add local mailbox into local mailbox table */
+       local_mailbox.mailbox_id = new_mailbox->mailbox_id;
+       local_mailbox.account_id = new_mailbox->account_id;
+       local_mailbox.local_yn = new_mailbox->local;
+       local_mailbox.mailbox_name = new_mailbox->mailbox_name;
+       local_mailbox.alias = new_mailbox->alias;
+       local_mailbox.mailbox_type = new_mailbox->mailbox_type;
+       local_mailbox.unread_count = 0;
+       local_mailbox.total_mail_count_on_local = 0;
+       local_mailbox.total_mail_count_on_server = 0;
+       emcore_get_default_mail_slot_count(local_mailbox.account_id, &local_mailbox.mail_slot_size);
+
+       if (strncmp(new_mailbox->mailbox_name, EMAIL_INBOX_NAME, EM_SAFE_STRLEN(EMAIL_INBOX_NAME))    == 0 || 
+               strncmp(new_mailbox->mailbox_name, EMAIL_DRAFTBOX_NAME, EM_SAFE_STRLEN(EMAIL_DRAFTBOX_NAME)) == 0 ||
+               strncmp(new_mailbox->mailbox_name, EMAIL_OUTBOX_NAME, EM_SAFE_STRLEN(EMAIL_OUTBOX_NAME)) == 0 || 
+               strncmp(new_mailbox->mailbox_name, EMAIL_SENTBOX_NAME, EM_SAFE_STRLEN(EMAIL_SENTBOX_NAME))  == 0)
+               local_mailbox.modifiable_yn = 0;                        /*  can be deleted/modified */
+       else
+               local_mailbox.modifiable_yn = 1;
+
+
+       if (!emstorage_add_mailbox(&local_mailbox, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_add_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       new_mailbox->mailbox_id = local_mailbox.mailbox_id;
+       ret = true;
+       
+FINISH_OFF: 
+       if (err_code)
+               *err_code = err;
+       
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_delete_mailbox(int input_mailbox_id, int on_server, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], err_code[%p]", input_mailbox_id, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+       
+       if (input_mailbox_id == 0)  {
+               EM_DEBUG_EXCEPTION(" input_mailbox_id == 0");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE || !mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (on_server) {
+               EM_DEBUG_LOG("Delete the mailbox in Sever >>> ");
+               if  (!emcore_delete_imap_mailbox(input_mailbox_id, &err))
+                       EM_DEBUG_EXCEPTION("Delete the mailbox in server : failed [%d]", err);
+               else
+                       EM_DEBUG_LOG("Delete the mailbox in server : success");
+       }
+
+       if (!emcore_delete_all_mails_of_mailbox(mailbox_tbl->account_id, input_mailbox_id, false, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_delete_all_mails_of_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_delete_mailbox(mailbox_tbl->account_id, -1, input_mailbox_id, true, &err))  {
+               EM_DEBUG_EXCEPTION(" emstorage_delete_mailbox failed - %d", err);
+
+               goto FINISH_OFF;
+       }
+       
+       ret = true;
+       
+FINISH_OFF:
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emcore_delete_mailbox_ex(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, int input_on_server)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_mailbox_id_array[%p] input_mailbox_id_count[%d] input_on_server[%d]", input_mailbox_id_array, input_mailbox_id_array, input_mailbox_id_count, input_on_server);
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+
+       if(input_account_id == 0 || input_mailbox_id_count <= 0 || input_mailbox_id_array == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if((err = emstorage_set_field_of_mailbox_with_integer_value(input_account_id, input_mailbox_id_array, input_mailbox_id_count, "deleted_flag", 1, true)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_set_field_of_mailbox_with_integer_value failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < input_mailbox_id_count; i++) {
+               if(!emcore_delete_mailbox(input_mailbox_id_array[i] , input_on_server, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_delete_mailbox failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_delete_mailbox_all(email_mailbox_t *mailbox, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN(" mailbox[%p], err_code[%p]", mailbox, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (mailbox == NULL) {
+               EM_DEBUG_EXCEPTION(" mailbox[%p]", mailbox);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       if (!emcore_delete_all_mails_of_mailbox(mailbox->account_id, mailbox->mailbox_id, 0, /*NULL, */ &err)) {
+               EM_DEBUG_EXCEPTION(" emcore_delete_all_mails_of_mailbox failed - %d", err);
+               
+               goto FINISH_OFF;
+       }
+       
+       if (!emstorage_delete_mailbox(mailbox->account_id, -1, mailbox->mailbox_id, true, &err)) {
+               EM_DEBUG_EXCEPTION(" emstorage_delete_mailbox failed - %d", err);
+               
+
+               goto FINISH_OFF;
+       }
+       
+       ret = true;
+       
+FINISH_OFF: 
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_update_mailbox(email_mailbox_t *old_mailbox, email_mailbox_t *new_mailbox, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("old_mailbox[%p], new_mailbox[%p], err_code[%p]", old_mailbox, new_mailbox, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (old_mailbox == NULL || new_mailbox == NULL)  {
+               EM_DEBUG_EXCEPTION("old_mailbox[%p], new_mailbox[%p]", old_mailbox, new_mailbox);
+               
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       emstorage_mailbox_tbl_t new_mailbox_tbl;
+       memset(&new_mailbox_tbl, 0x00, sizeof(emstorage_mailbox_tbl_t));
+       
+       /*  Support only updating mailbox_type */
+       new_mailbox_tbl.mailbox_type = new_mailbox->mailbox_type;
+
+       if (old_mailbox->mailbox_type != new_mailbox_tbl.mailbox_type) {
+               if (!emstorage_update_mailbox_type(old_mailbox->account_id, -1, old_mailbox->mailbox_name, new_mailbox_tbl.mailbox_type, true, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_update_mailbox failed - %d", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       new_mailbox_tbl.mailbox_id                      = old_mailbox->mailbox_id;
+       new_mailbox_tbl.account_id                      = old_mailbox->account_id;
+       new_mailbox_tbl.mailbox_name            = new_mailbox->mailbox_name;
+       new_mailbox_tbl.mailbox_type            = new_mailbox->mailbox_type;
+       new_mailbox_tbl.alias                           = new_mailbox->alias;
+       new_mailbox_tbl.mail_slot_size          = new_mailbox->mail_slot_size;
+       new_mailbox_tbl.total_mail_count_on_server = new_mailbox->total_mail_count_on_server;
+       
+       if (!emstorage_update_mailbox(old_mailbox->account_id, -1, old_mailbox->mailbox_id, &new_mailbox_tbl, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_update_mailbox failed - %d", err);
+
+               goto FINISH_OFF;
+       }
+       
+       if (EM_SAFE_STRCMP(old_mailbox->mailbox_name, new_mailbox_tbl.mailbox_name) != 0) {
+               if ( (err = emstorage_rename_mailbox(old_mailbox->mailbox_id, new_mailbox_tbl.mailbox_name, new_mailbox_tbl.alias, true)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emstorage_rename_mailbox failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       
+       ret = true;
+       
+FINISH_OFF: 
+       if (err_code)
+               *err_code = err;
+       
+       return ret;
+}
+
+extern int try_auth;
+extern int try_auth_smtp;
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+extern long smtp_send(SENDSTREAM *stream, char *command, char *args);
+#endif /* __FEATURE_KEEP_CONNECTION__ */
+
+INTERNAL_FUNC int emcore_connect_to_remote_mailbox_with_account_info(email_account_t *account, int input_mailbox_id, void **result_stream, int *err_code)
+{
+       EM_PROFILE_BEGIN(emCoreMailboxOpen);
+       EM_DEBUG_FUNC_BEGIN("account[%p], input_mailbox_id[%d], mail_stream[%p], err_code[%p]", account, input_mailbox_id, result_stream, err_code);
+       
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       email_session_t *session = NULL;
+       char *mbox_path = NULL;
+       void *reusable_stream = NULL;
+       int is_connection_for = _SERVICE_THREAD_TYPE_NONE;
+       emstorage_mailbox_tbl_t* mailbox = NULL;
+       char *mailbox_name = NULL;
+
+       if (account == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter.");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       if (!emcore_get_current_session(&session)) {
+               EM_DEBUG_EXCEPTION("emcore_get_current_session failed...");
+               error = EMAIL_ERROR_SESSION_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (input_mailbox_id == 0 || input_mailbox_id != EMAIL_CONNECT_FOR_SENDING)
+               is_connection_for = _SERVICE_THREAD_TYPE_RECEIVING;
+       else 
+               is_connection_for = _SERVICE_THREAD_TYPE_SENDING;
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+       email_connection_info_t *connection_info = emcore_get_connection_info_by_account_id(account->account_id);
+
+       if(connection_info) {
+               if (is_connection_for == _SERVICE_THREAD_TYPE_RECEIVING) {
+                       if(connection_info->receiving_server_stream_status == EMAIL_STREAM_STATUS_CONNECTED)
+                               reusable_stream = connection_info->receiving_server_stream;
+               }
+               else {
+                       if(connection_info->sending_server_stream_status == EMAIL_STREAM_STATUS_CONNECTED)
+                               reusable_stream = connection_info->sending_server_stream;
+               }
+       }
+       
+       if (reusable_stream != NULL)
+               EM_DEBUG_LOG("Stream reuse desired");
+#else
+       reusable_stream = *result_stream;
+#endif
+
+       session->error = EMAIL_ERROR_NONE;
+       emcore_set_network_error(EMAIL_ERROR_NONE);             /*  set current network error as EMAIL_ERROR_NONE before network operation */
+       
+       if (input_mailbox_id == EMAIL_CONNECT_FOR_SENDING) {
+               mailbox_name = EM_SAFE_STRDUP(ENCODED_PATH_SMTP);
+       }
+       else if (input_mailbox_id == 0) {
+               mailbox_name = NULL;
+       }else {
+               if ( (error = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox)) != EMAIL_ERROR_NONE || !mailbox) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+               mailbox_name = EM_SAFE_STRDUP(mailbox->mailbox_name);
+       }
+
+       if (is_connection_for == _SERVICE_THREAD_TYPE_RECEIVING) {      
+               /*  open pop3/imap server */
+               MAILSTREAM *mail_stream = NULL;
+               
+               if (!emcore_get_long_encoded_path_with_account_info(account, mailbox_name, '/', &mbox_path, &error)) {
+                       EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path failed - %d", error);
+                       session->error = error;
+                       goto FINISH_OFF;
+               }
+               
+               EM_DEBUG_LOG("open mail connection to mbox_path [%s]", mbox_path);
+               
+               try_auth = 0;           /*  ref_account->receiving_auth ? 1  :  0  */
+               session->auth = 0; /*  ref_account->receiving_auth ? 1  :  0 */
+               
+               if (!(mail_stream = mail_open(reusable_stream, mbox_path, IMAP_2004_LOG))) {    
+                       EM_DEBUG_EXCEPTION("mail_open failed. session->error[%d], session->network[%d]", session->error, session->network);
+                       
+                       if ((session->error == EMAIL_ERROR_UNKNOWN) || (session->error == EMAIL_ERROR_NONE))
+                               session->error = EMAIL_ERROR_CONNECTION_FAILURE;
+                       
+                       error = session->error;
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+                       /* Since mail_open failed Reset the global stream pointer as it is a dangling pointer now */
+#endif /*  __FEATURE_KEEP_CONNECTION__ */
+                       goto FINISH_OFF;
+               }
+               *result_stream = mail_stream;
+       }
+       else {  
+               /*  open smtp server */
+               SENDSTREAM *send_stream = NULL;
+               char *host_list[2] = {NULL, NULL};
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+               if (reusable_stream != NULL) {
+                       int send_ret = 0;
+                       /* Check whether connection is avaiable */
+                       send_stream     = reusable_stream;
+                       /*
+                       send_ret = smtp_send(send_stream, "RSET", 0);
+                       
+                       if (send_ret != SMTP_RESPONSE_OK) {
+                               EM_DEBUG_EXCEPTION("[SMTP] RSET --> [%s]", send_stream->reply);
+                               send_stream = NULL;
+                       }
+                       */
+               }
+#endif
+               if(!send_stream) {
+                       if (!emcore_get_long_encoded_path_with_account_info(account, mailbox_name, 0, &mbox_path, &error)) {
+                               EM_DEBUG_EXCEPTION(" emcore_get_long_encoded_path failed - %d", error);
+                               session->error = error;
+                               goto FINISH_OFF;
+                       }
+                               
+                       EM_DEBUG_LOG("open SMTP connection to mbox_path [%s]", mbox_path);
+                       
+                       try_auth_smtp = account->outgoing_server_need_authentication ? 1  :  0;
+                       session->auth = account->outgoing_server_need_authentication ? 1  :  0;
+                       
+                       host_list[0] = mbox_path;
+                       
+                       if (!(send_stream = smtp_open(host_list, 1))) {
+                               EM_DEBUG_EXCEPTION("smtp_open failed... : current outgoing_server_secure_connection[%d] session->error[%d] session->network[%d]",
+                                       account->outgoing_server_secure_connection, session->error, session->network);
+                               if (session->network != EMAIL_ERROR_NONE)
+                                       session->error = session->network;
+                               if ((session->error == EMAIL_ERROR_UNKNOWN) || (session->error == EMAIL_ERROR_NONE))
+                                       session->error = EMAIL_ERROR_CONNECTION_FAILURE;
+                               
+                               error = session->error;
+                               goto FINISH_OFF;
+                       }
+               }
+               *result_stream = send_stream;
+       }
+       
+       ret = true;
+       
+FINISH_OFF: 
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+       if (ret == true) {
+               if(!connection_info) {
+                       connection_info = em_malloc(sizeof(email_connection_info_t));
+                       connection_info->account_id = account->account_id;
+                       if(!connection_info) 
+                               EM_DEBUG_EXCEPTION("em_malloc for connection_info failed.");
+                       else
+                               emcore_append_connection_info(connection_info);
+               }
+
+               if(connection_info) {
+                       /* connection_info->account_id = account->account_id; */
+                       if (is_connection_for == _SERVICE_THREAD_TYPE_RECEIVING) {
+                               connection_info->receiving_server_stream      = *result_stream;
+                               connection_info->receiving_server_stream_status = EMAIL_STREAM_STATUS_CONNECTED;
+                       }
+                       else {
+                               connection_info->sending_server_stream        = *result_stream;
+                               connection_info->sending_server_stream_status = EMAIL_STREAM_STATUS_CONNECTED;
+                       }
+               }
+       }
+#endif
+
+       EM_SAFE_FREE(mbox_path);
+
+       EM_SAFE_FREE(mailbox_name);
+
+       if (mailbox) {
+               emstorage_free_mailbox(&mailbox, 1, NULL);
+       }
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_PROFILE_END(emCoreMailboxOpen);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);     
+       return ret;
+}
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+
+/*h.gahlaut@samsung.com :  20-oct-2010*/
+/*Precaution :  When Reuse Stream feature is enabled then stream should only be closed using emcore_close_mailbox from email-service code.
+mail_close should not be used directly from anywhere in code.
+emcore_close_mailbox uses mail_close inside it.
+
+mail_close is only used in emcore_connect_to_remote_mailbox and emcore_reset_streams as an exception to above rule*/
+
+INTERNAL_FUNC int emcore_connect_to_remote_mailbox(int account_id, char *mailbox, void **mail_stream, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox[%p], mail_stream[%p], err_code[%p]", account_id, mailbox, mail_stream, err_code);
+       
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       email_account_t *ref_account = NULL;
+
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (!ref_account) {             
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - account id[%d]", account_id);
+               error = EMAIL_ERROR_INVALID_ACCOUNT;            
+               goto FINISH_OFF;
+       }
+       
+       ret = emcore_connect_to_remote_mailbox_with_account_info(ref_account, mailbox, mail_stream, &error);
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = error;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC void emcore_close_mailbox_receiving_stream()
+{
+       EM_DEBUG_FUNC_BEGIN("recv_thread_run [%d]", recv_thread_run);
+       if (!recv_thread_run) {
+               ENTER_CRITICAL_SECTION(_close_stream_lock);
+               mail_close(g_receiving_thd_stream);
+               g_receiving_thd_stream = NULL;
+               prev_acc_id_recv_thd = 0;
+               LEAVE_CRITICAL_SECTION(_close_stream_lock);
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC void emcore_close_mailbox_partial_body_stream()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (false == emcore_get_pbd_thd_state()) {
+               EM_DEBUG_LOG("emcore_get_pbd_thd_state returned false");
+               mail_close(g_partial_body_thd_stream);
+               g_partial_body_thd_stream = NULL;
+               prev_acc_id_pb_thd = 0;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+/* h.gahlaut@samsung.com :  21-10-2010 - 
+emcore_reset_stream() function is used to reset globally stored partial body thread and receiving thread streams 
+on account deletion and pdp deactivation */
+
+INTERNAL_FUNC void emcore_reset_streams()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       emcore_close_mailbox_receiving_stream();
+       emcore_close_mailbox_partial_body_stream();
+       
+       EM_DEBUG_FUNC_END();
+       return;
+}
+
+#else /*  __FEATURE_KEEP_CONNECTION__ */
+
+INTERNAL_FUNC int emcore_connect_to_remote_mailbox(int account_id, int input_mailbox_id, void **mail_stream, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], input_mailbox_id[%d], mail_stream[%p], err_code[%p]", account_id, input_mailbox_id, mail_stream, err_code);
+       
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       email_session_t *session = NULL;
+       email_account_t *ref_account = NULL;
+
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (!ref_account)  {            
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed - account id[%d]", account_id);
+               error = EMAIL_ERROR_INVALID_ACCOUNT;            
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_check_thread_status()) {
+               error = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       if (!emnetwork_check_network_status(&error)) {
+               EM_DEBUG_EXCEPTION("emnetwork_check_network_status failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_empty_session(&session)) {
+               EM_DEBUG_EXCEPTION("emcore_get_empty_session failed...");
+               error = EMAIL_ERROR_SESSION_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       ret = emcore_connect_to_remote_mailbox_with_account_info(ref_account, input_mailbox_id, mail_stream, &error);
+
+FINISH_OFF: 
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       emcore_clear_session(session);
+       
+       if (err_code)
+               *err_code = error;
+       
+       return ret;
+}
+#endif  /*  __FEATURE_KEEP_CONNECTION__ */
+
+INTERNAL_FUNC int emcore_close_mailbox(int account_id, void *mail_stream)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_stream[%p]", account_id, mail_stream);
+       
+       if (!mail_stream)  {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               return false;
+       }
+       
+#ifdef __FEATURE_KEEP_CONNECTION__
+       thread_t thread_id = THREAD_SELF();
+
+       if (thread_id == (thread_t)emcore_get_receiving_thd_id()) {
+               /*  Receiving thread - Dont' Free Reuse feature enabled  */
+       }
+       else if (thread_id == (thread_t)emcore_get_partial_body_thd_id()) {
+               /*  Partial Body Download thread - Dont' Free Reuse feature enabled  */
+       }
+       else {
+               /*  Some other thread so free stream */
+               if (g_receiving_thd_stream != mail_stream && g_partial_body_thd_stream != mail_stream)
+                       mail_close((MAILSTREAM *)mail_stream);
+       }
+#else
+       mail_close((MAILSTREAM *)mail_stream);
+#endif /*  __FEATURE_KEEP_CONNECTION__ */
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+INTERNAL_FUNC void emcore_free_mailbox_list(email_mailbox_t **mailbox_list, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_list[%p], count[%d]", mailbox_list, count);
+       
+       if (count <= 0 || !mailbox_list || !*mailbox_list)  {
+               EM_DEBUG_EXCEPTION("INVALID_PARAM: mailbox_list[%p], count[%d]", mailbox_list, count);
+               return;
+       }
+               
+       email_mailbox_t *p = *mailbox_list;
+       int i;
+               
+       for (i = 0; i < count; i++)
+               emcore_free_mailbox(p+i);
+
+       EM_SAFE_FREE(p);
+       *mailbox_list = NULL;
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+INTERNAL_FUNC void emcore_free_mailbox(email_mailbox_t *mailbox)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!mailbox)  {
+               EM_DEBUG_EXCEPTION("INVALID_PARAM");
+               return;
+       }
+       
+       EM_SAFE_FREE(mailbox->mailbox_name);
+       EM_SAFE_FREE(mailbox->alias);
+       
+       EM_DEBUG_FUNC_END();
+}
+
+
+INTERNAL_FUNC int emcore_free_internal_mailbox(email_internal_mailbox_t **mailbox_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_list[%p], count[%d], err_code[%p]", mailbox_list, count, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (count > 0)  {
+               if (!mailbox_list || !*mailbox_list)  {
+                       EM_DEBUG_EXCEPTION(" mailbox_list[%p], count[%d]", mailbox_list, count);
+
+                       err = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               email_internal_mailbox_t *p = *mailbox_list;
+               int i;
+
+               /* EM_DEBUG_LOG("before loop"); */
+               for (i = 0; i < count; i++)  {
+                       EM_SAFE_FREE(p[i].mailbox_name);
+                       EM_SAFE_FREE(p[i].alias);
+               }
+               /* EM_DEBUG_LOG("p [%p]", p); */
+               free(p);
+               *mailbox_list = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC void emcore_bind_mailbox_type(email_internal_mailbox_t *mailbox_list)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_list[%p]", mailbox_list);
+
+       int i = 0;
+       int bIsNotUserMailbox = false;
+       email_mailbox_type_item_t   *pMailboxType1 = NULL ;
+       
+       for (i = 0 ; i < MAX_MAILBOX_TYPE ; i++) {
+               pMailboxType1 = g_mailbox_type + i;
+               if (0 == EM_SAFE_STRCMP(pMailboxType1->mailbox_name, mailbox_list->mailbox_name)) { /*prevent 24662*/
+                       mailbox_list->mailbox_type = pMailboxType1->mailbox_type;
+                       EM_DEBUG_LOG("mailbox_list->mailbox_type[%d]", mailbox_list->mailbox_type);
+                       bIsNotUserMailbox = true;
+                       break;
+               }
+       }
+
+       if (false == bIsNotUserMailbox)
+               mailbox_list->mailbox_type = EMAIL_MAILBOX_TYPE_USER_DEFINED;
+
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC int  emcore_send_mail_event(email_mailbox_t *mailbox, int mail_id , int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int handle; 
+       email_event_t event_data;
+
+       if (!mailbox || mailbox->account_id <= 0) {
+               EM_DEBUG_LOG(" mailbox[%p]", mailbox);
+               
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       event_data.type = EMAIL_EVENT_SEND_MAIL;
+       event_data.account_id = mailbox->account_id;
+       event_data.event_param_data_4 = mail_id;
+       event_data.event_param_data_1 = NULL;
+       event_data.event_param_data_5 = mailbox->mailbox_id;
+                       
+       if (!emcore_insert_event_for_sending_mails(&event_data, &handle, &err))  {
+               EM_DEBUG_LOG(" emcore_insert_event failed - %d", err);
+               goto FINISH_OFF;
+       }
+       emcore_add_transaction_info(mail_id , handle , &err);
+
+       ret = true;
+FINISH_OFF: 
+       if (err_code)
+               *err_code = err;
+       
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_partial_body_thd_local_activity_sync(int *is_event_inserted, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int activity_count = 0;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (false == emstorage_get_pbd_activity_count(&activity_count, false, &error)) {
+               EM_DEBUG_LOG("emstorage_get_pbd_activity_count failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       if (activity_count > 0) {
+
+               email_event_partial_body_thd pbd_event;
+
+               /* Carefully initialise the event */ 
+               memset(&pbd_event, 0x00, sizeof(email_event_partial_body_thd));
+
+               pbd_event.event_type = EMAIL_EVENT_LOCAL_ACTIVITY_SYNC_BULK_PBD;
+               pbd_event.activity_type = EMAIL_EVENT_LOCAL_ACTIVITY_SYNC_BULK_PBD;
+
+               if (false == emcore_insert_partial_body_thread_event(&pbd_event, &error)) {
+                       EM_DEBUG_LOG(" emcore_insert_partial_body_thread_event failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+               else {
+                       /*Not checking for NULL here because is_event_inserted is never NULL. */
+                       *is_event_inserted = true;
+               }
+               
+       }
+       else {
+               *is_event_inserted = false;     
+       }
+
+       ret = true;
+       
+       FINISH_OFF: 
+
+       if (NULL != err_code) {
+               *err_code = error;
+       }
+
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_get_mailbox_by_type(int account_id, email_mailbox_type_e mailbox_type, email_mailbox_t *result_mailbox, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], result_mailbox [%p], err_code [%p]", account_id, result_mailbox, err_code);
+       int ret = false, err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *mail_box_tbl_spam = NULL;
+
+       if (result_mailbox == NULL)     {       
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_mailbox_by_mailbox_type(account_id, mailbox_type, &mail_box_tbl_spam, false, &err)) {
+
+               EM_DEBUG_LOG("emstorage_get_mailbox_by_mailbox_type failed - %d", err);
+       }
+       else {  
+               if (mail_box_tbl_spam) {
+                       result_mailbox->mailbox_type = mail_box_tbl_spam->mailbox_type;
+                       result_mailbox->mailbox_name = EM_SAFE_STRDUP(mail_box_tbl_spam->mailbox_name);
+                       result_mailbox->account_id = mail_box_tbl_spam->account_id;
+                       result_mailbox->mail_slot_size = mail_box_tbl_spam->mail_slot_size;
+                       if (!emstorage_free_mailbox(&mail_box_tbl_spam, 1, &err))
+                               EM_DEBUG_EXCEPTION(" emstorage_free_mailbox Failed [%d]", err);
+                       ret = true;     
+               }
+       }
+
+FINISH_OFF: 
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+INTERNAL_FUNC int emcore_local_activity_sync(int account_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       EM_DEBUG_LOG(">> account_id [%d], err_code [%p] ", account_id, err_code);
+       
+       int *activity_id_list = NULL;
+       int activity_count = 0;
+       int err         = 0;
+       int handle = 0;
+       int ret = false;
+       email_event_t event_data;
+
+
+       memset(&event_data, 0x00, sizeof(email_event_t));
+       
+
+       EM_IF_NULL_RETURN_VALUE(err_code, false);
+
+       if (account_id <= 0) {
+               EM_DEBUG_EXCEPTION(" Invalid Account ID [%d] ", account_id);
+               return false;
+       }
+               EM_DEBUG_LOG(">>> emdaemon_sync_local_activity 3 ");
+
+       if (!emstorage_get_activity_id_list(account_id, &activity_id_list, &activity_count, ACTIVITY_DELETEMAIL, ACTIVITY_COPYMAIL, true,  &err)) {
+                       EM_DEBUG_LOG(">>> emdaemon_sync_local_activity 4 ");
+               EM_DEBUG_EXCEPTION(" emstorage_get_activity_id_list failed [ %d] ", err);
+               goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG(">>> emdaemon_sync_local_activity 5 ");
+
+       if (activity_count > 0) {
+               event_data.type = EMAIL_EVENT_LOCAL_ACTIVITY;
+               event_data.account_id  = account_id;
+               if (!emcore_insert_event(&event_data, &handle, &err))  {
+                       EM_DEBUG_LOG(" emcore_insert_event failed - %d", err);
+                       goto FINISH_OFF;
+               }
+               
+               ret = true;
+       }
+
+       FINISH_OFF: 
+               
+       if (activity_id_list)
+               emstorage_free_activity_id_list(activity_id_list, &err); 
+       
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+
+}
+
+INTERNAL_FUNC int emcore_save_local_activity_sync(int account_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       EM_DEBUG_LOG(">> account_id [%d], err_code [%p] ", account_id, err_code);
+       
+       emstorage_activity_tbl_t *local_activity = NULL;
+       int *activity_id_list = NULL;
+       int activity_count = 0;
+       int err         = 0;
+       int ret = false;
+       int handle = 0;
+       email_event_t event_data;
+
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       EM_IF_NULL_RETURN_VALUE(err_code, false);
+
+       if (account_id <= 0) {
+               EM_DEBUG_EXCEPTION(" Invalid Account ID [%d] ", account_id);
+               return false;
+       }
+               EM_DEBUG_LOG(">>> emdaemon_sync_local_activity 3 ");
+
+       if (!emstorage_get_activity_id_list(account_id, &activity_id_list, &activity_count, ACTIVITY_SAVEMAIL, ACTIVITY_DELETEMAIL_SEND, true,  &err)) {
+               EM_DEBUG_EXCEPTION(" emstorage_get_activity_id_list [ %d] ", err);
+               goto FINISH_OFF;
+       }
+
+       
+       if (activity_count > 0) {
+               event_data.type = EMAIL_EVENT_LOCAL_ACTIVITY;
+               event_data.account_id  = account_id;
+               if (!emcore_insert_event_for_sending_mails(&event_data, &handle, &err))  {
+                       EM_DEBUG_LOG(" emcore_insert_event failed - %d", err);
+                       goto FINISH_OFF;
+               }       
+               
+               ret = true;
+       }
+
+
+       FINISH_OFF: 
+
+       if (local_activity)
+               emstorage_free_local_activity(&local_activity, activity_count, NULL); 
+
+       if (activity_id_list)
+               emstorage_free_activity_id_list(activity_id_list, &err);        
+
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+
+}
+
+#endif
+
diff --git a/email-core/email-core-mime.c b/email-core/email-core-mime.c
new file mode 100755 (executable)
index 0000000..5d73272
--- /dev/null
@@ -0,0 +1,5653 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+
+/* ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ***
+ *File :  email-core-mime.c
+ *Desc :  MIME Operation
+ *
+ *Auth :
+ *
+ *History :
+ *   2011.04.14  :  created
+ ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ***/
+#undef close
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <vconf.h>
+#include <ctype.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include "email-internal-types.h"
+#include "lnx_inc.h"
+#include "email-utilities.h"
+#include "email-core-global.h"
+#include "email-core-utils.h"
+#include "email-core-mail.h"
+#include "email-core-mime.h"
+#include "email-storage.h"
+#include "email-core-event.h"
+#include "email-core-account.h"
+#include "email-core-signal.h"
+#include "email-debug-log.h"
+
+#define MIME_MESG_IS_SOCKET
+
+#define MIME_LINE_LEN  1024
+#define BOUNDARY_LEN   256
+
+#define TYPE_TEXT            1
+#define TYPE_IMAGE           2
+#define TYPE_AUDIO           3
+#define TYPE_VIDEO           4
+#define TYPE_APPLICATION     5
+#define TYPE_MULTIPART       6
+#define TYPE_MESSAGE         7
+#define TYPE_UNKNOWN         8
+
+#define TEXT_STR             "TEXT"
+#define IMAGE_STR            "IMAGE"
+#define AUDIO_STR            "AUDIO"
+#define VIDEO_STR            "VIDEO"
+#define APPLICATION_STR      "APPLICATION"
+#define MULTIPART_STR        "MULTIPART"
+#define MESSAGE_STR          "MESSAGE"
+
+#define CONTENT_TYPE         1
+#define CONTENT_SUBTYPE      2
+#define CONTENT_ENCODING     3
+#define CONTENT_CHARSET      4
+#define CONTENT_DISPOSITION  5
+#define CONTENT_NAME         6
+#define CONTENT_FILENAME     7
+#define CONTENT_BOUNDARY     8
+#define CONTENT_REPORT_TYPE  9
+#define CONTENT_ID           10
+#define CONTENT_LOCATION     11
+
+#define GRAB_TYPE_TEXT       1 /*  retrieve text and attachment name */
+#define GRAB_TYPE_ATTACHMENT 2 /*  retrieve only attachmen */
+
+#define SAVE_TYPE_SIZE       1 /*  only get content siz */
+#define SAVE_TYPE_BUFFER     2 /*  save content to buffe */
+#define SAVE_TYPE_FILE       3 /*  save content to temporary fil */
+
+#define EML_FOLDER           20 /*  save eml content to temporary folder */
+
+/*
+       MIME Structure Example
+
+       (part 0)        multipart/mixed
+       (part 1)                multipart/alternative
+       (part 1.1)                      text/plain              <- text message
+       (part 1.2)                      text/html               <- html message
+       (part 2)                text/plain                      <- text attachment
+
+
+       (part 0)        multipart/related
+       (part 1)                multipart/alternative
+       (part 1.1)                      text/plain                      <- text message
+       (part 1.2)                      text/html                       <- html message
+       (part 2)                image/png                               <- inline image
+       (part 2)                image/png                               <- inline image
+
+
+       (part 0)        multipart/mixed
+       (part 1.1)              multipart/related
+       (part 2.1)                      multipart/alternative
+       (part 3.1)                              text/plain(body)  <- text message
+       (part 3.2)                              text/html(body) <- html message
+       (part 2.2)                      image/png(related)      <- inline image
+       (part 1.2)              image/png(attachment)   <- image attachment
+*/
+
+/*  Text and Attachment Holde */
+/* struct _m_content_info  */
+/*     int grab_type;  */              /*  1 :  text and attachment list */
+                                               /*  2 :  attachmen */
+/*     int file_no; */                 /*  attachment sequence to be downloaded (min : 1 */
+/*     struct text_data  */
+/*             char *plain;    */      /*  body plain tex */
+/*             char *plain_charset */ /*  charset of plai */
+/*             char *html; */ /*  body html tex */
+/*     } text */
+
+/*     struct attachment_info  */
+/*             int   type;     */              /*  1 : inline 2 : attachmen */
+/*             char *name;     */              /*  attachment filenam */
+/*             int   size;             */      /*  attachment siz */
+/*             char *save;     */              /*  content saving filenam */
+/*             struct attachment_info *next */
+/*     } *file */
+/* } */
+
+/* --------------------- MIME Structure --------------------------------- */
+/*  MIME Header Parameter (Content-Type, Content-Disposition, ... */
+struct _parameter {
+       char                            *name;                  /*  parameter name */
+       char                            *value;                 /*  parameter valu */
+       struct _parameter       *next;                  /*  next paramete */
+};
+
+/*  Content-Dispositio */
+struct _disposition {
+       char                            *type;                  /*  "inline" "attachment */
+       struct _parameter       *parameter;             /*  "filename", .. */
+};
+
+/*  RFC822 Heade */
+struct _rfc822header {
+       char                            *return_path;   /*  error return pat */
+       char                            *received;
+       char                            *date;
+       char                            *from;
+       char                            *subject;
+       char                            *sender;
+       char                            *to;
+       char                            *cc;
+       char                            *bcc;
+       char                            *reply_to;
+       char                            *priority;
+       char                            *ms_priority;
+       char                            *dsp_noti_to;
+       char                            *others;
+};
+
+/*  MIME Part Header */
+struct _m_part_header {
+       char                            *type;                  /*  text, image, audio, video, application, multipart, message */
+       char                            *subtype;               /*  plain, html, jpeg, .. */
+       char                            *encoding;              /*  encoding typ */
+       struct _parameter       *parameter;             /*  content-type parameter  :  "boundary" "charset" .. */
+       char                            *desc;                  /*  descriptio */
+       char                            *disp_type;             /*  disposition type  :  "inline" "attachment", */
+       struct _parameter       *disp_parameter;    /*  disposition parameter  :  "filename", .. */
+       char                            *content_id;    /*  content id  :  it is inline  */
+       char                            *content_location;      /*  content location  :  "inline" location  */
+};
+
+/*  MIME Message Header */
+struct _m_mesg_header {
+       char                            *version;               /*  MIME Versio */
+       struct _m_part_header  *part_header;    /*  MIME Part Heade */
+};
+
+/*  MIME Multipart Body linked list */
+typedef struct _m_body _m_body_t;
+struct _m_part{
+       _m_body_t                       *body;                  /*  part bod */
+       struct _m_part          *next;                  /*  the next found par */
+};
+
+/*  MIME Multipart Body */
+struct _m_body {
+       struct _m_part_header *part_header;     /*  MIME Part Heade */
+       struct _m_part                  nested;                 /*  nested structure if contain multipar */
+       char                            *text;                  /*  text if not contain multipar */
+       int                                             size;                   /*  text size if not contain multipar */
+       char                            *holdingfile;
+};
+
+/*  MIME Message */
+struct _m_mesg {
+       struct _rfc822header  *rfc822header;    /*  RFC822 Heade */
+       struct _m_mesg_header *header;                  /*  MIME Message Heade */
+       struct _m_part          nested;                 /*  nested structure if contain multipar */
+       char                            *text;                  /*  text if not contain multipar */
+       int                                             size;                   /*  text size if not contain multipar */
+};
+/* ---------------------------------------------------------------------- */
+/*  Global variable */
+static bool next_decode_string = false;
+static int  eml_data_count = 0;
+
+/* ---------------------------------------------------------------------- */
+/*  External variable */
+extern int _pop3_receiving_mail_id;
+extern int _pop3_received_body_size;
+extern int _pop3_last_notified_body_size;
+extern int _pop3_total_body_size;
+
+extern int _imap4_received_body_size;
+extern int _imap4_last_notified_body_size;
+extern int _imap4_total_body_size;
+extern int _imap4_download_noti_interval_value;
+
+extern int multi_part_body_size;
+extern bool only_body_download;
+
+extern BODY **g_inline_list;
+extern int g_inline_count;
+
+/* ---------------------------------------------------------------------- */
+/*  Function Declaration */
+
+/*  parsing the first header (RFC822 Header and Message Header and Etc... */
+static int emcore_mime_parse_header(void *stream, int is_file, struct _rfc822header **rfcheader, struct _m_mesg_header **header, int *err_code);
+
+/*  parsing the first bod */
+static int emcore_mime_parse_body(void *stream, int is_file, struct _m_mesg *mmsg, struct _m_content_info *cnt_info, void *callback, int *err_code);
+
+/*  parsing the message part header (CONTENT-... header */
+static int emcore_mime_parse_part_header(void *stream, int is_file, struct _m_part_header **header, int *err_code);
+
+/*  parsing the message part by boundar */
+static int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *parent_header, struct _m_part *nested, struct _m_content_info *cnt_info, int *end_of_parsing, int *err_code);
+
+/*  set RFC822 Header valu */
+static int emcore_mime_set_rfc822_header_value(struct _rfc822header **rfc822header, char *name, char *value, int *err_code);
+
+/*  set Message Part Header (Content-... Header */
+static int emcore_mime_set_part_header_value(struct _m_part_header **header, char *name, char *value, int *err_code);
+
+static int emcore_mime_get_param_from_str(char *str, struct _parameter **param, int *err_code);
+
+static int emcore_mime_add_param_to_list(struct _parameter **param_list, struct _parameter *param, int *err_code);
+
+char *emcore_mime_get_header_value(struct _m_part_header *header, int type, int *err_code);
+
+void emcore_mime_free_param(struct _parameter *param);
+void emcore_mime_free_part_header(struct _m_part_header *header);
+void emcore_mime_free_message_header(struct _m_mesg_header *header);
+void emcore_mime_free_rfc822_header(struct _rfc822header *rfc822header);
+void emcore_mime_free_part(struct _m_part *part);
+void emcore_mime_free_part_body(struct _m_body *body);
+void emcore_mime_free_mime(struct _m_mesg *mmsg);
+char *emcore_mime_get_line_from_sock(void *stream, char *buf, int size, int *err_code);
+char *emcore_mime_get_save_file_name(int *err_code);
+
+/*  get content data and save buffer or fil */
+/*  mode - 1 :  get the only siz */
+/*         2 :  save content to buffer (holder is buffer */
+/*         3 :  save content to file (holder is file name */
+static int emcore_mime_get_content_data(void *stream,
+                                       int  is_file,
+                       int   is_text,
+                                       char *boundary_str,
+                                       char *content_encoding,
+                                       int *end_of_parsing,
+                                       int   mode,
+                                       char **holder,
+                                       int *size,
+                                       void *callback,
+                                       int *err_code);
+
+int emcore_decode_body_text_from_sock(void *stream, char *boundary_str, int encoding, int mode, int is_text, int fd, char **holder, int *end_of_parsing, int *size);
+int emcore_decode_body_text_from_file(FILE *stream, char *boundary_str, int encoding, int mode, int is_text, int fd, char **holder, int *end_of_parsing, int *size);
+/*  skip content data to boundary_str or end of fil */
+int emcore_mime_skip_content_data(void *stream,
+                                                       int is_file,
+                                                       char *boundary_str,
+                                                       int *end_of_parsing,
+                                                       int *size,
+                                                       void *callback,
+                                                       int *err_code);
+
+static int emcore_get_file_pointer(BODY *body, bool input_check_duplicated_file_name, char *buf, struct _m_content_info *cnt_info , int *err);
+static PARTLIST *emcore_get_body_full(MAILSTREAM *stream, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST *section_list);
+static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int account_id, int mail_id, PARTLIST *section_list, struct _m_content_info *cnt_info, int *err_code, int event_handle);
+static PARTLIST *emcore_add_node(PARTLIST *section_list, BODY *body);
+static void emcore_free_section_list(PARTLIST *section_list);
+static int emcore_get_section_body_size(char *response, char *section, int *body_size);
+static void parse_file_path_to_filename(char *src_string, char **out_string);
+extern long pop3_reply (MAILSTREAM *stream);
+/* ------------------------------------------------------------------------------------------------- */
+
+
+/* Fix for issue junk characters in mail body */
+char *em_split_file_path(char *str)
+{
+       EM_DEBUG_FUNC_BEGIN("str [%s]", str);
+
+       EM_IF_NULL_RETURN_VALUE(str, NULL);
+
+       char *buf = NULL;
+       char delims[] = "@";
+       char *result = NULL;
+       char *temp_str = NULL;
+       char *content_id = NULL;
+       int buf_length = 0;
+       char *temp_cid_data = NULL;
+       char *temp_cid = NULL;
+       temp_str = EM_SAFE_STRDUP(str);
+       buf_length = EM_SAFE_STRLEN(str) + 1024;
+       buf = em_malloc(buf_length);
+       content_id = temp_str;
+       temp_cid = strstr(temp_str, "\"");
+
+       if (temp_cid == NULL) {
+               EM_DEBUG_EXCEPTION(">>>> File Path Doesnot contain end line for CID ");
+               next_decode_string = true;
+               EM_SAFE_FREE(buf);
+               return temp_str;
+       }
+       temp_cid_data = em_malloc((temp_cid-temp_str)+1);
+       memcpy(temp_cid_data, temp_str, (temp_cid-temp_str));
+
+       if (!strstr(temp_cid_data, delims)) {
+               EM_DEBUG_EXCEPTION(">>>> File Path Doesnot contain @ ");
+               next_decode_string = true;
+               EM_SAFE_FREE(buf);
+               EM_SAFE_FREE(temp_cid_data);
+               return temp_str;
+       }
+       else            {
+               result = strstr(temp_str, delims);
+               if (result != NULL) {
+                       next_decode_string = false;
+                       *result = '\0';
+                       result++;
+                       EM_DEBUG_LOG("content_id is [ %s ]", content_id);
+
+                       if (strcasestr(content_id, ".bmp") || strcasestr(content_id, ".jpeg") || strcasestr(content_id, ".png") ||
+                                       strcasestr(content_id, ".jpg") || strcasestr(content_id, ".gif"))
+                               snprintf(buf+EM_SAFE_STRLEN(buf), buf_length - EM_SAFE_STRLEN(buf), "%s\"", content_id);
+                       else
+                               snprintf(buf+EM_SAFE_STRLEN(buf), buf_length - EM_SAFE_STRLEN(buf), "%s%s", content_id, ".jpeg\"");
+               }
+               else {
+                       EM_DEBUG_EXCEPTION(">>>> File Path Doesnot contain end line for CID ");
+                       next_decode_string = true;
+                       EM_SAFE_FREE(buf);
+                       EM_SAFE_FREE(temp_cid_data);
+                       return temp_str;
+               }
+               result = strstr(result, "\"");
+               if (result != NULL) {
+                       result++;
+                       snprintf(buf+EM_SAFE_STRLEN(buf), buf_length - EM_SAFE_STRLEN(buf), "%s", result);
+               }
+       }
+       EM_SAFE_FREE(temp_str);
+       EM_SAFE_FREE(temp_cid_data);
+       return buf;
+}
+
+
+static char *em_replace_string_with_split_file_path(char *source_string, char *old_string, char *new_string)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       char *buffer = NULL;
+       char *split_str = NULL;
+       char *p = NULL;
+       char *q = NULL;
+       int   buf_len = 0;
+
+       EM_IF_NULL_RETURN_VALUE(source_string, NULL);
+       EM_IF_NULL_RETURN_VALUE(old_string, NULL);
+       EM_IF_NULL_RETURN_VALUE(new_string, NULL);
+
+       EM_DEBUG_LOG("source_string [%s] ", source_string);
+       EM_DEBUG_LOG("old_string    [%s] ", old_string);
+       EM_DEBUG_LOG("new_string    [%s] ", new_string);
+
+       p = strstr(source_string, old_string);
+
+       if (!p) {
+               EM_DEBUG_EXCEPTION("Orig not found in source_string");
+               return NULL;
+       }
+
+       buf_len = EM_SAFE_STRLEN(source_string) + 1024;
+       buffer = (char *)em_malloc(buf_len);
+
+       if(p - source_string < EM_SAFE_STRLEN(source_string) + 1024 + 1) {
+               strncpy(buffer, source_string, p - source_string);
+
+               EM_DEBUG_LOG("BUFFER [%s]", buffer);
+
+               split_str = em_split_file_path(p);
+
+               if (!split_str) {
+                       EM_DEBUG_EXCEPTION(">> SPLIT STRING IS NULL  ");
+                       goto FINISH_OFF;
+               }
+
+               q = strstr(split_str, old_string);
+               if (q) {
+                       EM_DEBUG_LOG("Split string [%s]", split_str);
+                       snprintf(buffer + EM_SAFE_STRLEN(buffer), buf_len - EM_SAFE_STRLEN(buffer), "%s%s", new_string, q+strlen(old_string)); /*prevent 34353*/
+                       EM_DEBUG_LOG("BUFFER 1 [%s]", buffer);
+                       EM_SAFE_FREE(split_str);
+                       EM_DEBUG_FUNC_END("Suceeded");
+                       return buffer;
+               }
+       }
+       else  {
+               EM_DEBUG_EXCEPTION("Buffer is too small.");
+               EM_SAFE_FREE(buffer);
+               return NULL;
+       }
+
+FINISH_OFF:
+       EM_SAFE_FREE(split_str);
+       EM_SAFE_FREE(buffer);
+
+       EM_DEBUG_FUNC_END("Failed");
+       return NULL;
+
+}
+
+
+int emcore_mime_flush_receiving_buffer(void *stream, int is_file, char *boundary_string, char *boundary_end_string,  int *end_of_parsing, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], boundary_string[%s], boundary_end_string[%s], end_of_parsing[%p],  err_code[%p]", stream, is_file, boundary_string, boundary_end_string, end_of_parsing, err_code);
+       int err = EMAIL_ERROR_NONE;
+       int local_end_of_parsing = 0;
+       char buf[MIME_LINE_LEN] = {0, };
+
+       if (!stream) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       while (TRUE)  {
+               if (!emcore_check_thread_status()) {
+                       EM_DEBUG_FUNC_END("EMAIL_ERROR_CANCELLED");
+                       if (err_code)
+                               *err_code = EMAIL_ERROR_CANCELLED;
+                       return false;
+               }
+
+               if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, &err)) ||
+                       (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, &err))) {
+                       if (err != EMAIL_ERROR_NO_MORE_DATA) {
+                               EM_DEBUG_EXCEPTION("file : [%d], emcore_mime_get_line_from_sock or emcore_mime_get_line_from_file failed", is_file);
+                               local_end_of_parsing = 0;
+                               break;
+                       }
+       
+                       local_end_of_parsing = 1;
+                       break;
+               }
+
+               if (boundary_string && boundary_end_string) {
+                       if (!strcmp(buf, boundary_string))  {
+                               EM_DEBUG_LOG("found boundary");
+                               local_end_of_parsing = 0;
+                               break;
+                       }
+                       else if (!strcmp(buf, boundary_end_string))  {
+                               EM_DEBUG_LOG("found boundary_end");
+                               local_end_of_parsing = 1;
+                               break;
+                       }
+               }
+       }
+
+       if (end_of_parsing)
+               *end_of_parsing = local_end_of_parsing;
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_parse_mime(void *stream, int is_file, struct _m_content_info *cnt_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], cnt_info[%p], err_code[%p]", stream, is_file, cnt_info, err_code);
+
+       struct _m_mesg *mmsg = em_malloc(sizeof(struct _m_mesg));
+
+       if (!mmsg) return false;
+
+       memset(mmsg, 0x00, sizeof(struct _m_mesg));
+
+       /*  1. parse the first found header */
+       EM_DEBUG_LOG(">>>>>> 1. parse the first found header");
+       if (!emcore_mime_parse_header(stream, is_file, &mmsg->rfc822header, &mmsg->header, err_code)) {
+               EM_SAFE_FREE(mmsg);
+               return false;
+       }
+
+       if (!emcore_check_thread_status())  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_CANCELLED;
+               emcore_mime_free_mime(mmsg);
+               return false;
+       }
+
+       /*  2. parse body */
+       EM_DEBUG_LOG(">>>>>> 2. parse body");
+       if (mmsg && mmsg->header && mmsg->header->part_header && mmsg->header->part_header->parameter)  {
+               EM_DEBUG_LOG("name[%s]", mmsg->header->part_header->parameter->name);
+               EM_DEBUG_LOG("value[%s]", mmsg->header->part_header->parameter->value);
+               EM_DEBUG_LOG("next  :  %p", mmsg->header->part_header->parameter->next);
+       }
+
+       if (!emcore_mime_parse_body(stream, is_file, mmsg, cnt_info, NULL, err_code)) {
+               EM_SAFE_FREE(mmsg);
+               return false;
+       }
+
+       /*  3. free memory */
+       EM_DEBUG_LOG(">>>>>> 3. free memory");
+       if (mmsg && mmsg->header && mmsg->header->part_header && mmsg->header->part_header->parameter)  {
+               EM_DEBUG_LOG("name[%s]", mmsg->header->part_header->parameter->name);
+               EM_DEBUG_LOG("value[%s]", mmsg->header->part_header->parameter->value);
+               EM_DEBUG_LOG("next  :  %p", mmsg->header->part_header->parameter->next);
+       }
+       emcore_mime_free_mime(mmsg);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_mime_parse_header(void *stream, int is_file, struct _rfc822header **rfc822header, struct _m_mesg_header **header, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], rfc822header[%p], header[%p], err_code[%p]", stream, is_file, rfc822header, header, err_code);
+
+       struct _m_mesg_header *tmp_header = NULL;
+       struct _rfc822header *tmp_rfc822header = NULL;
+       char buf[MIME_LINE_LEN] = {0, };
+       char *name = NULL;
+       char *value = NULL;
+       char *pTemp = NULL;
+       int  is_longheader;
+
+       if (!emcore_check_thread_status())  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_CANCELLED;
+                       return false;
+               }
+
+
+       if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, err_code)) ||
+               (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, err_code)))  {
+               return false;
+       }
+
+       if (!(tmp_header = em_malloc(sizeof(struct _m_mesg_header))))  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               return false;
+       }
+
+       if (!emcore_check_thread_status())  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_CANCELLED;
+                       return false;
+               }
+
+       while (TRUE)  {
+               EM_DEBUG_LOG("buf[%s]", buf);
+
+               if (!strncmp(buf, CRLF_STRING, 2))
+                       break;
+
+               is_longheader = (buf[0] == ' ' || buf[0] == '\t') ? TRUE  :  FALSE;
+
+
+               if (!is_longheader)  { /*  Normal header (format :  "Name :  Value" or "Name :  Value; Parameters" */
+                       if (name)  {
+                               EM_SAFE_FREE(name);
+                       }
+
+                       /* EM_DEBUG_FUNC_BEGIN() */
+                       if ((pTemp = strtok(buf, ":")) == NULL)
+                               break;
+
+                       name = EM_SAFE_STRDUP(pTemp);
+
+                       value = strtok(NULL, CRLF_STRING);
+
+                       em_upper_string(name);
+               }
+               else  { /*  Long header */
+                       value = strtok(buf, CRLF_STRING);
+                       em_trim_left(value);
+               }
+
+               /* --> 2007-05-08 by cy */
+               if (!name)
+                       break;
+
+               EM_DEBUG_LOG("> name[%s]", name);
+               EM_DEBUG_LOG("> value[%s]", value);
+
+               /*  MIME Part Heade */
+               if (memcmp(name, "CONTENT-", 8) == 0 && value)  {
+                       EM_DEBUG_LINE;
+                       emcore_mime_set_part_header_value(&tmp_header->part_header, name, value, err_code);
+
+                       if (tmp_header->part_header && tmp_header->part_header->parameter)      {
+                               EM_DEBUG_LOG("name[%s]", tmp_header->part_header->parameter->name);
+                               EM_DEBUG_LOG("value[%s]", tmp_header->part_header->parameter->value);
+                               EM_DEBUG_LOG("next  :  %p", tmp_header->part_header->parameter->next);
+                       }
+
+                       /*  MIME Version Heade */
+               }
+               else if (memcmp(name, "MIME-VERSION", 12) == 0)  {
+                       /* EM_DEBUG_FUNC_BEGIN() */
+                       /*  ignored because we need only contents information */
+                       /*  tmp_header->version = EM_SAFE_STRDUP(value) */
+
+                       /*  RFC822 Heade */
+               }
+               else  {
+                       /*  in socket stream case, ignored because we need only contents information */
+                       if (is_file == 1)
+                               emcore_mime_set_rfc822_header_value(&tmp_rfc822header, name, value, err_code);
+               }
+
+               if (!emcore_check_thread_status())  {
+                       if (err_code != NULL)
+                               *err_code = EMAIL_ERROR_CANCELLED;
+                       return false;
+               }
+
+               if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, err_code)) ||
+                       (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, err_code)))  {
+
+                       if (tmp_rfc822header)
+                               emcore_mime_free_rfc822_header(tmp_rfc822header);
+
+
+                       if (tmp_header)  {
+                               emcore_mime_free_part_header(tmp_header->part_header);
+
+                               EM_SAFE_FREE(tmp_header->version);
+                               EM_SAFE_FREE(tmp_header);
+                       }
+                       return false;
+               }
+       }
+
+       *header = tmp_header;
+       *rfc822header = tmp_rfc822header;
+
+       EM_SAFE_FREE(name);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_mime_parse_part_header(void *stream, int is_file, struct _m_part_header **header, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], header[%p], err_code[%p]", stream, is_file, header, err_code);
+
+       struct _m_part_header *tmp_header = NULL;
+       char buf[MIME_LINE_LEN] = {0x00};
+       char *name = NULL;
+       char *value = NULL;
+       char *p = NULL;
+       int is_longheader = false;
+
+       if (!emcore_check_thread_status())  {
+                       if (err_code != NULL)
+                               *err_code = EMAIL_ERROR_CANCELLED;
+                       return false;
+       }
+
+       if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, err_code)) ||
+       (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, err_code)))
+               return false;
+
+       tmp_header = em_malloc(sizeof(struct _m_part_header));
+
+       if (!tmp_header)  {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               return false;
+       }
+
+       memset(tmp_header, 0, sizeof(struct _m_part_header));
+
+       while (true)  {
+               if (!strncmp(buf, CRLF_STRING, EM_SAFE_STRLEN(CRLF_STRING))) break;
+
+               is_longheader = (buf[0] == ' ' || buf[0] == TAB);
+
+               if (!is_longheader)  {   /*  Normal header (format :  "Name :  Value" or "Name :  Value; Parameters" */
+                       EM_SAFE_FREE(name);
+                       p = strtok(buf , ":");
+
+                       if (p)  {
+                               name = EM_SAFE_STRDUP(p);
+                               value = strtok(NULL, CRLF_STRING);
+                               em_upper_string(name);
+                       }
+               }
+               else            /*  Long header */
+                       value = strtok(buf, CRLF_STRING);
+
+               if (!name)
+                       break;
+
+               emcore_mime_set_part_header_value(&tmp_header, name, value, err_code);
+
+               if (!emcore_check_thread_status())  {
+                       if (err_code != NULL)
+                               *err_code = EMAIL_ERROR_CANCELLED;
+                       return false;
+               }
+
+               if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, err_code)) ||
+               (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, err_code)))  {
+                       EM_SAFE_FREE(name);
+                       EM_SAFE_FREE(tmp_header);
+
+                       return false;
+               }
+       }
+
+       *header = tmp_header;
+
+       EM_SAFE_FREE(name);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+
+int emcore_mime_parse_body(void *stream, int is_file, struct _m_mesg *mmsg, struct _m_content_info *cnt_info,  void *callback, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], mmsg[%p], cnt_info[%p], callback[%p], err_code[%p]", stream, is_file, mmsg, cnt_info, callback, err_code);
+
+       if (!mmsg->header) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       } 
+       
+       char *content_type = NULL, *content_encoding = NULL, *holder = NULL, *attachment_name, *t = NULL;
+       int type = 0, end_of_parsing = 0, size;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emcore_check_thread_status())  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_CANCELLED;
+               return false;
+       }
+
+       if (mmsg->header)
+               content_type = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_TYPE, err_code);
+       if (!content_type)
+               content_type = "TEXT/PLAIN";
+
+       if (mmsg->header)
+               content_encoding = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_ENCODING, err_code);
+       if (!content_encoding)
+               content_encoding = "7BIT";
+
+       if (strstr(content_type, TEXT_STR)) type = TYPE_TEXT;
+       else if (strstr(content_type, IMAGE_STR)) type = TYPE_IMAGE;
+       else if (strstr(content_type, AUDIO_STR)) type = TYPE_AUDIO;
+       else if (strstr(content_type, VIDEO_STR)) type = TYPE_VIDEO;
+       else if (strstr(content_type, APPLICATION_STR)) type = TYPE_APPLICATION;
+       else if (strstr(content_type, MULTIPART_STR)) type = TYPE_MULTIPART;
+       else if (strstr(content_type, MESSAGE_STR)) type = TYPE_MESSAGE;
+       else type = TYPE_UNKNOWN;
+
+       switch (type)  {
+               case TYPE_MULTIPART:
+                       if (mmsg->header && !emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_BOUNDARY, &err))  {
+                               EM_DEBUG_FUNC_END("false");
+                               if (err_code != NULL)
+                                       *err_code = err;
+                               return false;
+                       }
+
+                       if (mmsg->header && !emcore_mime_parse_part(stream, is_file, mmsg->header->part_header, &mmsg->nested, cnt_info, &end_of_parsing, &err)) {
+                               EM_DEBUG_FUNC_END("false");
+                               if (err_code != NULL)
+                                       *err_code = err;
+                               return false;
+                       }
+
+                       /*  after finishing body parsing, make stream empty to get next mail. (get line from sock or file until '.' is read */
+                       if (end_of_parsing == true && err != EMAIL_ERROR_NO_MORE_DATA)
+                               emcore_mime_flush_receiving_buffer(stream, is_file, NULL, NULL, NULL, err_code);
+
+                       break;
+
+               default:
+                       attachment_name = NULL;
+
+                       if (mmsg->header && emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_DISPOSITION, err_code)) {
+                               attachment_name = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_FILENAME, err_code);
+                               /* if (!attachment_name) attachment_name = "unknown" */
+                               if (attachment_name) EM_DEBUG_LOG(" attachment = [%s]", attachment_name);
+                       }
+
+                       if (strstr(content_type, "PKCS7-MIME")) {
+                               EM_DEBUG_LOG("Encrypted mail do not include the body");
+                               cnt_info->file = em_malloc(sizeof(struct attachment_info));
+                               if (cnt_info->file) {
+                                       cnt_info->file->type = 2;
+                                       cnt_info->file->name = EM_SAFE_STRDUP(attachment_name);
+                                       if (!emcore_mime_get_content_data(stream, is_file, false, NULL, content_encoding, &end_of_parsing, SAVE_TYPE_FILE, &holder, &size, NULL, err_code)) {
+                                               EM_DEBUG_EXCEPTION("emcore_mime_get_content_data failed : [%d]", err_code);
+                                               return false;
+                                       }
+                                       cnt_info->file->save = holder;
+                                       cnt_info->file->size = size;
+                               }
+                               break;
+                       }
+
+                       if (cnt_info->grab_type & GRAB_TYPE_TEXT)  {
+                               /* EM_DEBUG_LINE */
+                               /*  get content data. content data is saved in file */
+                               if (!emcore_mime_get_content_data(stream, is_file, true, NULL, content_encoding, &end_of_parsing, SAVE_TYPE_FILE, &holder, &size, NULL, err_code)) {
+                                       EM_DEBUG_EXCEPTION("emcore_mime_get_content_data failed : [%d]", err_code);
+                                       return false;
+                               }
+
+                               EM_DEBUG_LOG("After emcore_mime_get_content_data");
+
+                               char *charset = mmsg->header? emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_CHARSET, err_code) : NULL; /* prevent 27453 */
+                               EM_DEBUG_LOG(">>>> charset [%s]", charset);
+
+                               if (mmsg->header && mmsg->header->part_header && strstr((t = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_TYPE, err_code)) ? t  :  "", "HTML")) {
+                                       if (!charset || !strncmp(charset, "X-UNKNOWN", strlen("X-UNKNOWN")))
+                                               cnt_info->text.html_charset = strdup("UTF-8");
+                                       else
+                                               cnt_info->text.html_charset = EM_SAFE_STRDUP(charset);
+                                       EM_DEBUG_LOG(">>>> cnt_info->text.html_charset [%s]", cnt_info->text.html_charset);
+
+                                       cnt_info->text.html = holder;
+                                       EM_DEBUG_LOG(">>>> cnt_info->text.html [%s]", cnt_info->text.html);
+                               }
+                               else if (mmsg->header) {
+
+                                       if (!charset || !strncmp(charset, "X-UNKNOWN", strlen("X-UNKNOWN")))
+                                               cnt_info->text.plain_charset = strdup("UTF-8");
+                                       else
+                                               cnt_info->text.plain_charset = EM_SAFE_STRDUP(charset);
+                                       EM_DEBUG_LOG(">>>> cnt_info->text.plain_charset [%s]", cnt_info->text.plain_charset);
+
+                                       cnt_info->text.plain = holder;
+                                       EM_DEBUG_LOG(">>>> cnt_info->text.plain [%s]", cnt_info->text.plain);
+                               }
+                       }
+
+                       break;
+       }
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_mime_parse_part(void *stream, int is_file, struct _m_part_header *parent_header, struct _m_part *nested, struct _m_content_info *cnt_info, int *eop, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], parent_header[%p], nested[%p], cnt_info[%p], eop[%p], err_code[%p]", stream, is_file, parent_header, nested, cnt_info, eop, err_code);
+
+       struct _m_body *tmp_body = NULL;
+       struct _m_part **p = NULL;
+       char buf[MIME_LINE_LEN] = {0x00, };
+       char boundary[BOUNDARY_LEN] = {0x00, };
+       char boundary_end[BOUNDARY_LEN] = {0x00, };
+       char mime_type_buffer[128] = { 0, };
+       char *boundary_str = NULL;
+       char *content_type = NULL;
+       char *content_encoding = NULL;
+       char *holder = NULL;
+       char *attachment_name = NULL;
+       char *content_disposition = NULL;
+       char *pTemp = NULL;
+       int type = 0;
+       int content_disposition_type = 0;
+       int end_of_parsing = 0;
+       int size = 0, local_err_code = EMAIL_ERROR_NONE;
+       int is_skip = false;
+       int result = 0;
+
+       boundary_str = emcore_mime_get_header_value(parent_header, CONTENT_BOUNDARY, err_code);
+
+       SNPRINTF(boundary, BOUNDARY_LEN, "--%s%s", boundary_str, CRLF_STRING);
+       SNPRINTF(boundary_end, BOUNDARY_LEN, "--%s%s", boundary_str, "--\r\n");
+
+       nested->body = NULL;
+       nested->next = NULL;
+
+       /*  goto the first found useful mime dat */
+       EM_DEBUG_LOG("Before first loop");
+       while (true)  {
+               if (!emcore_check_thread_status())  {
+                       if (err_code != NULL)
+                               *err_code = EMAIL_ERROR_CANCELLED;
+                       return false;
+               }
+               if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, err_code)) ||
+               (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, err_code))) {
+                       EM_DEBUG_EXCEPTION("emcore_mime_get_line_from_sock failed.");
+                       if (eop)
+                               *eop = true;
+                       EM_DEBUG_FUNC_END("false");
+                       return false;
+               }
+
+               if (!strcmp(buf, boundary))
+                       break;
+       }
+
+       EM_DEBUG_LOG("Before second loop");
+       while (true)  {
+               if (!(tmp_body = em_malloc(sizeof(struct _m_body))))  {
+                       EM_DEBUG_EXCEPTION("em_malloc failed.");
+                       if (nested->body)
+                               emcore_mime_free_part_body(nested->body);
+                       if (nested->next)
+                               emcore_mime_free_part(nested->next);
+                       EM_DEBUG_FUNC_END("false");
+                       return false;
+               }
+
+               memset(tmp_body, 0, sizeof(struct _m_body));
+
+               /*  parsing MIME Header */
+               if (!emcore_mime_parse_part_header(stream, is_file, &tmp_body->part_header, err_code))  {
+                       EM_DEBUG_EXCEPTION("emcore_mime_parse_part_header failed.");
+                       if (nested->body)
+                               emcore_mime_free_part_body(nested->body);
+                       if (nested->next)
+                               emcore_mime_free_part(nested->next);
+
+                       emcore_mime_free_part_body(tmp_body);
+                       return false;
+               }
+
+               content_type = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_TYPE, err_code);
+
+               if (!content_type)
+                       content_type = "TEXT/PLAIN";
+
+               content_encoding = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_ENCODING, err_code);
+               if (!content_encoding)
+                       content_encoding = "7BIT";
+
+               if (strstr(content_type, TEXT_STR)) type = TYPE_TEXT;
+               else if (strstr(content_type, IMAGE_STR)) type = TYPE_IMAGE;
+               else if (strstr(content_type, AUDIO_STR)) type = TYPE_AUDIO;
+               else if (strstr(content_type, VIDEO_STR)) type = TYPE_VIDEO;
+               else if (strstr(content_type, APPLICATION_STR)) type = TYPE_APPLICATION;
+               else if (strstr(content_type, MULTIPART_STR)) type = TYPE_MULTIPART;
+               else if (strstr(content_type, MESSAGE_STR)) type = TYPE_MESSAGE;
+               else type = TYPE_UNKNOWN;
+
+               switch (type)  {
+                       case TYPE_MULTIPART:
+                               EM_DEBUG_LOG("TYPE_MULTIPART");
+                               if (!emcore_mime_get_header_value(tmp_body->part_header, CONTENT_BOUNDARY, err_code))  {
+                                       EM_DEBUG_EXCEPTION("emcore_mime_get_header_value failed.");
+                                       emcore_mime_free_part_body(tmp_body);
+                                       EM_DEBUG_FUNC_END("false");
+                                       return false;
+                               }
+
+                               emcore_mime_parse_part(stream, is_file, tmp_body->part_header, &tmp_body->nested, cnt_info, &end_of_parsing, &local_err_code);
+
+                               if (!nested->body)
+                                       nested->body = tmp_body;
+                               else  {
+                                       p = &nested->next;
+
+                                       while (*p && (*p)->next)
+                                               *p = (*p)->next;
+
+                                       if (*p)
+                                               p = &(*p)->next;
+
+                                       if (!(*p = em_malloc(sizeof(struct _m_part))))  {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                                               if (nested->body) emcore_mime_free_part_body(nested->body);
+                                               if (nested->next) emcore_mime_free_part(nested->next);
+                                               emcore_mime_free_part_body(tmp_body);
+                                               EM_DEBUG_FUNC_END("false");
+                                               return false;
+                                       }
+
+                                       (*p)->body = tmp_body;
+                                       (*p)->next = NULL;
+                               }
+
+                               if (err_code)
+                                       *err_code = local_err_code;
+
+                               if (end_of_parsing && local_err_code != EMAIL_ERROR_NO_MORE_DATA) /*  working with imap */
+                               /* if (!end_of_parsing) */ /*  working with pop */ {
+                                       EM_DEBUG_LOG("Enter flushing socket buffer.");
+                                       emcore_mime_flush_receiving_buffer(stream, is_file, boundary, boundary_end, &end_of_parsing, err_code);
+                               }
+
+                               break;
+
+                       default:
+                               EM_DEBUG_LOG("default");
+                               attachment_name = NULL;
+                               content_disposition = NULL;
+
+                               if (type == TYPE_MESSAGE)
+                                       is_skip = true;
+
+                               if (is_skip == true)  {
+                                       if (!emcore_mime_skip_content_data(stream, is_file, boundary_str, &end_of_parsing, &size, NULL, err_code))
+                                               EM_DEBUG_EXCEPTION("emcore_mime_skip_content_data failed...");
+
+                                       emcore_mime_free_part_body(tmp_body);
+                                       EM_DEBUG_LOG_MIME("break");
+                                       break;
+                               }
+
+                               /*  first check inline content */
+                               /*  if the content id or content location exis */
+                               content_disposition = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_DISPOSITION, err_code);
+                               EM_DEBUG_LOG("content_disposition : [%s]", content_disposition);
+
+                               attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_ID, err_code);
+                               EM_DEBUG_LOG("content_id : [%s]", attachment_name);
+
+                               if (attachment_name) {
+                                       if (emcore_search_string_from_file(cnt_info->text.html, attachment_name, &result) == EMAIL_ERROR_NONE && result) {
+                                               content_disposition_type = INLINE_ATTACHMENT;
+                                       } else if (!strcasecmp(content_disposition ? content_disposition : "", "attachment")) {
+                                               attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_NAME, err_code);
+
+                                               if (!attachment_name)
+                                                       attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_FILENAME, err_code);
+
+                                               content_disposition_type = ATTACHMENT;
+
+                                       } else {
+                                               EM_DEBUG_EXCEPTION("Unknown mime type");
+                                       }
+                               } else {
+                                       if (!strcasecmp(content_disposition ? content_disposition : "", "attachment")) {
+                                               attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_NAME, err_code);
+
+                                               if (!attachment_name)
+                                                       attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_FILENAME, err_code);
+
+                                               content_disposition_type = ATTACHMENT;
+
+                                       } else if (!strcasecmp(content_disposition ? content_disposition : "", "inline")) {
+                                               attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_NAME, err_code);
+
+                                               if (!attachment_name)
+                                                       attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_FILENAME, err_code);
+
+                                               content_disposition_type = INLINE_ATTACHMENT;
+                                       } else if (strstr(content_type ? content_type : "", "PKCS7")) {
+                                               attachment_name = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_NAME, err_code);
+                                               EM_DEBUG_LOG_MIME(">> attachment = [%s]", attachment_name ? attachment_name  :  NIL);
+
+                                               content_disposition_type = ATTACHMENT;
+
+                                       } else {
+                                               EM_DEBUG_LOG("No attachment");
+                                       }
+                               }
+
+                               if (!emcore_check_thread_status())  {
+                                       if (err_code != NULL)
+                                               *err_code = EMAIL_ERROR_CANCELLED;
+                                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_CANCELLED");
+                                       emcore_mime_free_part_body(tmp_body);
+                                       EM_DEBUG_FUNC_END("false");
+                                       return false;
+                               }
+
+                               EM_DEBUG_LOG("attachment_name : [%s]", attachment_name);
+                               /*  get content and content information */
+                               if (!attachment_name)  {        /*  text */
+                                       /*  get content by buffer */
+                                       EM_DEBUG_LOG_MIME("attachment_name is NULL. It's a text message");
+                                       if (!emcore_mime_get_content_data(stream, is_file, true, boundary_str, content_encoding, &end_of_parsing, SAVE_TYPE_FILE, &holder, &size, NULL, err_code)) {
+                                               EM_DEBUG_EXCEPTION("emcore_mime_get_content_data failed [%d]", err_code);
+                                               emcore_mime_free_part_body(tmp_body);
+                                               return false;
+                                       }
+
+                                       EM_DEBUG_LOG("After emcore_mime_get_content_data");
+
+                                       if (cnt_info->grab_type & GRAB_TYPE_TEXT) {
+                                               char *charset = emcore_mime_get_header_value(tmp_body->part_header, CONTENT_CHARSET, err_code);
+                                               EM_DEBUG_LOG(" charset [%s]", charset);
+
+                                               if (tmp_body->part_header && strstr(content_type ? content_type  :  "", "HTML"))  {
+                                                       if (!charset || !strncmp(charset, "X-UNKNOWN", strlen("X-UNKNOWN")))
+                                                               cnt_info->text.html_charset = strdup("UTF-8");
+                                                       else
+                                                               cnt_info->text.html_charset = EM_SAFE_STRDUP(charset);
+                                                       EM_DEBUG_LOG(" cnt_info->text.html_charset [%s]", cnt_info->text.html_charset);
+
+                                                       cnt_info->text.html = holder;
+                                                       EM_DEBUG_LOG(" cnt_info->text.html [%s]", cnt_info->text.html);
+                                               } else {
+                                                       if (!charset || !strncmp(charset, "X-UNKNOWN", strlen("X-UNKNOWN")))
+                                                               cnt_info->text.plain_charset = strdup("UTF-8");
+                                                       else
+                                                               cnt_info->text.plain_charset = EM_SAFE_STRDUP(charset);
+                                                       EM_DEBUG_LOG(" cnt_info->text.plain_charset [%s]", cnt_info->text.plain_charset);
+
+                                                       cnt_info->text.plain = holder;
+                                                       EM_DEBUG_LOG(" cnt_info->text.plain [%s]", cnt_info->text.plain);
+                                               }
+                                       } else {
+                                               if (holder) {
+                                                       free(holder);
+                                                       holder = NULL;
+                                               }
+                                       }
+                               } else {                /*  attachment */
+                                       EM_DEBUG_LOG("attachment_name is not NULL. It's a attachment");
+                                       struct attachment_info *file = NULL;
+                                       struct attachment_info *temp_file = cnt_info->file;
+
+                                       file = em_malloc(sizeof(struct attachment_info));
+                                       if (file == NULL) {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed...");
+                                               emcore_mime_free_part_body(tmp_body);
+                                               EM_DEBUG_FUNC_END("false");
+                                               return false;
+                                       }
+
+                                       file->type = content_disposition_type;
+
+                                       EM_DEBUG_LOG("file->type : %d", file->type);
+
+                                       file->name                 = EM_SAFE_STRDUP(attachment_name);
+                                       file->content_id           = EM_SAFE_STRDUP(tmp_body->part_header->content_id);
+                                       if(tmp_body->part_header->type && tmp_body->part_header->subtype) {
+                                               SNPRINTF(mime_type_buffer, 128, "%s/%s", tmp_body->part_header->type, tmp_body->part_header->subtype);
+                                               file->attachment_mime_type = EM_SAFE_STRDUP(mime_type_buffer);
+                                       }
+
+                                       /*  check if the current file is target file */
+                                       if ((cnt_info->grab_type & GRAB_TYPE_ATTACHMENT) || file->type == INLINE_ATTACHMENT)  {
+                                               /*  get content by file */
+                                               EM_DEBUG_LOG_MIME("Trying to get content");
+                                               if (!emcore_mime_get_content_data(stream, is_file, false, boundary_str, content_encoding, &end_of_parsing, SAVE_TYPE_FILE, &holder, &size, NULL, err_code)) {
+                                                       EM_DEBUG_EXCEPTION("emcore_mime_get_content_data failed [%d]", err_code);
+                                                       emcore_mime_free_part_body(tmp_body);
+                                                       emcore_free_attachment_info(file);
+                                                       EM_DEBUG_FUNC_END("false");
+                                                       return false;
+                                               }
+
+                                               file->save = holder;
+                                       } else {
+                                               /*  only get content size */
+                                               EM_DEBUG_LOG_MIME("Pass downloading");
+                                               if (!emcore_mime_get_content_data(stream, is_file, false, boundary_str, content_encoding, &end_of_parsing, SAVE_TYPE_SIZE, NULL, &size, NULL, err_code)) {
+                                                       EM_DEBUG_EXCEPTION("emcore_mime_get_content_data failed [%d]", err_code);
+                                                       emcore_mime_free_part_body(tmp_body);
+                                                       emcore_free_attachment_info(file);
+                                                       EM_DEBUG_FUNC_END("false");
+                                                       return false;
+                                               }
+
+                                               file->save = NULL;
+                                       }
+
+                                       if (err_code)
+                                               EM_DEBUG_LOG("end_of_parsing [%d], err_code [%d]", end_of_parsing, *err_code);
+
+                                       file->size = size;
+
+                                       if (strstr(content_type, APPLICATION_STR))  {
+                                               pTemp = content_type + EM_SAFE_STRLEN(APPLICATION_STR);
+
+                                               if (strcasecmp(pTemp, MIME_SUBTYPE_DRM_OBJECT) == 0)
+                                                       file->drm = EMAIL_ATTACHMENT_DRM_OBJECT;
+                                               else if (strcasecmp(pTemp, MIME_SUBTYPE_DRM_RIGHTS) == 0)
+                                                       file->drm = EMAIL_ATTACHMENT_DRM_RIGHTS;
+                                               else if (strcasecmp(pTemp, MIME_SUBTYPE_DRM_DCF) == 0)
+                                                       file->drm = EMAIL_ATTACHMENT_DRM_DCF;
+                                       }
+
+                                       while (temp_file && temp_file->next)
+                                               temp_file = temp_file->next;
+
+                                       if (temp_file == NULL)
+                                               cnt_info->file = file;
+                                       else
+                                               temp_file->next = file;
+                               }
+
+                               if (!emcore_check_thread_status())  {
+                                       if (err_code != NULL)
+                                               *err_code = EMAIL_ERROR_CANCELLED;
+                                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_CANCELLED");
+                                       emcore_mime_free_part_body(tmp_body);
+                                       EM_DEBUG_FUNC_END("false");
+                                       return false;
+                               }
+
+                               if (!nested->body)
+                                       nested->body = tmp_body;
+                               else {
+                                       p = &nested->next;
+
+                                       while (*p && (*p)->next)
+                                               p = &(*p)->next;
+
+                                       if (*p)
+                                               p = &(*p)->next;
+
+                                       if (!(*p = em_malloc(sizeof(struct _m_part))))  {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                                               if (nested->body) emcore_mime_free_part_body(nested->body);
+                                               if (nested->next) emcore_mime_free_part(nested->next);
+
+                                               emcore_mime_free_part_body(tmp_body);
+                                               EM_DEBUG_FUNC_END("false");
+                                               return false;
+                                       }
+
+                                       (*p)->body = tmp_body;
+                                       (*p)->next = NULL;
+                               }
+
+                               break;
+               }
+
+               /*  End of parsin */
+               if (end_of_parsing)
+                       break;
+       }
+
+       if (eop != NULL)
+               *eop = end_of_parsing;
+
+       EM_DEBUG_FUNC_END("end_of_parsing [%d]", end_of_parsing);
+       return true;
+}
+
+/*  set RFC822 Heade */
+int emcore_mime_set_rfc822_header_value(struct _rfc822header **header, char *name, char *value, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("header[%p], name[%s], value[%s], err_code[%p]", header, name, value, err_code);
+
+       char **p = NULL;
+       char *t = NULL;
+
+       if (!value || !*value || !name ) return false; /*prevent 34354*/
+
+       if (!*header)  {
+               *header = em_malloc(sizeof(struct _rfc822header));
+               if (!*header)  {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       return false;
+               }
+       }
+
+
+       em_upper_string(name);
+
+       if (strncmp(name, "RETURN-PATH", strlen("RETURN-PATH")) == 0)
+               p = &(*header)->return_path;/*  Return-Rat */
+       else if (strncmp(name, "RECEIVED", strlen("RECEIVED")) == 0)
+               p = &(*header)->received;       /*  Receive */
+       else if (strncmp(name, "REPLY-TO", strlen("REPLY-TO")) == 0)
+               p = &(*header)->reply_to;       /*  Reply-T */
+       else if (strncmp(name, "DATE", strlen("DATE")) == 0)
+               p = &(*header)->date;           /*  Dat */
+       else if (strncmp(name, "FROM", strlen("FROM")) == 0)
+               p = &(*header)->from;           /*  Fro */
+       else if (strncmp(name, "SUBJECT", strlen("SUBJECT")) == 0)
+               p = &(*header)->subject;        /*  Subjec */
+       else if (strncmp(name, "SENDER", strlen("SENDER")) == 0)
+               p = &(*header)->sender;         /*  Sende */
+       else if (strncmp(name, "TO", strlen("TO")) == 0)
+               p = &(*header)->to;                     /*  T */
+       else if (strncmp(name, "CC", strlen("CC")) == 0)
+               p = &(*header)->cc;                     /*  C */
+       else if (strncmp(name, "BCC", strlen("BCC")) == 0)
+               p = &(*header)->bcc;            /*  Bc */
+       else if (strncmp(name, "X-PRIORITY", strlen("X-PRIORITY")) == 0)
+               p = &(*header)->priority;       /*  Prorit */
+       else if (strncmp(name, "X-MSMAIL-PRIORITY", strlen("X-MSMAIL-PRIORITY")) == 0)
+               p = &(*header)->ms_priority;/*  Prorit */
+       else if (strncmp(name, "DISPOSITION-NOTIFICATION-TO", strlen("DISPOSITION-NOTIFICATION-TO")) == 0)
+               p = &(*header)->dsp_noti_to;/*  Disposition-Notification-T */
+       else {
+               return false;
+       }
+
+       if (!*p)
+               *p = EM_SAFE_STRDUP(value);
+       else  { /*  Long Header */
+               if (!(t = realloc(*p, strlen(*p) + strlen(value)+1))) /*prevent 34354*/
+                       return false;
+
+               strncat(t, value, strlen(value)); /*prevent 34354*/
+               *p = t;
+       }
+
+       return true;
+}
+
+/*  set MIME Part Heade */
+int emcore_mime_set_part_header_value(struct _m_part_header **header, char *name, char *value, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("header[%p], name[%s], value[%s], err_code[%p]", header, name, value, err_code);
+
+       if (!name || !value) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       struct _parameter *p = NULL;
+       char *p_val = NULL;
+
+       if (!*header)  {
+               *header = em_malloc(sizeof(struct _m_part_header));
+               if (!(*header)) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed...");
+                       return false;
+               }
+       }
+
+       em_upper_string(name);
+       em_trim_left(value);
+       em_trim_right(value);
+
+       if (!emcore_check_thread_status())  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_CANCELLED;
+               return false;
+       }
+
+       if (name) {
+               if (strncmp(name, "CONTENT-TYPE", strlen("CONTENT-TYPE")) == 0)  {
+                       p_val = strtok(value, ";");
+
+                       if (p_val)  {
+                               if (!(*header)->type)  {   /*  Content-Type */
+                                       em_upper_string(p_val);
+                                       (*header)->type = EM_SAFE_STRDUP(p_val);
+                               }
+                               else  {   /*  Content-Type Parameter (format :  "name =value" */
+                                       if (emcore_mime_get_param_from_str(p_val, &p, err_code))
+                                               emcore_mime_add_param_to_list(&((*header)->parameter), p, err_code);
+                                       else /* name= CRLF value */ {
+                                               struct _parameter *t = (*header)->parameter;
+                                               while (t && t->next) {
+                                                       t = t->next;
+                                               }
+
+                                               EM_DEBUG_LOG("name : [%s]", t->name);
+                                               EM_DEBUG_LOG("value : [%s]", t->value);
+
+                                               if (t->value == NULL) {
+                                                       char *pointer = NULL;
+
+                                                       if (EM_SAFE_STRLEN(p_val) > 0)  {
+                                                               if ((pointer = strchr(p_val, '\"')))  {
+                                                                       p_val = pointer + 1;
+                                                                       if (!*p_val) return false;
+                                                               }
+                                                               if ((pointer = strchr(p_val, '\"')))
+                                                                       *pointer = '\0';
+
+                                                               /*  = ? ENCODING_TYPE ? B(Q) ? ENCODED_STRING ? */
+                                                               int err = EMAIL_ERROR_NONE;
+                                                               char *utf8_text = NULL;
+
+                                                               if (!(utf8_text = emcore_decode_rfc2047_text(p_val, &err)))
+                                                                       EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_text failed [%d]", err);
+                                                               EM_DEBUG_LOG("utf8_text : [%s]", utf8_text);
+                                                               t->value = EM_SAFE_STRDUP(utf8_text);
+                                                       }
+                                               }
+                                       }
+
+                               }
+
+                               /*  repeatedly get paramete */
+                               while ((p_val = strtok(NULL, ";")))  {
+                                       if (emcore_mime_get_param_from_str(p_val, &p, err_code))
+                                               emcore_mime_add_param_to_list(&((*header)->parameter), p, err_code);
+                               }
+                       }
+               }
+               else if (strncmp(name, "CONTENT-TRANSFER-ENCODING", strlen("CONTENT-TRANSFER-ENCODING")) == 0)  {
+                       em_upper_string(value);
+                       (*header)->encoding = EM_SAFE_STRDUP(value);
+               }
+               else if (strncmp(name, "CONTENT-DESCRPTION", strlen("CONTENT-DESCRPTION")) == 0)  {
+                       em_upper_string(value);
+                       (*header)->desc = EM_SAFE_STRDUP(value);
+               }
+               else if (strncmp(name, "CONTENT-DISPOSITION", strlen("CONTENT-DISPOSITION")) == 0)  {
+                       p_val = strtok(value, ";");
+
+                       if (p_val)  {
+                               if (!(*header)->disp_type)  {   /*  Content-Dispositio */
+                                       em_upper_string(p_val);
+                                       (*header)->disp_type = EM_SAFE_STRDUP(p_val);
+                               }
+                               else  { /*  Content-Disposition parameter (format :  "name =value" */
+                                       if (emcore_mime_get_param_from_str(p_val, &p, err_code))
+                                               emcore_mime_add_param_to_list(&((*header)->disp_parameter), p, err_code);
+                               }
+
+                               /*  repeatedly get paramete */
+                               while ((p_val = strtok(NULL, ";")))  {
+                                       if (emcore_mime_get_param_from_str(p_val, &p, err_code))
+                                               emcore_mime_add_param_to_list(&((*header)->disp_parameter), p, err_code);
+                               }
+                       }
+               }
+               else if (strncmp(name, "CONTENT-ID", strlen("CONTENT-ID")) == 0)  {
+                       size_t len = 0;
+                       len = EM_SAFE_STRLEN(value);
+                       /* em_upper_string(value) */
+
+                       if ((len) && (value[0] == '<'))  {
+                               ++value;
+                               --len;
+                       }
+
+                       if ((len > 1) && (value[len-1] == '>'))
+                               value[len-1] = '\0';
+
+                       (*header)->content_id = EM_SAFE_STRDUP(value);
+               }
+               else if (strncmp(name, "CONTENT-LOCATION", strlen("CONTENT-LOCATION")) == 0)
+                       (*header)->content_location = EM_SAFE_STRDUP(value);
+       }
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+/*  get header parameter from string */
+int emcore_mime_get_param_from_str(char *str, struct _parameter **param, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("str[%s], param[%p], err_code[%p]", str, param, err_code);
+
+       char *p_name, *p_val, *p;
+
+       *param = NULL;
+
+       /*  Parameter Check */
+       if (!(p = strchr(str, '=')))    return false;
+
+       *p = '\0';
+
+       p_name = str;
+       p_val = p+1;
+
+       em_trim_left(p_name);
+       em_trim_right(p_name);
+
+       if (!*p_name) return false;
+
+       if (!(*param = em_malloc(sizeof(struct _parameter)))) return false;
+
+       (*param)->next = NULL;
+
+       /*  Name set */
+       /*  Check string length */
+       if (EM_SAFE_STRLEN(p_name) > 0)  {
+               em_upper_string(p_name);
+               (*param)->name = EM_SAFE_STRDUP(p_name);
+       }
+
+       em_trim_left(p_val);
+       em_trim_right(p_val);
+
+       if (!*p_val)  {
+               EM_DEBUG_LOG("Parameter value is NULL");
+               return true;
+       }
+
+       if (EM_SAFE_STRLEN(p_val) > 0)  {
+               if ((p = strchr(p_val, '\"')))  {
+                       p_val = p + 1;
+                       if (!*p_val) return false;
+               }
+               if ((p = strchr(p_val, '\"')))
+                       *p = '\0';
+
+               if (strncmp(p_name, "BOUNDARY", strlen("BOUNDARY")) != 0 && !strstr(p_name, "NAME"))
+                       em_upper_string(p_val);
+
+               /*  = ? ENCODING_TYPE ? B(Q) ? ENCODED_STRING ? */
+               int err = EMAIL_ERROR_NONE;
+               char *utf8_text = NULL;
+
+               if (!(utf8_text = emcore_decode_rfc2047_text(p_val, &err)))
+                       EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_text failed [%d]", err);
+               (*param)->value = utf8_text;
+       }
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+/*  add a parameter to parameter lis */
+int emcore_mime_add_param_to_list(struct _parameter **param_list, struct _parameter *param, int *err_code)
+{
+       struct _parameter **t = param_list;
+
+       while (*t && (*t)->next)
+               *t = (*t)->next;
+
+       if (*t)
+               (*t)->next = param;
+       else
+               *t = param;
+
+       return true;
+}
+
+/*  get header value from MIME Part Heade */
+char *emcore_mime_get_header_value(struct _m_part_header *header, int type, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("header[%p], type[%d], err_code[%p]", header, type, err_code);
+
+       struct _parameter *p = NULL;
+       char *name = NULL;
+
+       if (!header)  {
+               EM_DEBUG_EXCEPTION("header[%p], type[%d]", header, type);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return NULL;
+       }
+
+       switch (type)  {
+               case CONTENT_TYPE:
+                       return header->type;
+
+               case CONTENT_SUBTYPE:
+                       return header->subtype;
+
+               case CONTENT_ENCODING:
+                       return header->encoding;
+
+               case CONTENT_CHARSET:
+                       name = "CHARSET";
+                       p = header->parameter;
+                       break;
+
+               case CONTENT_DISPOSITION:
+                       return header->disp_type;
+
+               case CONTENT_NAME:
+                       name = "NAME";
+                       p = header->parameter;
+                       break;
+
+               case CONTENT_FILENAME:
+                       name = "FILENAME";
+                       p = header->disp_parameter;
+                       break;
+
+               case CONTENT_BOUNDARY:
+                       name = "BOUNDARY";
+                       p = header->parameter;
+                       break;
+
+               case CONTENT_REPORT_TYPE:
+                       name = "REPORT-TYPE";
+                       p = header->parameter;
+                       break;
+
+               case CONTENT_ID:
+                       return header->content_id;
+
+               case CONTENT_LOCATION:
+                       return header->content_location;
+
+               default:
+                       return NULL;
+       }
+
+       for (; p; p = p->next)  {
+               if (strcmp(p->name, name) == 0)
+                       break;
+       }
+
+       if (!p)
+               return NULL;
+       EM_DEBUG_FUNC_END();
+       return p->value;
+}
+
+/*
+ * decode body text (quoted-printable, base64)
+ * enc_type : encoding type (base64/quotedprintable)
+ */
+INTERNAL_FUNC int emcore_decode_body_text(char *enc_buf, int enc_len, int enc_type, int *dec_len, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("enc_buf[%p], enc_len[%d], enc_type[%d], dec_len[%p]", enc_buf, enc_len, enc_type, dec_len);
+       unsigned char *content = NULL;
+
+       /*  too many called */
+       *dec_len = enc_len;
+
+       switch (enc_type)  {
+               case ENCQUOTEDPRINTABLE:
+                       EM_DEBUG_LOG("ENCQUOTEDPRINTABLE");
+                       content = rfc822_qprint((unsigned char *)enc_buf, (unsigned long)enc_len, (unsigned long *)dec_len);
+                       break;
+
+               case ENCBASE64:
+                       EM_DEBUG_LOG("ENCBASE64");
+                       content = rfc822_base64((unsigned char *)enc_buf, (unsigned long)enc_len, (unsigned long *)dec_len);
+                       break;
+
+               case ENC7BIT:
+               case ENC8BIT:
+               case ENCBINARY:
+               case ENCOTHER:
+               default:
+                       break;
+       }
+
+       if (content)  {
+               if (enc_len < *dec_len) {
+                       EM_DEBUG_EXCEPTION("Decoded length is too big to store it");
+                       return -1;
+               }
+               memcpy(enc_buf, content, *dec_len);
+               enc_buf[*dec_len] = '\0';
+               EM_SAFE_FREE(content);
+       }
+       EM_DEBUG_FUNC_END();
+       return 0;
+}
+
+/*  1. if boundary is NULL, contnent has not multipart */
+/*  2. if boundary isn't NULL, content is from current line to the next found boundary */
+/*     if next found boundary is the other part boundary ("--boundary"), return and set end_of_parsing to 1 */
+/*     if next found boundary is the multipart ending boundary ("--boundary--"), return and set end_of_parsing to 0 */
+/*  mode - SAVE_TYPE_SIZE   :  no saving (only hold content size */
+/*         SAVE_TYPE_BUFFER :  content is saved to buffer (holder is buffer */
+/*         SAVE_TYPE_FILE   :  content is saved to temporary file (holder is file name */
+int emcore_mime_get_content_data(void *stream, int is_file, int is_text, char *boundary_str, char *content_encoding, int *end_of_parsing, int mode, char **holder, int *size, void *callback, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], boundary_str[%s], content_encoding[%s], end_of_parsing[%p], mode[%d], holder[%p], size[%p], callback[%p], err_code[%p]", stream, is_file, boundary_str, content_encoding, end_of_parsing, mode, holder, size, callback, err_code);
+
+       int encoding = ENC7BIT;
+       int error = EMAIL_ERROR_NONE, ret = false;
+       int fd = 0;
+       int sz = 0;
+
+       if ((mode == SAVE_TYPE_FILE || mode == SAVE_TYPE_BUFFER) && !holder)
+               return false;
+
+       if (holder)
+               *holder = NULL;
+
+       if (size)
+               *size = 0;
+
+       EM_DEBUG_LOG("get content");
+
+       if (content_encoding)  {
+               switch (content_encoding[0])  {
+                       case 'Q':
+                               encoding = ENCQUOTEDPRINTABLE;
+                               break;  /*  qutoed-printabl */
+                       case 'B':
+                               if (content_encoding[1] == 'A')  {
+                                       encoding = ENCBASE64;
+                                       break; /*  base6 */
+                               }
+                               if (content_encoding[1] == 'I')  {
+                                       encoding = ENCBINARY;
+                                       break; /*  binar */
+                               }
+                               encoding = ENC7BIT;
+                               break;
+                       case '7':
+                               encoding = ENC7BIT;
+                               break; /*  7bi */
+                       case '8':
+                               encoding = ENC8BIT;
+                               break; /*  8bi */
+                       default:
+                               encoding = ENCOTHER;
+                               break; /*  unknow */
+               }
+       }
+
+       /*  saving type is file */
+       if (mode == SAVE_TYPE_FILE)  {
+               *holder = emcore_mime_get_save_file_name(&error);
+
+               EM_DEBUG_LOG("holder[%s]", *holder);
+
+               fd = open(*holder, O_WRONLY|O_CREAT, 0644);
+               if (fd < 0)  {
+                       EM_DEBUG_EXCEPTION("holder open failed :  holder is a filename that will be saved.");
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (is_file) {
+               EM_DEBUG_LOG("from file");
+               error = emcore_decode_body_text_from_file((FILE *)stream, boundary_str, encoding, mode, is_text, fd, holder, end_of_parsing, &sz);
+               if (error != EMAIL_ERROR_NONE) {
+                       if (error != EMAIL_ERROR_NO_MORE_DATA) {
+                               EM_DEBUG_EXCEPTION("emcore_decode_body_text_from_file failed : [%d]", error);
+                               goto FINISH_OFF;
+                       }
+               }
+       } else {
+               EM_DEBUG_LOG("from sock");
+               error = emcore_decode_body_text_from_sock(stream, boundary_str, encoding, mode, is_text, fd, holder, end_of_parsing, &sz);
+               if (error != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_decode_body_text_from_sock failed : [%d]", error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       if(fd>0) close(fd); /*prevent 32736*/
+
+       if (ret) {
+               if (size)
+                       *size = sz;
+       }
+
+       EM_DEBUG_FUNC_END("ret [%d], sz [%d]", ret, sz);
+       return ret;
+}
+
+int emcore_mime_skip_content_data(void *stream,
+                                                       int is_file,
+                                                       char *boundary_str,
+                                                       int *end_of_parsing,
+                                                       int *size,
+                                                       void *callback,
+                                                       int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], is_file[%d], boundary_str[%s], end_of_parsing[%p], size[%p], callback[%p], err_code[%p]", stream, is_file, boundary_str, end_of_parsing, size, callback, err_code);
+
+       char buf[MIME_LINE_LEN] = {0x00}, boundary[BOUNDARY_LEN], boundary_end[BOUNDARY_LEN];
+       int sz = 0;
+
+       if (size)
+               *size = 0;
+
+       EM_DEBUG_LOG(">>> skip content <<<<<<<<<<<<<");
+
+       if (!boundary_str)  {   /*  if no boundary, this content is from current line to end of all multipart */
+               while (TRUE)  {
+
+                       if (!emcore_check_thread_status())  {
+                               if (err_code != NULL)
+                                       *err_code = EMAIL_ERROR_CANCELLED;
+                               return false;
+                       }
+                       if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, err_code)) ||
+                       (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, err_code)))  {
+                               *end_of_parsing = 1;
+                               if (size)
+                                       *size = sz;
+                               return false;
+                       }
+                       sz += EM_SAFE_STRLEN(buf);
+               }
+       }
+       else  {         /*  if there boundary, this content is from current line to ending boundary */
+               memset(boundary, 0x00, BOUNDARY_LEN);
+               memset(boundary_end, 0x00, BOUNDARY_LEN);
+
+               SNPRINTF(boundary,  BOUNDARY_LEN, "--%s%s", boundary_str, CRLF_STRING);
+               SNPRINTF(boundary_end, BOUNDARY_LEN, "--%s%s", boundary_str, "--\r\n");
+
+               while (TRUE)  {
+
+                       if (!emcore_check_thread_status())  {
+                               if (err_code != NULL)
+                                       *err_code = EMAIL_ERROR_CANCELLED;
+                               return false;
+                       }
+                       if ((is_file == 0 && !emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, err_code)) ||
+                       (is_file == 1 && !emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, err_code)))  {
+                               /*  end of fil */
+                               *end_of_parsing = 1;
+                               if (size)
+                                       *size = sz;
+                               return true;
+                       }
+
+                       if (!strcmp(buf, boundary))  {          /*  the other part started. the parsing of other part will be started */
+                               *end_of_parsing = 0;
+                               if (size)
+                                       *size = sz;
+                               return true;
+                       }
+                       else if (!strcmp(buf, boundary_end))  {         /*  if ending boundary, the parsing of other multipart will be started */
+                               *end_of_parsing = 1;
+                               if (size)
+                                       *size = sz;
+                               return true;
+                       }
+
+                       sz += EM_SAFE_STRLEN(buf);
+               }
+       }
+
+       if (size)
+               *size = sz;
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+/*  get temporary file name */
+char *emcore_mime_get_save_file_name(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       char tempname[512];
+       struct timeval tv;
+
+       gettimeofday(&tv, NULL);
+       srand(tv.tv_usec);
+
+       memset(tempname, 0x00, sizeof(tempname));
+
+       SNPRINTF(tempname, sizeof(tempname), "%s%s%d", MAILTEMP, DIR_SEPERATOR, rand());
+       EM_DEBUG_FUNC_END();
+       return EM_SAFE_STRDUP(tempname);
+}
+
+/*  get a line from file pointer */
+char *emcore_get_line_from_file(void *stream, char *buf, int size, int *err_code)
+{
+       if (!fgets(buf, size, (FILE *)stream))  {
+               if (feof((FILE *)stream)) {
+                       *err_code = EMAIL_ERROR_NO_MORE_DATA;
+                       return NULL;
+               } else
+                       return NULL;
+       }
+       return buf;
+}
+
+/*  get a line from POP3 mail stream */
+/*  emcore_mail_cmd_read_mail_pop3 must be called before this function */
+char *emcore_mime_get_line_from_sock(void *stream, char *buf, int size, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], buf[%p]", stream, buf);
+       POP3LOCAL *p_pop3local = NULL;
+
+       if (!stream || !buf)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return NULL;
+       }
+
+       memset(buf, 0x00, size);
+
+       p_pop3local = (POP3LOCAL *)(((MAILSTREAM *)stream)->local);
+       if (!p_pop3local)  {
+               EM_DEBUG_EXCEPTION("stream->local[%p]", p_pop3local);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return NULL;
+       }
+
+       if (!pop3_reply((MAILSTREAM *)stream))  { /*  if TRUE, check respons */
+               EM_DEBUG_LOG("p_pop3local->response 1[%s]", p_pop3local->response);
+               if (p_pop3local->response) {
+                       if (*p_pop3local->response == '.' && EM_SAFE_STRLEN(p_pop3local->response) == 1)  {
+                               free(p_pop3local->response);
+                               p_pop3local->response = NULL;
+                               if (err_code != NULL)
+                                       *err_code = EMAIL_ERROR_NO_MORE_DATA;
+                               EM_DEBUG_FUNC_END("end of response");
+                               return NULL;
+                       }
+                       EM_DEBUG_LOG("Not end of response");
+                       strncpy(buf, p_pop3local->response, size-1);
+                       strncat(buf, CRLF_STRING, size-(EM_SAFE_STRLEN(buf) + 1));
+
+                       free(p_pop3local->response);
+                       p_pop3local->response = NULL;
+
+                       goto FINISH_OFF;
+               }
+       }
+
+       EM_DEBUG_LOG("p_pop3local->response 2[%s]", p_pop3local->response);
+       if (p_pop3local->response)
+       {
+               /*  if response isn't NULL, check whether this response start with '+' */
+               /*  if the first character is '+', return error because this response is normal data */
+               strncpy(buf, p_pop3local->response, size-1);
+               strncat(buf, CRLF_STRING, size-(EM_SAFE_STRLEN(buf)+1));
+               free(p_pop3local->response); p_pop3local->response = NULL;
+               goto FINISH_OFF;
+       }
+       else  {
+               EM_DEBUG_EXCEPTION("p_pop3local->response is null. network error... ");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_RESPONSE;
+               EM_DEBUG_FUNC_END();
+               return NULL;
+       }
+
+FINISH_OFF:
+       if (buf) {
+               int received_percentage, last_notified_percentage;
+               _pop3_received_body_size += EM_SAFE_STRLEN(buf);
+
+               last_notified_percentage = (double)_pop3_last_notified_body_size / (double)_pop3_total_body_size *100.0;
+               received_percentage      = (double)_pop3_received_body_size / (double)_pop3_total_body_size *100.0;
+
+               EM_DEBUG_LOG("_pop3_received_body_size = %d, _pop3_total_body_size = %d", _pop3_received_body_size, _pop3_total_body_size);
+               EM_DEBUG_LOG("received_percentage = %d, last_notified_percentage = %d", received_percentage, last_notified_percentage);
+
+               if (received_percentage > last_notified_percentage + 5) {
+                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, _pop3_receiving_mail_id, "dummy-file", _pop3_total_body_size, _pop3_received_body_size))
+                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
+                       else
+                               EM_DEBUG_LOG("NOTI_DOWNLOAD_BODY_START notified (%d / %d)", _pop3_received_body_size, _pop3_total_body_size);
+                       _pop3_last_notified_body_size = _pop3_received_body_size;
+               }
+       }
+       EM_DEBUG_FUNC_END();
+       return buf;
+}
+
+void emcore_mime_free_param(struct _parameter *param)
+{
+       struct _parameter *t, *p = param;
+       EM_DEBUG_FUNC_BEGIN();
+       while (p) {
+               t = p->next;
+               EM_SAFE_FREE(p->name);
+               EM_SAFE_FREE(p->value);
+               free(p);p = NULL;
+               p = t;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_mime_free_part_header(struct _m_part_header *header)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (!header) return ;
+       EM_SAFE_FREE(header->type);
+       if (header->parameter) emcore_mime_free_param(header->parameter);
+       EM_SAFE_FREE(header->subtype);
+       EM_SAFE_FREE(header->encoding);
+       EM_SAFE_FREE(header->desc);
+       EM_SAFE_FREE(header->disp_type);
+       if (header->disp_parameter) emcore_mime_free_param(header->disp_parameter);
+       free(header); header = NULL;
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_mime_free_message_header(struct _m_mesg_header *header)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (!header) return ;
+       EM_SAFE_FREE(header->version);
+       if (header->part_header) emcore_mime_free_part_header(header->part_header);
+       free(header); header = NULL;
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_mime_free_rfc822_header(struct _rfc822header *header)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (!header) return ;
+       EM_SAFE_FREE(header->return_path);
+       EM_SAFE_FREE(header->received);
+       EM_SAFE_FREE(header->reply_to);
+       EM_SAFE_FREE(header->date);
+       EM_SAFE_FREE(header->from);
+       EM_SAFE_FREE(header->subject);
+       EM_SAFE_FREE(header->sender);
+       EM_SAFE_FREE(header->to);
+       EM_SAFE_FREE(header->cc);
+       EM_SAFE_FREE(header->bcc);
+       free(header); header = NULL;
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_mime_free_part_body(struct _m_body *body)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (!body) return ;
+       if (body->part_header) emcore_mime_free_part_header(body->part_header);
+       EM_SAFE_FREE(body->text);
+       if (body->nested.body) emcore_mime_free_part_body(body->nested.body);
+       if (body->nested.next) emcore_mime_free_part(body->nested.next);
+       free(body); body = NULL;
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_mime_free_part(struct _m_part *part)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (!part) return ;
+       if (part->body) emcore_mime_free_part_body(part->body);
+       if (part->next) emcore_mime_free_part(part->next);
+       free(part);part = NULL;
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_mime_free_mime(struct _m_mesg *mmsg)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!mmsg) return ;
+       if (mmsg->header) emcore_mime_free_message_header(mmsg->header);
+       if (mmsg->rfc822header) emcore_mime_free_rfc822_header(mmsg->rfc822header);
+       if (mmsg->nested.body) emcore_mime_free_part_body(mmsg->nested.body);
+       if (mmsg->nested.next) emcore_mime_free_part(mmsg->nested.next);
+       EM_SAFE_FREE(mmsg->text);
+       free(mmsg); mmsg = NULL;
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_free_content_info(struct _m_content_info *cnt_info)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       struct attachment_info *p;
+
+       if (!cnt_info) return ;
+       EM_SAFE_FREE(cnt_info->text.plain);
+       EM_SAFE_FREE(cnt_info->text.plain_charset);
+       EM_SAFE_FREE(cnt_info->text.html);
+       while (cnt_info->file) {
+               p = cnt_info->file->next;
+               EM_SAFE_FREE(cnt_info->file->name);
+               EM_SAFE_FREE(cnt_info->file->save);
+               EM_SAFE_FREE(cnt_info->file->attachment_mime_type);
+               EM_SAFE_FREE(cnt_info->file->content_id);
+               free(cnt_info->file); cnt_info->file = NULL;
+               cnt_info->file = p;
+       }
+       free(cnt_info);cnt_info = NULL;
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_free_attachment_info(struct attachment_info *attchment)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       struct attachment_info *p;
+
+       if (!attchment) return;
+
+       while (attchment) {
+               p = attchment->next;
+               EM_SAFE_FREE(attchment->name);
+               EM_SAFE_FREE(attchment->save);
+               EM_SAFE_FREE(attchment->attachment_mime_type);
+               EM_SAFE_FREE(attchment->content_id);
+               EM_SAFE_FREE(attchment);
+               attchment = p;
+       }
+
+       EM_DEBUG_FUNC_END();
+}
+
+/* get body-part in nested part */
+static PARTLIST *emcore_get_allnested_part_full(MAILSTREAM *stream, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST *section_list)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       PART *part_child = body->nested.part;
+
+       while (part_child) {
+               section_list = emcore_get_body_full(stream, msg_uid, &part_child->body, cnt_info, err_code, section_list);
+               part_child = part_child->next;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return section_list;
+}
+
+/* get body-part in alternative multiple part */
+static PARTLIST *emcore_get_alternative_multi_part_full(MAILSTREAM *stream, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST *section_list)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       PART *part_child = body->nested.part;
+
+       /* find the best sub part we can show */
+       while (part_child)  {
+               section_list = emcore_get_body_full(stream, msg_uid, &part_child->body, cnt_info, err_code, section_list);
+               part_child = part_child->next;
+       }
+
+       EM_DEBUG_FUNC_END("section_list[%p]", section_list);
+       return section_list;
+}
+
+/* get body part in signed multiple part */
+static PARTLIST *emcore_get_signed_multi_part_full(MAILSTREAM *stream, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST *section_list)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       PART *part_child = body->nested.part;
+
+       /* find the best sub part we can show */
+       while (part_child)  {
+               section_list = emcore_get_body_full(stream, msg_uid, &part_child->body, cnt_info, err_code, section_list);
+               part_child = part_child->next;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return section_list;
+}
+
+/* get body part in encrypted multiple part */
+static PARTLIST *emcore_get_encrypted_multi_part_full(MAILSTREAM *stream, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST *section_list)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       /*  "protocol" = "application/pgp-encrypted */
+       EM_DEBUG_FUNC_END();
+       return section_list;
+}
+
+/* get body part in multiple part */
+static PARTLIST *emcore_get_multi_part_full(MAILSTREAM *stream, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST *section_list)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       switch (body->subtype[0])  {
+               case 'A':               /*  ALTERNATIV */
+                       return section_list = emcore_get_alternative_multi_part_full(stream, msg_uid, body, cnt_info, err_code, section_list);
+
+               case 'S':               /*  SIGNE */
+                       return section_list = emcore_get_signed_multi_part_full(stream, msg_uid, body, cnt_info, err_code, section_list);
+
+               case 'E':               /*  ENCRYPTE */
+                       return section_list = emcore_get_encrypted_multi_part_full(stream, msg_uid, body, cnt_info, err_code, section_list);
+
+               default:                /*  process all unknown as MIXED (according to the RFC 2047 */
+                       return section_list = emcore_get_allnested_part_full(stream, msg_uid, body, cnt_info, err_code, section_list);
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+
+PARTLIST* emcore_get_body_full(MAILSTREAM *stream, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST *section_list)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+       char content_type_buffer[512] = { 0, };
+
+       if (!stream || !body || !cnt_info)  {
+               EM_DEBUG_EXCEPTION("stream[%p], msg_uid[%d], body[%p], cnt_info[%p]", stream, msg_uid, body, cnt_info);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_FUNC_END();
+               return NULL;
+       }
+
+       switch (body->type)  {
+               case TYPEMULTIPART:
+                       section_list = emcore_get_multi_part_full(stream, msg_uid, body, cnt_info, err_code, section_list);
+                       EM_DEBUG_FUNC_END("section_list [%p]", section_list);
+                       return section_list;
+
+               case TYPEMESSAGE:
+                       break;
+
+               case TYPETEXT:
+               case TYPEAPPLICATION:
+               case TYPEAUDIO:
+               case TYPEIMAGE:
+               case TYPEVIDEO:
+               case TYPEMODEL:
+               case TYPEOTHER:
+
+                       /* Form list of attachment followed by list of inline images */
+                       if (body->id || body->location || body->disposition.type) {
+
+                               char filename[512] = {0, };
+                               struct attachment_info *current_ai = NULL;
+                               struct attachment_info *ai = NULL;
+
+                               if (emcore_get_file_pointer(body, true, filename, cnt_info, (int*)NULL) < 0)
+                                       EM_DEBUG_EXCEPTION("emcore_get_file_pointer failed");
+                               else {
+                                       /* To form list of attachment info - Attachment list followed by inline attachment list */
+                                       current_ai = cnt_info->file;
+
+                                       EM_DEBUG_LOG("current_ai - %p", current_ai);
+
+                                       ai = em_malloc(sizeof(struct attachment_info));
+                                       if (ai == NULL)  {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed...");
+                                               if(err_code)
+                                                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+                                               return NULL;
+                                       }
+
+                                       if ((body->id) || (body->location) || ((body->disposition.type != NULL) && ((body->disposition.type[0] == 'i') || (body->disposition.type[0] == 'I'))))
+                                               ai->type = 1; /* inline contents */
+                                       else
+                                               ai->type = 2; /* attachment */
+
+                                       ai->name                 = EM_SAFE_STRDUP(filename);
+                                       ai->size                 = body->size.bytes;
+                                       ai->content_id           = EM_SAFE_STRDUP(body->id);
+                                       if (emcore_get_content_type_from_mail_bodystruct(body, 512, content_type_buffer) == EMAIL_ERROR_NONE)
+                                               ai->attachment_mime_type = EM_SAFE_STRDUP(content_type_buffer);
+
+#ifdef __ATTACHMENT_OPTI__
+                                       ai->encoding = body->encoding;
+                                       if (body->sparep)
+                                               ai->section = EM_SAFE_STRDUP(body->sparep);
+
+                                       EM_DEBUG_LOG("Encoding - %d  Section No - %s ", ai->encoding, ai->section);
+#endif
+
+                                       EM_DEBUG_LOG("Type[%d], Name[%s], Path[%s] ", ai->type, ai->name, ai->save);
+                                       if (body->type == TYPEAPPLICATION)  {
+                                               if (!strcasecmp(body->subtype, MIME_SUBTYPE_DRM_OBJECT))
+                                                       ai->drm = EMAIL_ATTACHMENT_DRM_OBJECT;
+                                               else if (!strcasecmp(body->subtype, MIME_SUBTYPE_DRM_RIGHTS))
+                                                       ai->drm = EMAIL_ATTACHMENT_DRM_RIGHTS;
+                                               else if (!strcasecmp(body->subtype, MIME_SUBTYPE_DRM_DCF))
+                                                       ai->drm = EMAIL_ATTACHMENT_DRM_DCF;
+                                               else if (!strcasecmp(body->subtype, "pkcs7-mime"))
+                                                       cnt_info->grab_type = cnt_info->grab_type | GRAB_TYPE_ATTACHMENT;
+                                       }
+
+                                       if (current_ai == NULL) {
+                                               cnt_info->file = ai;
+                                       } else {
+                                               while(current_ai->next != NULL)
+                                                       current_ai = current_ai->next;
+
+                                               current_ai->next = ai;
+                                       }
+                               }
+                       }
+
+                       /* if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT */
+                       if (cnt_info->grab_type & GRAB_TYPE_ATTACHMENT) {
+                               if (((body->disposition.type != NULL) && ((body->disposition.type[0] == 'a') || (body->disposition.type[0] == 'A'))) && (cnt_info->file != NULL)) {
+                                       PARAMETER *param = NULL;
+                                       char *fn = NULL;
+
+                                       param = body->parameter;
+
+                                       while (param)  {
+                                               if (!strcasecmp(param->attribute, "NAME")) {
+                                                       fn = EM_SAFE_STRDUP(param->value);
+                                                       break;
+                                               }
+                                               if (!strcasecmp(param->attribute, "FILENAME")) {
+                                                       fn = EM_SAFE_STRDUP(param->value);
+                                                       break;
+                                               }
+                                               param = param->next;
+                                       }
+                                       if ((fn != NULL)&& (!strcmp(fn, cnt_info->file->name)) && (body->size.bytes == cnt_info->file->size)) /*  checks to zero in on particular attachmen */ {
+                                               section_list = emcore_add_node(section_list, body);
+                                               if (section_list == NULL) {
+                                                       EM_DEBUG_EXCEPTION("adding node to section list failed");
+                                                       if(err_code)
+                                                               *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+                                                       EM_SAFE_FREE(fn);
+                                                       return NULL;
+                                               }
+                                               else {
+                                                       EM_SAFE_FREE(fn);
+                                                       EM_DEBUG_FUNC_END("section_list [%p]", section_list);
+                                                       return section_list; /* single attachment download, so if a match found break the recursion */
+                                               }
+                                       }
+                                       EM_SAFE_FREE(fn);
+                               }
+                       }
+                       else {
+                               /* get a section list which has only plain, html and inline */
+                               if (!((body->disposition.type != NULL) && ((body->disposition.type[0] == 'a') || (body->disposition.type[0] == 'A'))))/*  if the body not an attachmen */ {
+                                       section_list = emcore_add_node(section_list, body);
+                                       if (section_list == NULL) {
+                                               EM_DEBUG_EXCEPTION("adding node to section list failed");
+                                               if(err_code)
+                                                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+                                               return NULL;
+                                       }
+                               }
+                       }
+
+                       break;
+
+               default:
+                       break;
+       }
+
+       if(section_list == NULL && err_code != NULL) {
+               *err_code = EMAIL_ERROR_ON_PARSING;
+       }
+
+       EM_DEBUG_FUNC_END("section_list [%p]", section_list);
+       return section_list;
+}
+
+INTERNAL_FUNC int emcore_get_body_part_list_full(MAILSTREAM *stream, int msg_uid, int account_id, int mail_id, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST *section_list, int event_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       if (!stream || !body || !cnt_info)  {
+               EM_DEBUG_EXCEPTION("stream[%p], msg_uid[%d], body[%p], cnt_info[%p]", stream, msg_uid, body, cnt_info);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return FAILURE;
+       }
+       section_list = emcore_get_body_full(stream, msg_uid, body, cnt_info, err_code, section_list);
+
+       if (section_list == NULL) {
+               /*  assumed at least one body part exist */
+               if(err_code)
+                       EM_DEBUG_EXCEPTION("emcore_get_body_full failed [%d]", *err_code);
+               else
+                       EM_DEBUG_EXCEPTION("emcore_get_body_full failed");
+               return FAILURE;
+       }
+
+       if (emcore_get_body_part_imap_full(stream, msg_uid, account_id, mail_id, section_list, cnt_info, err_code, event_handle) < 0) {
+               EM_DEBUG_EXCEPTION("emcore_get_body_part_imap_full failed");
+               emcore_free_section_list(section_list);
+               return FAILURE;
+       }
+       emcore_free_section_list(section_list);
+       return SUCCESS;
+}
+
+static int emcore_write_response_into_file(char *filename, char *write_mode, char *encoded, int encoding_type, char *subtype, int account_id, int mail_id, int *err)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int temp_decoded_len = 0;
+       int inline_support = 0;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int not_found = true;
+       int encoded_len = 0;
+       int written_bytes = 0;
+       unsigned long decoded_len = 0;
+       char *decoded = NULL;
+       char *decoded_temp = NULL;
+       char save_file_name[MAX_PATH+1] = {0, };
+       char html_cid_path[MAX_PATH+1] = {0, };
+       FILE *fp = NULL;
+       PARAMETER *param = NULL;
+       PARAMETER *param1 = NULL;
+
+
+       if (!encoded || !filename || !write_mode) {
+               EM_DEBUG_EXCEPTION("Invalid Param ");
+               if( err ) *err = EMAIL_ERROR_INVALID_PARAM;  /* prevent 28347 */
+               return false;
+       }
+
+
+       EM_DEBUG_LOG("Encoded buffer length [%d]", EM_SAFE_STRLEN(encoded));
+       encoded_len = EM_SAFE_STRLEN(encoded);
+
+       EM_DEBUG_LOG("encoding_type [%d]", encoding_type);
+       switch (encoding_type)  {
+               case ENCQUOTEDPRINTABLE:   {
+                       unsigned char *orignal = (unsigned char *)g_strdup_printf("%s\r\n", encoded);
+                       decoded = (char *)rfc822_qprint(orignal, encoded_len + 2, &decoded_len);
+                       g_free(orignal);
+                       break;
+               }
+
+               case ENCBASE64:
+                       decoded = (char *)rfc822_base64((unsigned char *)encoded, encoded_len, &decoded_len);
+                       break;
+
+               default:  {
+                       unsigned char *orignal = (unsigned char *)g_strdup_printf("%s\r\n", encoded);
+                       decoded = em_malloc(encoded_len + 3); /*prevent 28347*/
+                       if(!decoded) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+                       memcpy(decoded, orignal, encoded_len + 3);
+                       decoded_len = encoded_len + 2;
+                       g_free(orignal);
+               }
+               break;
+       }
+
+       if (decoded != NULL)  {
+               EM_DEBUG_LOG("Decoded Length [%d] " , decoded_len);
+               EM_DEBUG_LOG("filename [%s] " , filename);
+
+               if (!(fp = fopen(filename, write_mode)))  {
+                       EM_DEBUG_EXCEPTION("fopen failed - %s", filename);
+                       error = EMAIL_ERROR_SYSTEM_FAILURE; /*prevent 28347*/
+                       goto FINISH_OFF;
+               }
+
+               if (subtype && subtype[0] == 'H')  {
+                       char body_inline_id[512] = {0};
+
+                       while (strstr(decoded, "cid:"))   {
+                               EM_DEBUG_LOG("Found cid:");
+                               not_found = true;
+                               if (g_inline_count) {
+                                       BODY *body_inline = NULL;
+                                       int   inline_count = 0;
+                                       char *decoded_content_id = NULL;
+                                       while (inline_count < g_inline_count && g_inline_list[inline_count]) {
+                                               EM_DEBUG_LOG("inline_count [%d], g_inline_count [%d]", inline_count, g_inline_count);
+                                               body_inline = g_inline_list[inline_count];
+                                               param = body_inline->disposition.parameter;
+                                               param1 = body_inline->parameter;
+
+                                               memset(body_inline_id, 0x00, 512);
+
+                                               if (body_inline->id && EM_SAFE_STRLEN(body_inline->id) > 0) { /*prevent 27454*/
+                                                       EM_DEBUG_LOG("body_inline->id - %s", body_inline->id);
+                                                       EM_DEBUG_LOG("param - %p param1 - %p", param, param1);
+                                                       decoded_content_id = strstr(decoded, "cid:");
+
+                                                       if (body_inline->id[0] == '<')
+                                                               memcpy(body_inline_id, body_inline->id + 1, EM_SAFE_STRLEN(body_inline->id) - 2);
+                                                       else
+                                                               memcpy(body_inline_id, body_inline->id , EM_SAFE_STRLEN(body_inline->id));
+
+                                                       EM_DEBUG_LOG("Inline body_inline_id [%s]  ", body_inline_id);
+
+                                                       if ((param || param1) && 0 == strncmp(body_inline_id , decoded_content_id + strlen("cid:"), EM_SAFE_STRLEN(body_inline_id))) {
+                                                               EM_DEBUG_LOG(" Inline CID Found ");
+
+                                                               memset(save_file_name, 0x00, MAX_PATH);
+                                                               memset(html_cid_path, 0x00, MAX_PATH);
+
+                                                               /*  Finding 'filename' attribute from content inf */
+                                                               emcore_get_file_pointer(body_inline, true, save_file_name, NULL, &error);
+
+                                                               if (EM_SAFE_STRLEN(save_file_name) > 0) {
+                                                                       /*  Content ID will be replaced with its file name in html */
+                                                                       memcpy(html_cid_path, decoded_content_id , strlen("cid:") + EM_SAFE_STRLEN(body_inline_id));
+
+                                                                       EM_DEBUG_LOG("Replacing %s with %s ", html_cid_path, save_file_name);
+                                                                       if ((decoded_temp = em_replace_string(decoded, html_cid_path, save_file_name))) {
+                                                                               EM_SAFE_FREE(decoded);
+                                                                               decoded = decoded_temp;
+                                                                               decoded_len = EM_SAFE_STRLEN(decoded);
+                                                                               EM_DEBUG_LOG("Decoded Length [%d] ", decoded_len);
+                                                                               inline_support = 1;
+                                                                               not_found = false;
+                                                                               /* only_body_download = false */
+                                                                               break;
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                               inline_count++;
+                                       }
+
+                               }
+
+
+                               if (not_found) {
+                                       EM_DEBUG_LOG("not_found is true");
+                                       memset(body_inline_id, 0x00, sizeof(body_inline_id));
+                                       decoded_temp = em_replace_string_with_split_file_path(decoded, "cid:", body_inline_id);
+                                       if (decoded_temp) {
+                                               /* only_body_download = false */
+                                               /* EM_DEBUG_LOG(">>>> decoded_temp 2 [ %s ] ", decoded_temp) */
+                                               EM_SAFE_FREE(decoded);
+                                               decoded = decoded_temp;
+                                               temp_decoded_len = EM_SAFE_STRLEN(body_inline_id);
+                                               decoded_len = EM_SAFE_STRLEN(decoded);
+                                               EM_DEBUG_LOG("Decoded Length [%d] ", decoded_len);
+                                               inline_support = 1;
+                                       }
+                               }
+                       }
+               }
+
+               EM_DEBUG_LOG("Trying to fwrite. decoded_len [%d]", decoded_len);
+
+               if (decoded_len > 0 && fwrite(decoded, decoded_len, 1, fp) == 0)  {
+                       EM_DEBUG_EXCEPTION("Error Occured while writing. fwrite(\"%s\") failed. decoded_len [%d], written_bytes [%d] ", decoded, decoded_len, written_bytes);
+                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("fwrite succeed");
+       }
+       else {
+               EM_DEBUG_EXCEPTION("Error Occured while decoding ");
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err)
+               *err = error;
+
+       EM_SAFE_FREE(decoded);
+
+       if (fp != NULL)
+               fclose(fp);
+
+       EM_DEBUG_FUNC_END();
+
+       return ret;
+}
+
+
+static BODY *emcore_select_body_structure_from_section_list(PARTLIST *section_list,  char *section)
+{
+       PARTLIST *temp = section_list;
+       BODY *body = NULL;
+
+       while (temp != NULL) {
+               body = temp->body;
+               if (!strcmp(section, body->sparep))
+                       return body;
+               temp = (PARTLIST *)temp->next;
+       }
+       return body;
+}
+
+
+#define MAX_WRITE_BUFFER_SIZE 0 /* should be tuned */
+
+static int imap_mail_write_body_to_file(MAILSTREAM *stream, int account_id, int mail_id, int is_attachment, char *filepath, int uid, char *section, int encoding, int *decoded_total, char *section_subtype, int *err_code)
+{
+       EM_PROFILE_BEGIN(imapMailWriteBodyToFile);
+       EM_DEBUG_FUNC_BEGIN("stream[%p], filepath[%s], uid[%d], section[%s], encoding[%d], decoded_total[%p], err_code[%p]", stream, filepath, uid, section, encoding, decoded_total, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       FILE *fp = NULL;
+       IMAPLOCAL *imaplocal = NULL;
+       char tag[16], command[64];
+       char *response = NULL;
+       char *decoded = NULL;
+       int body_size = 0, total = 0;
+       char *file_id = NULL;
+       char server_uid[129] = { 0, };
+       char *filename = NULL;
+       int server_response_yn = 0;
+       int write_flag = false;
+       unsigned char encoded[DOWNLOAD_MAX_BUFFER_SIZE] = {0, };
+       unsigned char test_buffer[LOCAL_MAX_BUFFER_SIZE] = {0, };
+       int flag_first_write = true;
+
+       if (!stream || !filepath || !section)  {
+               EM_DEBUG_EXCEPTION("stream[%p], filepath[%s], uid[%d], section[%s], encoding[%d], decoded_total[%p]", stream, filepath, uid, section, encoding, decoded_total);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       FINISH_OFF_IF_CANCELED;
+
+       if (!(fp = fopen(filepath, "wb+")))  {
+               EM_DEBUG_EXCEPTION("fopen failed - %s", filepath);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;               /* EMAIL_ERROR_UNKNOWN */
+               goto FINISH_OFF;
+       }
+
+       imaplocal = stream->local;
+
+       if (!imaplocal->netstream)  {
+               EM_DEBUG_EXCEPTION("invalid IMAP4 stream detected... %p", imaplocal->netstream);
+               err = EMAIL_ERROR_INVALID_STREAM;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG(" next_decode_string = false  ");
+       next_decode_string = false;
+
+       memset(tag, 0x00, sizeof(tag));
+       memset(command, 0x00, sizeof(command));
+
+       SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+       SNPRINTF(command, sizeof(command), "%s UID FETCH %d BODY.PEEK[%s]\015\012", tag, uid, section);
+
+       EM_DEBUG_LOG("[IMAP4] >>> [%s]", command);
+
+       /*  send command  :  get msgno/uid for all messag */
+       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command)))  {
+               EM_DEBUG_EXCEPTION("net_sout failed...");
+               err = EMAIL_ERROR_CONNECTION_BROKEN;
+               goto FINISH_OFF;
+       }
+
+       while (imaplocal->netstream)  {
+               char *p = NULL;
+               char *s = NULL;
+
+               if (!emcore_check_thread_status())  {
+                       EM_DEBUG_LOG("Canceled...");
+                       /*      Is it realy required ? It might cause crashes.
+                       if (imaplocal->netstream)
+                               net_close (imaplocal->netstream);
+                       */
+                       imaplocal->netstream = NULL;
+                       err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               /*  receive respons */
+               if (!(response = net_getline(imaplocal->netstream)))  {
+                       EM_DEBUG_EXCEPTION("net_getline failed...");
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       goto FINISH_OFF;
+               }
+#ifdef FEATURE_CORE_DEBUG
+               EM_DEBUG_LOG("recv[%s]", response);
+#endif
+
+               write_flag = false;
+               if (response[0] == '*' && !server_response_yn)  {               /*  start of respons */
+
+                       if ((p = strstr(response, "BODY[")) /* || (p = strstr(s + 1, "BODY["))*/) {
+                               server_response_yn = 1;
+                               p += strlen("BODY[");
+                               s = p;
+
+                               while (*s != ']')
+                                       s++;
+
+                               *s = '\0';
+
+                               if (strcmp(section, p))  {
+                                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                                       goto FINISH_OFF;
+                               }
+
+                               if ((p = strstr(s+1, " {")))  {
+                                       p += strlen(" {");
+                                       s = p;
+
+                                       while (isdigit(*s))
+                                               s++;
+
+                                       *s = '\0';
+
+                                       body_size = atoi(p);
+                               }
+                               else {  /*  no body length is replied */
+                                       if ((p = strstr(s+1, " \""))) { /*  seek the termination of double quot */
+                                               char *t = NULL;
+                                               p += strlen(" \"");
+                                               if ((t = strstr(p, "\""))) {
+                                                       body_size = t - p;
+                                                       *t = '\0';
+                                                       EM_DEBUG_LOG("Body  :  start[%p] end[%p]  :  body[%s]", p, t, p);
+                                                       /*  need to decod */
+                                                       EM_SAFE_FREE(response);
+                                                       response = EM_SAFE_STRDUP(p);
+                                                       write_flag = true;
+                                               }
+                                               else {
+                                                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                                                       goto FINISH_OFF;
+                                               }
+                                       }
+                                       else {
+                                               err = EMAIL_ERROR_INVALID_RESPONSE;
+                                               goto FINISH_OFF;
+                                       }
+                               }
+
+                               /* sending progress noti to application.
+                               1. mail_id
+                               2. file_id
+                               3. bodysize
+                               */
+                               parse_file_path_to_filename(filepath, &file_id);
+
+                               filename = file_id;
+                               sprintf(server_uid, "%d", uid);
+
+                               EM_DEBUG_LOG("file_id [%s]", file_id);
+                               EM_DEBUG_LOG("filename [%p]-[%s]", filename, filename);
+                               EM_DEBUG_LOG("body_size [%d]", body_size);
+                               EM_DEBUG_LOG("server_uid [%s]", server_uid);
+                               EM_DEBUG_LOG("mail_id [%d]", mail_id);
+
+                               if (is_attachment) {
+                                       EM_DEBUG_LOG("Attachment number [%d]", is_attachment);
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, filename, is_attachment, 0))
+                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+                                       _imap4_download_noti_interval_value =  body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                                       _imap4_total_body_size = body_size;
+                               }
+                               else {
+                                       if (multi_part_body_size) {
+                                               EM_DEBUG_LOG("Multipart body size is [%d]", multi_part_body_size);
+                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, filename, multi_part_body_size, 0))
+                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
+                                               _imap4_download_noti_interval_value =  multi_part_body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                                               /*  _imap4_total_body_size should be set before calling this functio */
+                                               /* _imap4_total_body_size */
+                                       }
+                                       else {
+                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, filename, body_size, 0))
+                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                               _imap4_download_noti_interval_value =  body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                                               _imap4_total_body_size = body_size;
+                                       }
+                               }
+                               if (_imap4_download_noti_interval_value > DOWNLOAD_NOTI_INTERVAL_SIZE) {
+                                       _imap4_download_noti_interval_value = DOWNLOAD_NOTI_INTERVAL_SIZE;
+                               }
+                               if (body_size < DOWNLOAD_MAX_BUFFER_SIZE) {
+                                       if (net_getbuffer (imaplocal->netstream, (long)body_size, (char *)encoded) <= 0) {
+                                               EM_DEBUG_EXCEPTION("net_getbuffer failed...");
+                                               err = EMAIL_ERROR_NO_RESPONSE;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       if (!emcore_write_response_into_file(filepath, "wb+", (char *)encoded, encoding, section_subtype, account_id, mail_id, &err)) {
+                                               EM_DEBUG_EXCEPTION("write_response_into_file failed [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+
+                                       total = EM_SAFE_STRLEN((char *)encoded);
+                                       EM_DEBUG_LOG("total = %d", total);
+                                       EM_DEBUG_LOG("write_response_into_file successful %s.....", filename);
+
+                                       if (((_imap4_last_notified_body_size  + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
+                                                               || (_imap4_received_body_size >= _imap4_total_body_size))               /*  100  */ {
+                                               /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
+                                               int gap = 0;
+                                               if (total > body_size)
+                                                       gap = total - body_size;
+                                               _imap4_received_body_size -= gap;
+                                               _imap4_last_notified_body_size = _imap4_received_body_size;
+
+                                               if(body_size > 0)
+                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Encoded[%d] / [%d] = %d %% Completed. -- Total Decoded[%d]", total, body_size, 100*total/body_size, total);
+
+                                               if(_imap4_total_body_size > 0)
+                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, 100*_imap4_received_body_size/_imap4_total_body_size);
+
+                                               if (is_attachment) {
+                                                       if (_imap4_total_body_size && !emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, filename, is_attachment, 100 *_imap4_received_body_size / _imap4_total_body_size))
+                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+                                               }
+                                               else {
+                                                       if (multi_part_body_size) {
+                                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
+                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
+                                                       }
+                                                       else {
+                                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
+                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                                       }
+                                               }       /*  if (is_attachment) .. else .. */
+                                       }
+                               }
+                               else {
+                                       int temp_body_size = body_size;
+                                       int x = 0;
+
+                                       if (encoding == ENCBASE64)
+                                               x = (sizeof(encoded)/78) *78; /*  to solve base64 decoding pro */
+                                       else
+                                               x = sizeof(encoded)-1;
+
+                                       memset(test_buffer, 0x00, sizeof(test_buffer));
+                                       while (temp_body_size && (total <body_size)) {
+
+                                               memset(test_buffer, 0x00, sizeof(test_buffer));
+                                               while ((total != body_size) && temp_body_size && ((EM_SAFE_STRLEN((char *)test_buffer) + x) < sizeof(test_buffer))) {
+                                                       memset(encoded, 0x00, sizeof(encoded));
+
+                                                       if (net_getbuffer (imaplocal->netstream, (long)x, (char *)encoded) <= 0) {
+                                                               EM_DEBUG_EXCEPTION("net_getbuffer failed...");
+                                                               err = EMAIL_ERROR_NO_RESPONSE;
+                                                               goto FINISH_OFF;
+                                                       }
+
+                                                       temp_body_size = temp_body_size - x;
+                                                       strncat((char *)test_buffer, (char *)encoded, EM_SAFE_STRLEN((char *)encoded));
+                                                       total = total + x;
+                                                       _imap4_received_body_size += EM_SAFE_STRLEN((char *)encoded);
+
+                                                       if ( !(temp_body_size/x) && temp_body_size%x)
+                                                               x = temp_body_size%x;
+
+                                                       if (((_imap4_last_notified_body_size  + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
+                                                               || (_imap4_received_body_size >= _imap4_total_body_size))               /*  100  */ {
+                                                               /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
+                                                               int gap = 0;
+                                                               if (total > body_size)
+                                                                       gap = total - body_size;
+                                                               _imap4_received_body_size -= gap;
+                                                               _imap4_last_notified_body_size = _imap4_received_body_size;
+
+                                                               /* EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Encoded[%d] / [%d] = %d %% Completed. -- Total Decoded[%d]", total, body_size, 100*total/body_size, total) */
+                                                               EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, 100*_imap4_received_body_size/_imap4_total_body_size);
+
+                                                               if (is_attachment) {
+                                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, filename, is_attachment, 100 *_imap4_received_body_size / _imap4_total_body_size))
+                                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+                                                               }
+                                                               else {
+                                                                       if (multi_part_body_size) {
+                                                                               /* EM_DEBUG_LOG("DOWNLOADING..........  :  Multipart body size is [%d]", multi_part_body_size) */
+                                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
+                                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
+                                                                       }
+                                                                       else {
+                                                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, filename, _imap4_total_body_size, _imap4_received_body_size))
+                                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                                                       }
+                                                               }       /*  if (is_attachment) .. else .. */
+                                                       }
+
+
+               }
+
+                                                       if (flag_first_write == true) {
+                                                               if (!emcore_write_response_into_file(filepath, "wb+", (char *)test_buffer, encoding, section_subtype, account_id, mail_id, &err)) {
+                                                                       EM_DEBUG_EXCEPTION("write_response_into_file %s failed [%d]", filepath, err);
+                                                                       goto FINISH_OFF;
+                                                               }
+                                                               flag_first_write = false;
+                                                       }
+                                                       else {
+                                                               if (!emcore_write_response_into_file(filepath, "ab+", (char *)test_buffer, encoding, section_subtype, account_id, mail_id, &err)) /*  append */ {
+                                                                       EM_DEBUG_EXCEPTION("write_response_into_file %s failed [%d]", filepath, err);
+                                                                       goto FINISH_OFF;
+                                                               }
+                                                       }
+                                                       EM_DEBUG_LOG("%d has been written", EM_SAFE_STRLEN((char *)test_buffer));
+                                                       /*  notif */
+                                               }
+                               }
+
+                       }
+                       else  {
+                               err = EMAIL_ERROR_INVALID_RESPONSE;
+                               goto FINISH_OFF;
+                       }
+
+               }
+               else if (!strncmp(response, tag, EM_SAFE_STRLEN(tag)))  {               /*  end of respons */
+                       if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2))  {
+                               EM_SAFE_FREE(response);
+                       }
+                       else  {         /*  'NO' or 'BAD */
+                               err = EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE;
+                               goto FINISH_OFF;
+                       }
+
+                       break;
+               }
+               else if (!strcmp(response, ")"))  {
+                       /*  The end of response which contains body informatio */
+                       write_flag = false;
+               }
+
+       }       /*  while (imaplocal->netstream)  */
+
+       if (decoded_total != NULL)
+               *decoded_total = total;
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(decoded);
+       EM_SAFE_FREE(response);
+
+       if (fp != NULL)
+               fclose(fp);
+
+       if (ret == false) {     /*  delete temp fil */
+               struct stat temp_file_stat;
+               if (filepath &&  stat(filepath, &temp_file_stat) == 0)
+                       remove(filepath);
+       }
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_PROFILE_END(imapMailWriteBodyToFile);
+
+       return ret;
+}
+
+static int emcore_get_body_part_imap_full(MAILSTREAM *stream, int msg_uid, int account_id, int mail_id, PARTLIST *section_list, struct _m_content_info *cnt_info, int *err_code, int event_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, section_list, cnt_info, err_code);
+
+       int err = EMAIL_ERROR_NONE;
+       char sections[IMAP_MAX_COMMAND_LENGTH] = { 0, };
+       IMAPLOCAL *imaplocal = NULL;
+       char tag[16] = { 0, }, command[IMAP_MAX_COMMAND_LENGTH] = { 0, };
+       char section[16] = {0};
+       char *response = NULL;
+       BODY *body = NULL;
+       int server_response_yn = 0;
+       int body_size = 0;
+       char *buf = NULL;
+       char filename[512] = {0, };
+       int return_value = 0 ;
+       int encoding = 0;
+       unsigned char encoded[DOWNLOAD_MAX_BUFFER_SIZE] = {0};
+       unsigned char test_buffer[LOCAL_MAX_BUFFER_SIZE] = {0};
+       struct attachment_info *ai = NULL;
+       int i = 0;
+       int total = 0;
+       int flag_first_write = 1;
+       int imap4_total_body_download_progress = 0, progress = 0;
+
+       if (!(imaplocal = stream->local) || !imaplocal->netstream || !section_list || !cnt_info)  {
+               EM_DEBUG_EXCEPTION("invalid IMAP4 stream detected...");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return_value = -1;
+               goto FINISH_OFF;
+       }
+
+       if (section_list != NULL) {
+               PARTLIST *temp = section_list;
+
+               if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT) {
+                       /*  to download attachment */
+                       body = temp->body;
+                       if (body->sparep != NULL)  {
+                               snprintf(sections, sizeof(sections), "BODY.PEEK[%s]", (char *)body->sparep);
+                       }
+                       else {
+                               EM_DEBUG_EXCEPTION("body->sparep can not be null. ");
+                               return_value = -1;
+                               goto FINISH_OFF;
+
+                       }
+               }
+               else {
+                       while (temp != NULL) {
+                               char t[64] = {0};
+                               body = temp->body;
+
+                               if ((body->type == TYPETEXT)  || (body->id != NULL) || ((body->disposition.type != NULL) && ((body->disposition.type[0] == 'i') || (body->disposition.type[0] == 'I')))) {
+                                       snprintf(t, sizeof(t), "BODY.PEEK[%s] ", (char *)body->sparep);         /*  body parts seperated by period */
+                                       strcat(sections, t);
+                               }
+                               temp = (PARTLIST *)temp->next;
+                       }
+               }
+       }
+
+       if ((EM_SAFE_STRLEN(sections) == (sizeof(sections)-1)) || (EM_SAFE_STRLEN(sections) == 0)) {
+                       EM_DEBUG_EXCEPTION(" Too many body parts or nil. IMAP command may cross 1000bytes.");
+                       return_value = -1;
+                       goto FINISH_OFF;
+               }
+
+       if (sections[EM_SAFE_STRLEN(sections)-1] == ' ') {
+               sections[EM_SAFE_STRLEN(sections)-1] = '\0';
+       }
+
+       EM_DEBUG_LOG("sections <%s>", sections);
+
+       SNPRINTF(tag, sizeof(tag), "%08lx", 0xffffffff & (stream->gensym++));
+       SNPRINTF(command, sizeof(command), "%s UID FETCH %d (%s)\015\012", tag, msg_uid, sections);
+       EM_DEBUG_LOG("command %s", command);
+
+       if (EM_SAFE_STRLEN(command) == (sizeof(command)-1)) {
+               EM_DEBUG_EXCEPTION("Too many body parts. IMAP command will fail.");
+               return_value = -1;
+               goto FINISH_OFF;
+       }
+
+       /*  send command  :  get msgno/uid for all message */
+       if (!net_sout(imaplocal->netstream, command, (int)EM_SAFE_STRLEN(command)))  {
+               EM_DEBUG_EXCEPTION("net_sout failed...");
+               err = EMAIL_ERROR_CONNECTION_BROKEN;
+               return_value = -1;
+               goto FINISH_OFF;
+       }
+       while (imaplocal->netstream)  {
+
+               /*  receive respons */
+               if (!(response = net_getline(imaplocal->netstream)))  {
+                       EM_DEBUG_EXCEPTION("net_getline failed...");
+                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                       return_value = -1;
+                       goto FINISH_OFF;
+               }
+
+               if (strstr(response, "BODY[")) {
+
+                       if (!server_response_yn)                /*  start of response */ {
+                               if (response[0] != '*') {
+                                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                                       EM_DEBUG_EXCEPTION("Start of response doesn't contain *");
+                                       return_value = -1;
+                                       goto FINISH_OFF;
+                               }
+                               server_response_yn = 1;
+                       }
+
+                       flag_first_write = 1;
+                       total = 0;
+                       memset(encoded, 0x00, sizeof(encoded));
+
+                       if (emcore_get_section_body_size(response, section, &body_size)<0) {
+                               EM_DEBUG_EXCEPTION("emcore_get_section_body_size failed [%d]", err);
+                               err = EMAIL_ERROR_INVALID_RESPONSE;
+                               return_value = -1;
+                               goto FINISH_OFF;
+                       }
+                       EM_DEBUG_LOG("body_size-%d", body_size);
+
+                       /*  get body from seciton_list */
+                       if ((body = emcore_select_body_structure_from_section_list(section_list, section)) == NULL) {
+                               EM_DEBUG_EXCEPTION("emcore_select_body_structure_from_section_list failed [%d]", err);
+                               err = EMAIL_ERROR_INVALID_RESPONSE;
+                               return_value = -1;
+                               goto FINISH_OFF;
+                       }
+                       encoding = body->encoding;
+
+                       /* if (emcore_get_file_pointer(account_id, mail_id, body, buf, cnt_info , err)<0) {
+                               EM_DEBUG_EXCEPTION("emcore_get_file_pointer failed [%d]", err);
+                               goto FINISH_OFF;
+                       }*/
+
+                       if (!emcore_get_temp_file_name(&buf, &err))  {
+                               EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       EM_DEBUG_LOG("buf :  %s", buf);
+
+                       /*  notifying UI start */
+                       /*  parse_file_path_to_filename(buf, &file_id);                 */
+                       /*  EM_DEBUG_LOG(">>>> filename - %p >>>>>>", file_id) */
+
+                       if (body->type == TYPETEXT && body->subtype && (!body->disposition.type || (body->disposition.type && (body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I')))) {
+                               if (body->subtype[0] == 'H')
+                                       cnt_info->text.html = buf;
+                               else
+                                       cnt_info->text.plain = buf;
+
+                               PARAMETER *param = NULL;
+
+                               param = body->parameter;
+
+                               while (param)  {
+                                       if (!strcasecmp(param->attribute, "CHARSET"))  {
+                                               cnt_info->text.plain_charset = EM_SAFE_STRDUP(param->value);
+                                               break;
+                                       }
+                                       param = param->next;
+                               }
+                       }
+                       else if (body->subtype && (body->id || body->location || body->disposition.type)) { /*prevent 23712*/ /*refactoring : body->subtype*/
+
+                               if (emcore_get_file_pointer(body, false, filename, cnt_info , &err)<0) {
+                                       EM_DEBUG_EXCEPTION("emcore_get_file_pointer failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+
+                               /* Search info from attachment list followed by inline attachment list */
+
+                               ai = cnt_info->file;
+                               EM_DEBUG_LOG("ai - %p ", (ai));
+
+                               /* For Inline content append to the end */
+                               for (i = 1; ai; ai = ai->next, i++) {
+                                       if (ai->save == NULL && (ai->content_id != NULL && EM_SAFE_STRCMP(ai->content_id, body->id) == 0)) {
+                                               EM_DEBUG_LOG("Found matching details ");
+                                               ai->save = buf;
+                                               break;
+                                       }
+                               }
+                       }
+
+                       FINISH_OFF_IF_CANCELED;
+
+                       if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT) {
+                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, buf, cnt_info->file_no, 0))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+
+                               _imap4_download_noti_interval_value =  body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                               _imap4_total_body_size = body_size;
+                       }
+                       else {
+                               if (multi_part_body_size) {
+                                       EM_DEBUG_LOG("Multipart body size is [%d]", multi_part_body_size);
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, buf, multi_part_body_size, 0))
+                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
+
+                                       _imap4_download_noti_interval_value =  multi_part_body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                               }
+                               else {
+                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, buf, body_size, 0))
+                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
+
+                                       _imap4_download_noti_interval_value =  body_size *DOWNLOAD_NOTI_INTERVAL_PERCENT / 100;
+                                       _imap4_total_body_size = body_size;
+                               }
+
+                       }
+
+                       if (_imap4_download_noti_interval_value > DOWNLOAD_NOTI_INTERVAL_SIZE) {
+                               _imap4_download_noti_interval_value = DOWNLOAD_NOTI_INTERVAL_SIZE;
+                       }
+
+                       /* EM_SAFE_FREE(file_id) */
+                       /* notifying UI end */
+
+                       if (body_size < DOWNLOAD_MAX_BUFFER_SIZE) {
+                               if (net_getbuffer (imaplocal->netstream, (long)body_size, (char *)encoded) <= 0) {
+                                       EM_DEBUG_EXCEPTION("net_getbuffer failed...");
+                                       err = EMAIL_ERROR_NO_RESPONSE;
+                                       return_value = -1;
+                                       goto FINISH_OFF;
+                               }
+                               if (!emcore_write_response_into_file(buf, "wb+", (char *)encoded, encoding, body->subtype, account_id, mail_id, &err)) {
+                                       EM_DEBUG_EXCEPTION("write_response_into_file failed [%d]", err);
+                                       return_value = -1;
+                                       goto FINISH_OFF;
+                               }
+
+                               EM_DEBUG_LOG("total = %d", total);
+                               EM_DEBUG_LOG("write_response_into_file successful %s.....", buf);
+
+                               total = _imap4_received_body_size = EM_SAFE_STRLEN((char *)encoded);
+
+                               EM_DEBUG_LOG("_imap4_last_notified_body_size [%d]", _imap4_last_notified_body_size);
+                               EM_DEBUG_LOG("_imap4_download_noti_interval_value [%d]", _imap4_download_noti_interval_value);
+                               EM_DEBUG_LOG("_imap4_received_body_size [%d]", _imap4_received_body_size);
+                               EM_DEBUG_LOG("_imap4_total_body_size [%d] ", _imap4_total_body_size);
+
+                               if (((_imap4_last_notified_body_size  + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
+                                       || (_imap4_received_body_size >= _imap4_total_body_size))               /*  100  */ {
+                                       /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
+                                       int gap = 0;
+
+                                       if (total > body_size)
+                                               gap = total - body_size;
+                                       _imap4_received_body_size -= gap;
+                                       _imap4_last_notified_body_size = _imap4_received_body_size;
+                                       if (_imap4_total_body_size)
+                                               imap4_total_body_download_progress = 100*_imap4_received_body_size/_imap4_total_body_size;
+                                       else
+                                               imap4_total_body_download_progress = _imap4_received_body_size;
+
+                                       EM_DEBUG_LOG("3  :  body_size %d", body_size);
+
+                                       if (body_size)
+                                               progress = 100*total/body_size;
+                                       else
+                                               progress = body_size;
+
+                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Encoded[%d] / [%d] = %d %% Completed. -- Total Decoded[%d]", total, body_size, progress, total);
+                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, imap4_total_body_download_progress);
+
+                                       if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT) {
+                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, buf, cnt_info->file_no, imap4_total_body_download_progress))
+                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+                                       }
+                                       else {
+                                                       if (multi_part_body_size) {
+                                                               /* EM_DEBUG_LOG("DOWNLOADING..........  :  Multipart body size is [%d]", multi_part_body_size) */
+                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
+                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
+                                                       }
+                                                       else {
+                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
+                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                                       }
+                                       }       /*  if (is_attachment) .. else .. */
+                               }
+
+                               EM_DEBUG_LOG("4");
+
+                       }
+                       else {
+                               int temp_body_size = body_size;
+                               int x = 0;
+
+                               if (encoding == ENCBASE64)
+                                       x = (sizeof(encoded)/78) *78; /*  to solve base64 decoding pro */
+                               else
+                                       x = sizeof(encoded)-1;
+
+                               memset(test_buffer, 0x00, sizeof(test_buffer));
+                               while (temp_body_size && (total <body_size)) {
+
+                                       memset(test_buffer, 0x00, sizeof(test_buffer));
+                                       while ((total != body_size) && temp_body_size && ((EM_SAFE_STRLEN((char *)test_buffer) + x) < sizeof(test_buffer))) {
+                                               memset(encoded, 0x00, sizeof(encoded));
+
+                                               if (net_getbuffer (imaplocal->netstream, (long)x, (char *)encoded) <= 0) {
+                                                       EM_DEBUG_EXCEPTION("net_getbuffer failed...");
+                                                       err = EMAIL_ERROR_NO_RESPONSE;
+                                                       return_value = -1;
+                                                       goto FINISH_OFF;
+                                               }
+
+                                               temp_body_size = temp_body_size - x;
+                                               strncat((char *)test_buffer, (char *)encoded, EM_SAFE_STRLEN((char *)encoded));
+                                               total = total + x;
+                                               _imap4_received_body_size += EM_SAFE_STRLEN((char *)encoded);
+
+                                               EM_DEBUG_LOG("total = %d", total);
+
+                                               if ( !(temp_body_size/x) && temp_body_size%x)
+                                                       x = temp_body_size%x;
+
+                                               EM_DEBUG_LOG(" _imap4_last_notified_body_size - %d ", _imap4_last_notified_body_size);
+                                               EM_DEBUG_LOG(" _imap4_download_noti_interval_value - %d ", _imap4_download_noti_interval_value);
+                                               EM_DEBUG_LOG(" _imap4_received_body_size - %d ", _imap4_received_body_size);
+                                               EM_DEBUG_LOG(" _imap4_received_body_size - %d ", _imap4_received_body_size);
+                                               EM_DEBUG_LOG(" _imap4_total_body_size - %d ", _imap4_total_body_size);
+
+                                               if (_imap4_total_body_size)
+                                                       imap4_total_body_download_progress = 100*_imap4_received_body_size/_imap4_total_body_size;
+                                               else
+                                                       imap4_total_body_download_progress = _imap4_received_body_size;
+
+                                               if (((_imap4_last_notified_body_size  + _imap4_download_noti_interval_value) <=  _imap4_received_body_size)
+                                                       || (_imap4_received_body_size >= _imap4_total_body_size))               /*  100  */ {
+                                                       /*  In some situation, total_encoded_len includes the length of dummy bytes. So it might be greater than body_size */
+                                                       int gap = 0;
+                                                       if (total > body_size)
+                                                               gap = total - body_size;
+                                                       _imap4_received_body_size -= gap;
+                                                       _imap4_last_notified_body_size = _imap4_received_body_size;
+
+                                                       progress = 100*total/body_size; /*prevent 40023*/
+
+                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Encoded[%d] / [%d] = %d %% Completed. -- Total Decoded[%d]", total, body_size, progress, total);
+                                                       EM_DEBUG_LOG("DOWNLOADING STATUS NOTIFY  :  Total[%d] / [%d] = %d %% Completed.", _imap4_received_body_size, _imap4_total_body_size, imap4_total_body_download_progress);
+
+                                                       if (cnt_info->grab_type == GRAB_TYPE_ATTACHMENT) {
+                                                               if (!emcore_notify_network_event(NOTI_DOWNLOAD_ATTACH_START, mail_id, buf, cnt_info->file_no, imap4_total_body_download_progress))
+                                                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_ATTACH_START] Failed >>>> ");
+                                                       }
+                                                       else {
+                                                               if (multi_part_body_size) {
+                                                                       /* EM_DEBUG_LOG("DOWNLOADING..........  :  Multipart body size is [%d]", multi_part_body_size) */
+                                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_MULTIPART_BODY, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
+                                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>> ");
+                                                               }
+                                                               else {
+                                                                       if (!emcore_notify_network_event(NOTI_DOWNLOAD_BODY_START, mail_id, buf, _imap4_total_body_size, _imap4_received_body_size))
+                                                                               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_DOWNLOAD_BODY_START] Failed >>>>");
+                                                               }
+                                                       }       /*  if (is_attachment) .. else .. */
+                                               }
+                                       }
+
+                                       if (flag_first_write == 1) {
+                                               if (!emcore_write_response_into_file(buf, "wb+", (char *)test_buffer, encoding, body->subtype, account_id, mail_id, &err)) {
+                                                       EM_DEBUG_EXCEPTION("write_response_into_file %s failed [%d]", buf, err);
+                                                       return_value = -1;
+                                                       goto FINISH_OFF;
+                                               }
+                                               flag_first_write = 0;
+                                       }
+                                       else {
+                                               if (!emcore_write_response_into_file(buf, "ab+", (char *)test_buffer, encoding, body->subtype, account_id, mail_id, &err)) /*  append */ {
+                                                       EM_DEBUG_EXCEPTION("write_response_into_file %s failed [%d]", buf, err);
+                                                       return_value = -1;
+                                                       goto FINISH_OFF;
+                                               }
+                                       }
+                                       EM_DEBUG_LOG("%d has been written", EM_SAFE_STRLEN((char *)test_buffer));
+                               }
+                       }
+               }
+               else if (!strncmp(response, tag, EM_SAFE_STRLEN(tag)))  /*  end of respons */ {
+                       if (!strncmp(response + EM_SAFE_STRLEN(tag) + 1, "OK", 2))
+                               EM_SAFE_FREE(response);
+                       else                    /*  'NO' or 'BAD */ {
+                               err = EMAIL_ERROR_IMAP4_FETCH_UID_FAILURE;
+                               return_value = -1;
+                               goto FINISH_OFF;
+                       }
+
+                       break;
+               }
+               else if (!strcmp(response, ")"))  {
+
+               }
+
+               free(response);
+               response = NULL;
+       }
+
+       return_value = 0;
+
+       FINISH_OFF:
+
+       if (err_code)
+               *err_code = err;
+
+       EM_SAFE_FREE(response);
+
+       return return_value;
+}
+
+static int _find_duplicated_inline_content_file(char *input_source_file_name, struct _m_content_info *input_content_info, bool *output_result)
+{
+       EM_DEBUG_FUNC_BEGIN("input_source_file_name [%p], input_content_info [%p], output_result [%p]", input_source_file_name,input_content_info, output_result);
+       struct attachment_info *cur_attachment_info = NULL;
+       int  err = EMAIL_ERROR_NONE;
+       bool result = false;
+
+       if(!input_source_file_name || !input_content_info || !output_result) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       cur_attachment_info = input_content_info->file;
+
+       while(cur_attachment_info) {
+               if(strcmp(input_source_file_name, cur_attachment_info->name) == 0) {
+                       result = true;
+                       break;
+               }
+               cur_attachment_info = cur_attachment_info->next;
+       }
+
+       *output_result = result;
+
+       EM_DEBUG_FUNC_END("err [%d], result [%d]", err, result);
+       return err;
+}
+
+static int _modify_file_name_string_for_duplicated_inline_content(char *input_source_file_name, struct _m_content_info *input_content_info)
+{
+       EM_DEBUG_FUNC_BEGIN("input_source_file_name [%p], input_content_info [%p]", input_source_file_name,input_content_info);
+       int   err = EMAIL_ERROR_NONE;
+       char  temp_file_name[MAX_PATH] = { 0, };
+       char *file_name = NULL;
+       char *extension = NULL;
+
+       if(!input_source_file_name || !input_content_info) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if ( (err = em_get_file_name_and_extension_from_file_path(input_source_file_name, &file_name, &extension)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("em_get_file_name_and_extension_from_file_path failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(file_name && extension)
+               SNPRINTF(temp_file_name, MAX_PATH, "%s_.%s", file_name, extension);
+       else if(!extension)
+               SNPRINTF(temp_file_name, MAX_PATH, "%s_", file_name);
+
+       EM_SAFE_STRCPY(input_source_file_name, temp_file_name);
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(file_name);
+       EM_SAFE_FREE(extension);
+
+       EM_DEBUG_FUNC_END("err [%d], temp_file_name [%s]", err, temp_file_name);
+       return err;
+}
+
+static int emcore_get_file_pointer(BODY *body, bool input_check_duplicated_file_name, char *output_file_name_string, struct _m_content_info *cnt_info , int *err)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       char *decoded_filename = NULL;
+       char attachment_file_name[MAX_PATH] = { 0, };
+       char attachment_file_name_source[MAX_PATH] = {0, };
+       int error = EMAIL_ERROR_NONE;
+       bool file_name_duplicated = false;
+
+       if ((body->type == TYPETEXT) && (body->disposition.type == NULL)) {
+               EM_DEBUG_LOG("body->type == TYPETEXT");
+               if (!cnt_info) {
+                       EM_DEBUG_EXCEPTION("But, cnt_info is null");
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+               if (body->subtype[0] == 'H') {
+                       if (cnt_info->text.plain_charset != NULL) {
+                               memcpy(output_file_name_string, cnt_info->text.plain_charset, EM_SAFE_STRLEN(cnt_info->text.plain_charset));
+                               strcat(output_file_name_string, HTML_EXTENSION_STRING);
+                       }
+                       else {
+                               memcpy(output_file_name_string, "UTF-8.htm", strlen("UTF-8.htm"));
+                       }
+                       cnt_info->text.html = EM_SAFE_STRDUP(output_file_name_string);
+               }
+               else {
+                       PARAMETER *param = body->parameter;
+                       char charset_string[512];
+
+                       if (emcore_get_attribute_value_of_body_part(param, "CHARSET", charset_string, 512, false, &error)) {
+                               cnt_info->text.plain_charset = EM_SAFE_STRDUP(charset_string);
+                               memcpy(output_file_name_string, cnt_info->text.plain_charset, EM_SAFE_STRLEN(cnt_info->text.plain_charset));
+                       }
+                       else
+                               memcpy(output_file_name_string, "UTF-8", strlen("UTF-8"));
+
+                       cnt_info->text.plain = EM_SAFE_STRDUP(output_file_name_string);
+               }
+
+       }
+       else if ((body->id != NULL) || ((body->disposition.type != NULL) && ((body->disposition.type[0] == 'i') || (body->disposition.type[0] == 'I')))) {
+               /*  body id is exising or disposition type is inline */
+               size_t len = 0;
+               if (body->parameter) /* Get actual name of file */ {
+                       PARAMETER *param_body = body->parameter;
+                       if (!emcore_get_attribute_value_of_body_part(param_body, "NAME", attachment_file_name_source, MAX_PATH, true, &error))
+                               emcore_get_attribute_value_of_body_part(param_body, "CHARSET", attachment_file_name_source, MAX_PATH, true, &error);
+                       if (!emcore_make_attachment_file_name_with_extension(attachment_file_name_source, body->subtype, attachment_file_name, MAX_PATH, &error)) {
+                               EM_DEBUG_EXCEPTION("emcore_make_attachment_file_name_with_extension failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+               }
+               else if (body->disposition.type)  {
+                       PARAMETER *param_disposition = body->disposition.parameter;
+                       EM_DEBUG_LOG("body->disposition.type exist");
+                       emcore_get_attribute_value_of_body_part(param_disposition, "filename", attachment_file_name_source, MAX_PATH, true, &error);
+                       if (!emcore_make_attachment_file_name_with_extension(attachment_file_name_source, body->subtype, attachment_file_name, MAX_PATH, &error)) {
+                               EM_DEBUG_EXCEPTION("emcore_make_attachment_file_name_with_extension failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+               }
+               else {  /*  body id is not null but disposition type is null */
+                       if ((body->id[0] == '<'))
+                               SNPRINTF(attachment_file_name, MAX_PATH, "%s", body->id+1); /*  fname = em_parse_filename(body->id + 1 */
+                       else
+                               SNPRINTF(attachment_file_name, MAX_PATH, "%s", body->id); /*  fname = em_parse_filename(body->id */
+
+                       len = EM_SAFE_STRLEN(attachment_file_name);
+
+                       if ((len > 1) && (attachment_file_name[len-1] == '>'))
+                               attachment_file_name[len - 1] = '\0';
+                       decoded_filename = emcore_decode_rfc2047_text(attachment_file_name, &error);
+               }
+               EM_DEBUG_LOG("attachment_file_name [%s]", attachment_file_name);
+               if (decoded_filename != NULL)
+                       memcpy(output_file_name_string, decoded_filename, EM_SAFE_STRLEN(decoded_filename));
+               else
+                       memcpy(output_file_name_string, attachment_file_name, EM_SAFE_STRLEN(attachment_file_name));
+
+       }
+       else if (body->disposition.type != NULL) {      /*  disposition type is existing and not inline and body_id is nul */
+               PARAMETER *param = body->parameter;
+               if (!emcore_get_attribute_value_of_body_part(param, "NAME", attachment_file_name, MAX_PATH, true, &error))
+                       emcore_get_attribute_value_of_body_part(param, "FILENAME", attachment_file_name, MAX_PATH, true, &error);
+               memcpy(output_file_name_string, attachment_file_name, EM_SAFE_STRLEN(attachment_file_name));
+       }
+
+       if(input_check_duplicated_file_name) {
+               if ( (error = _find_duplicated_inline_content_file(output_file_name_string, cnt_info, &file_name_duplicated)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("_find_duplicated_inline_content_file failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+
+               if (file_name_duplicated == true) {
+                       if ( ( error = _modify_file_name_string_for_duplicated_inline_content(output_file_name_string, cnt_info)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("_modify_file_name_string_for_duplicated_inline_content failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(decoded_filename);
+
+       if (err)
+               *err = error;
+
+       EM_DEBUG_FUNC_END("output_file_name_string[%s], error [%d]", output_file_name_string, error);
+       return SUCCESS;
+}
+
+
+static PARTLIST *emcore_add_node(PARTLIST *section_list, BODY *body)
+{
+       PARTLIST *temp = (PARTLIST  *)malloc(sizeof(PARTLIST));
+
+       if (temp == NULL) {
+               EM_DEBUG_EXCEPTION("PARTLIST node creation failed");
+               return NULL;
+       }
+       temp->body = body;
+       temp->next = NULL;
+
+       if (section_list == NULL)/*  first node in list */ {
+               section_list = temp;
+       }
+       else/*  has min 1 nod */ {
+               PARTLIST *t = section_list;
+               while (t->next != NULL) /*  go to last nod */ {
+                       t = (PARTLIST *) t->next;
+               }
+               t->next = (PART *)temp;/*  I think this should be PARTLIST, but why this is PART */
+/*
+in imap-2007e/c-client/mail.h
+PARTLIST{
+  BODY *body;
+  PART *next;
+};
+*/
+       }
+       return section_list;
+}
+
+
+static void emcore_free_section_list(PARTLIST *section_list)
+{
+       PARTLIST *temp = NULL;
+
+       while (section_list != NULL) {
+               temp = (PARTLIST *)section_list->next;
+               EM_SAFE_FREE(section_list);
+               section_list = temp;
+       }
+}
+
+static int emcore_get_section_body_size(char *response, char *section, int *body_size)
+{
+       char *p = NULL;
+       char *s = NULL;
+       int size = 0;
+       if ((p = strstr(response, "BODY[")) /* || (p = strstr(s + 1, "BODY["))*/) {
+
+                               p += strlen("BODY[");
+                               s = p;
+
+                               while (*s != ']')
+                                       s++;
+
+                               *s = '\0';
+
+                               strcpy(section, p);
+
+               /* if (strcmp(section, p)) {
+                                       err = EMAIL_ERROR_INVALID_RESPONSE;
+                                       goto FINISH_OFF;
+               }*/
+               p = strstr(s+1, " {");
+               if (p)  {
+                       p += strlen(" {");
+                       s = p;
+
+                       while (isdigit(*s))
+                               s++;
+
+                       *s = '\0';
+
+                       size = atoi(p);
+                       *body_size = size;
+
+                       /* sending progress noti to application.
+                       1. mail_id
+                       2. file_id
+                       3. bodysize
+                       */
+
+               }
+               else  {
+                       return FAILURE;
+               }
+       }
+       else  {
+               return FAILURE;
+       }
+       return SUCCESS;
+}
+
+
+static char *em_parse_filename(char *filename)
+{
+       EM_DEBUG_FUNC_BEGIN("filename [%p] ", filename);
+       if (!filename) {
+               EM_DEBUG_EXCEPTION("filename is NULL ");
+               return NULL;
+       }
+
+       char delims[] = "@";
+       char *result = NULL;
+       static char parsed_filename[512] = {0, };
+
+       memset(parsed_filename, 0x00, 512);
+
+       if (!strstr(filename, delims)) {
+               EM_DEBUG_EXCEPTION("FileName does not contain @ ");
+               return NULL;
+       }
+
+       result = strtok(filename, delims);
+
+       if (strcasestr(result, ".bmp") || strcasestr(result, ".jpeg") || strcasestr(result, ".png") || strcasestr(result, ".jpg"))
+               sprintf(parsed_filename + EM_SAFE_STRLEN(parsed_filename), "%s", result);
+    else
+               sprintf(parsed_filename + EM_SAFE_STRLEN(parsed_filename), "%s%s", result, ".jpeg");
+
+       EM_DEBUG_LOG(">>> FileName [ %s ] ", result);
+
+       EM_DEBUG_FUNC_END("parsed_filename [%s] ", parsed_filename);
+       return parsed_filename;
+}
+
+#define CONTENT_TYPE_STRING_IN_MIME_HEAEDER "Content-Type:"
+
+INTERNAL_FUNC int emcore_get_content_type_from_mime_string(char *input_mime_string, char **output_content_type)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mime_string [%p], output_content_type [%p]", input_mime_string, output_content_type);
+
+       int   err = EMAIL_ERROR_NONE;
+       int   temp_mime_header_string_length = 0;
+       char  result_content_type[256] = { 0, };
+       char *temp_mime_header_string = NULL;
+       char *temp_content_type_start = NULL;
+       char *temp_content_type_end = NULL;
+
+       if(input_mime_string == NULL || output_content_type == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       temp_mime_header_string_length = EM_SAFE_STRLEN(input_mime_string);
+       temp_mime_header_string        = input_mime_string;
+
+       EM_DEBUG_LOG("temp_mime_header_string [%s]", temp_mime_header_string);
+
+       temp_content_type_start = strcasestr(temp_mime_header_string, CONTENT_TYPE_STRING_IN_MIME_HEAEDER);
+
+       if(temp_content_type_start == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_DATA");
+               err = EMAIL_ERROR_INVALID_DATA;
+               goto FINISH_OFF;
+       }
+       else {
+               temp_content_type_start += EM_SAFE_STRLEN(CONTENT_TYPE_STRING_IN_MIME_HEAEDER);
+               temp_content_type_end = temp_content_type_start;
+
+               while(temp_content_type_end && temp_content_type_end < (temp_mime_header_string + temp_mime_header_string_length) && *temp_content_type_end != ';')
+                       temp_content_type_end++;
+
+               if(temp_content_type_end && *temp_content_type_end == ';') {
+                       if(temp_content_type_end - temp_content_type_start < 256) {
+                               memcpy(result_content_type, temp_content_type_start, temp_content_type_end - temp_content_type_start);
+                               EM_DEBUG_LOG("result_content_type [%s]", result_content_type);
+                               *output_content_type = EM_SAFE_STRDUP(result_content_type);
+                               em_trim_left(*output_content_type);
+
+                       }
+                       else {
+                               EM_DEBUG_EXCEPTION("temp_content_type_end - temp_content_type_start [%d]", temp_content_type_end - temp_content_type_start);
+                               err = EMAIL_ERROR_DATA_TOO_LONG;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+#define SUBTYPE_STRING_LENGTH 128
+
+INTERNAL_FUNC int emcore_get_content_type_from_mail_bodystruct(BODY *input_body, int input_buffer_length, char *output_content_type)
+{
+       EM_DEBUG_FUNC_BEGIN("input_body [%p], input_buffer_length [%d], output_content_type [%p]", input_body, input_buffer_length, output_content_type);
+       int   err = EMAIL_ERROR_NONE;
+       char  subtype_string[SUBTYPE_STRING_LENGTH] = { 0 , };
+
+       if(input_body == NULL || output_content_type == NULL || input_buffer_length == 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       EM_SAFE_STRNCPY(subtype_string, input_body->subtype, SUBTYPE_STRING_LENGTH-1); /* prevent 21983 */
+       em_lower_string(subtype_string);
+
+       switch(input_body->type) {
+               case TYPETEXT :
+                       SNPRINTF(output_content_type, input_buffer_length, "text/%s", subtype_string);
+                       break;
+               case TYPEMULTIPART :
+                       SNPRINTF(output_content_type, input_buffer_length, "multipart/%s", subtype_string);
+                       break;
+               case TYPEMESSAGE :
+                       SNPRINTF(output_content_type, input_buffer_length, "message/%s", subtype_string);
+                       break;
+               case TYPEAPPLICATION :
+                       SNPRINTF(output_content_type, input_buffer_length, "application/%s", subtype_string);
+                       break;
+               case TYPEAUDIO :
+                       SNPRINTF(output_content_type, input_buffer_length, "audio/%s", subtype_string);
+                       break;
+               case TYPEIMAGE :
+                       SNPRINTF(output_content_type, input_buffer_length, "image/%s", subtype_string);
+                       break;
+               case TYPEVIDEO :
+                       SNPRINTF(output_content_type, input_buffer_length, "video/%s", subtype_string);
+                       break;
+               case TYPEMODEL :
+                       SNPRINTF(output_content_type, input_buffer_length, "model/%s", subtype_string);
+                       break;
+               case TYPEOTHER :
+                       SNPRINTF(output_content_type, input_buffer_length, "other/%s", subtype_string);
+                       break;
+               default:
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+                       err = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+                       break;
+       }
+
+       EM_DEBUG_LOG("output_content_type [%s]", output_content_type);
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_get_attribute_value_of_body_part(PARAMETER *input_param, char *atribute_name, char *output_value, int output_buffer_length, int with_rfc2047_text, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_param [%p], atribute_name [%s], output_buffer_length [%d], with_rfc2047_text [%d]", input_param, atribute_name, output_buffer_length, with_rfc2047_text);
+       PARAMETER *temp_param = input_param;
+       char *decoded_value = NULL, *result_value = NULL;
+       int ret = false, err = EMAIL_ERROR_NONE;
+
+       if(!output_value) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       memset(output_value, 0, output_buffer_length);
+
+       while (temp_param)  {
+               EM_DEBUG_LOG("temp_param->attribute [%s]", temp_param->attribute);
+               if (!strcasecmp(temp_param->attribute, atribute_name))  {
+                       EM_DEBUG_LOG("temp_param->value [%s]", temp_param->value);
+                       if (temp_param->value) {
+                               if (with_rfc2047_text) {
+                                       decoded_value = emcore_decode_rfc2047_text(temp_param->value, &err);
+                                       if (decoded_value)
+                                               result_value = decoded_value;
+                                       else
+                                               result_value = decoded_value;
+                               }
+                               else
+                                       result_value = temp_param->value;
+                       }
+                       else {
+                               EM_DEBUG_EXCEPTION("EMAIL_ERROR_DATA_NOT_FOUND");
+                               err = EMAIL_ERROR_DATA_NOT_FOUND;
+                               goto FINISH_OFF;
+                       }
+                       EM_DEBUG_LOG("result_value [%s]", result_value);
+                       if(result_value) {
+                               if(output_buffer_length > EM_SAFE_STRLEN(result_value)) {
+                                       strncpy(output_value, result_value, output_buffer_length);
+                                       output_value[EM_SAFE_STRLEN(result_value)] = NULL_CHAR;
+                                       ret = true;
+                               }
+                               else {
+                                       EM_DEBUG_EXCEPTION("buffer is too short");
+                                       err = EMAIL_ERROR_DATA_TOO_LONG;
+                                       goto FINISH_OFF;
+                               }
+                       }
+
+                       break;
+               }
+               temp_param = temp_param->next;
+       }
+
+FINISH_OFF:
+       EM_SAFE_FREE(decoded_value);
+
+       if(err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+/*
+ *download body part of imap mail (body-text and attachment)
+ */
+static int emcore_get_body_part_imap(MAILSTREAM *stream, int account_id, int mail_id, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       int err = EMAIL_ERROR_NONE, ret = -1;
+       struct attachment_info **ai;
+       struct attachment_info *prev_ai = NULL;
+       struct attachment_info *next_ai = NULL;
+       char *savefile = NULL;
+       char *o_data = NULL;
+       char filename[MAX_PATH + 1] = { 0, };
+       char *decoded_filename = NULL;
+       int is_attachment = 0;
+       int o_data_len = 0;
+       char *filename_temp = NULL;
+       char charset_value_buffer[512] = { 0, };
+       char content_type_buffer[512] = { 0, };
+/*  { is_pb */
+       PART *part = NULL;
+       int dec_len;
+       int i = 0;
+       char *sparep = NULL;
+       unsigned short encode = 0;
+       int section_plain = 0;
+       int section_html = 0;
+       int is_pbd = (account_id == 0 && mail_id == 0) ? true  :  false;
+/*   } is_pb */
+
+       EM_DEBUG_LOG("Grab Type [ %d ] ", cnt_info->grab_type);
+
+       /* unknown type */
+       if (body->type > TYPEOTHER)  {  /* unknown type */
+               EM_DEBUG_EXCEPTION("Unknown type.");
+               err = EMAIL_ERROR_NOT_SUPPORTED;
+               goto FINISH_OFF;
+       }
+
+       if (NULL == body->subtype)      {
+               EM_DEBUG_LOG("body->subtype is null. "); /*  not exceptional case */
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return FAILURE;
+       }
+
+       if (is_pbd) {
+               if (!emcore_get_temp_file_name(&o_data, &err) || !o_data)  {
+                       EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed [%d]", err);
+                       if (err_code != NULL)
+                               *err_code = err;
+                       return FAILURE;
+               }
+
+
+               if (body->subtype[0] == 'P')  { /*  Sub type is PLAIN_TEX */
+                       if (cnt_info->text.plain != NULL)
+                               EM_SAFE_FREE(o_data);
+               }
+
+               if (body->type == TYPETEXT && body->subtype &&
+                       (!body->disposition.type || (body->disposition.type && (body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I')))) {
+                       if (body->subtype[0] == 'H')    /*  HTM */
+                               cnt_info->text.html = o_data;
+                       else
+                               cnt_info->text.plain = o_data;
+
+                       memset(charset_value_buffer, 0, 512);
+
+                       if (emcore_get_attribute_value_of_body_part(body->parameter, "CHARSET", charset_value_buffer, 512, true, &err)) {
+                               cnt_info->text.plain_charset = EM_SAFE_STRDUP(charset_value_buffer);
+                               EM_DEBUG_LOG(">>>>> CHARSET [%s] ", filename);
+                       }
+               }
+       } /*  is_pbd */
+
+       if ((body->id) && EM_SAFE_STRLEN(body->id) > 1) {       /* if Content-ID or Content-Location exists, it is inline contents */
+               EM_DEBUG_LOG("body->id exist");
+               size_t len = 0;
+               /*  Get actual name of file - fix for inline images to be stored with actual names and not .jpeg */
+               if (body->parameter)  {
+                       PARAMETER *param1 = body->parameter;
+                       while (param1)  {
+                               EM_DEBUG_LOG("param1->attribute - %s ", param1->attribute);
+                               if (!strcasecmp(param1->attribute, "NAME"))  {  /*  attribute is "NAME" */
+                                       char *extcheck = NULL;
+
+                                       if (param1->value) {
+                                               decoded_filename = emcore_decode_rfc2047_text(param1->value, &err);
+                                               strncpy(filename, decoded_filename, MAX_PATH);
+                                               EM_SAFE_FREE(decoded_filename);
+                                       }
+                                       EM_DEBUG_LOG(">>>>> FILENAME [%s] ", filename);
+                                       extcheck = strchr(filename, '.');
+
+                                       if (extcheck)
+                                               EM_DEBUG_LOG(">>>> Extension Exist in the Attachment [ %s ] ", extcheck);
+                                       else /*  No extension attached , So add the Extension based on the subtyp */ {
+                                               if (body->subtype) {
+                                                       strcat(filename, ".");
+                                                       strcat(filename, body->subtype);
+                                                       EM_DEBUG_LOG(">>>>> FILENAME Identified the Extension [%s] ", filename);
+                                               }
+                                               else
+                                                       EM_DEBUG_EXCEPTION("UnKnown Extesnsion  : _ (");
+
+                                       }
+
+                                       break;
+                               }
+                               param1 = param1->next;
+                       }
+
+               }
+               else if (body->disposition.type)  {
+                       PARAMETER *param = body->disposition.parameter;
+
+                       while (param) {
+                               EM_DEBUG_LOG(">>>>> body->disposition.parameter->attribute [ %s ] ", param->attribute);
+                               EM_DEBUG_LOG(">>>>> body->disposition.parameter->value [ %s ] ", param->value);
+
+                               /*  attribute is "filename" */
+                               if (!strcasecmp(param->attribute, "filename"))  {
+                                       decoded_filename = emcore_decode_rfc2047_text(param->value, &err);
+                                       strncpy(filename, decoded_filename, MAX_PATH);
+                                       EM_SAFE_FREE(decoded_filename);
+                                       EM_DEBUG_LOG(">>>>> FILENAME [%s] ", filename);
+                                       break;
+                               }
+
+                               param = param->next;
+                       }
+               }
+               else {
+                       if ((body->id[0] == '<'))
+                               SNPRINTF(filename, MAX_PATH, "%s", body->id+1);
+                       else
+                               SNPRINTF(filename, MAX_PATH, "%s", body->id);
+
+                       len = EM_SAFE_STRLEN(filename);
+
+                       if ((len > 1) && (filename[len-1] == '>'))
+                               filename[len-1] = '\0';
+               }
+               /* is_attachment = 1; */
+               is_attachment = 0;
+       }
+       else if (body->location) {
+               EM_DEBUG_LOG("body->location exist");
+               is_attachment = 1;
+               decoded_filename = emcore_decode_rfc2047_text(body->location, &err);
+               strncpy(filename, decoded_filename, MAX_PATH);
+               EM_SAFE_FREE(decoded_filename);
+               EM_DEBUG_LOG("body->location [%s]", body->location);
+       }
+       else if (is_pbd && (strncmp(body->subtype, "RFC822", strlen("RFC822")) == 0) && (cnt_info->grab_type == 0 || (cnt_info->grab_type & GRAB_TYPE_ATTACHMENT))) {
+               EM_DEBUG_LOG("Beause subtype is RFC822. This is ttachment");
+               is_attachment = 1;
+
+               if (cnt_info->grab_type == 0) {
+                       if ((body->nested.msg != NULL) && (body->nested.msg->env != NULL) && (body->nested.msg->env->subject != NULL)) {
+                               decoded_filename = emcore_decode_rfc2047_text(body->nested.msg->env->subject, &err);
+                               strncpy(filename, decoded_filename, MAX_PATH);
+                               EM_SAFE_FREE(decoded_filename);
+                       }
+                       else
+                               strncpy(filename, "Unknown <message/rfc822>", MAX_PATH);
+               }
+               else if (cnt_info->grab_type & GRAB_TYPE_ATTACHMENT) {
+                       BODY *temp_body = NULL;
+                       if (body->nested.msg->env->subject != NULL) {
+                               int i = 0;
+                               int subject_count = 0;
+                               if (g_str_has_prefix(body->nested.msg->env->subject, "= ? ") && g_str_has_suffix(body->nested.msg->env->subject, " ? = "))
+                                       strncpy(filename, "unknown", MAX_PATH);
+                               else {
+                                       for (subject_count = 0; body->nested.msg->env->subject[subject_count] != '\0' ; subject_count++) {
+                                               if (body->nested.msg->env->subject[subject_count] != ':'  &&
+                                                       body->nested.msg->env->subject[subject_count] != ';'  &&
+                                                       body->nested.msg->env->subject[subject_count] != '*'  &&
+                                                       body->nested.msg->env->subject[subject_count] != '?'  &&
+                                                       body->nested.msg->env->subject[subject_count] != '\"' &&
+                                                       body->nested.msg->env->subject[subject_count] != '<'  &&
+                                                       body->nested.msg->env->subject[subject_count] != '>'  &&
+                                                       body->nested.msg->env->subject[subject_count] != '|'  &&
+                                                       body->nested.msg->env->subject[subject_count] != '/') {
+                                                       filename[i] = body->nested.msg->env->subject[subject_count];
+                                                       i++;
+                                               }
+                                               else
+                                                       continue;
+                                       }
+                               }
+                       }
+                       else
+                               strncpy(filename, "Unknown", MAX_PATH);
+
+                       body = ((MESSAGE *)body->nested.msg)->body;
+                       part = body->nested.part;
+
+                       if ((body->subtype[0] == 'P') || (body->subtype[0] == 'H'))
+                               temp_body = body;
+                       else if (part != NULL) {
+                               temp_body = &(part->body);
+                               if ((temp_body->subtype[0] == 'P' || temp_body->subtype[0] == 'H') && part->next != NULL) {
+                                       part = part->next;
+                                       temp_body = &(part->body);
+                               }
+                       }
+
+                       if (temp_body) {
+                               if (temp_body->subtype[0] == 'P')
+                                       section_plain = 1;
+                               else if (temp_body->subtype[0] == 'H')
+                                       section_html = 1;
+
+                               sparep = temp_body->sparep;
+                               encode = temp_body->encoding;
+                       }
+
+               }
+       }
+       else if (body->disposition.type) /*  if disposition exists, get filename from disposition parameter */ {        /*  "attachment" or "inline" or etc.. */
+               EM_DEBUG_LOG("body->disposition.type exist");
+               is_attachment = 1;
+
+               if (emcore_get_attribute_value_of_body_part(body->disposition.parameter, "filename", filename, MAX_PATH, true, &err))
+                       EM_DEBUG_LOG(">>>>> FILENAME [%s] ", filename);
+
+               if (!*filename)  {      /*  If the part has no filename, it may be report ms */
+                       if ((body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I') && body->parameter && body->parameter->attribute && strcasecmp(body->parameter->attribute, "NAME"))
+                               is_attachment = 0;
+                       else if (body->parameter) /* Fix for the MMS attachment File name as unknown */ {
+                               char *extcheck = NULL;
+
+                               if (emcore_get_attribute_value_of_body_part(body->parameter, "NAME", filename, MAX_PATH, true, &err))
+                                       EM_DEBUG_LOG("NAME [%s] ", filename);
+
+                               extcheck = strchr(filename, '.');
+
+                               if (extcheck)
+                                       EM_DEBUG_LOG(">>>> Extension Exist in the Attachment [ %s ] ", extcheck);
+                               else  { /* No extension attached , So add the Extension based on the subtype */
+                                       if (body->subtype) {
+                                               if (EM_SAFE_STRLEN(filename) + EM_SAFE_STRLEN(body->subtype) + 1 < MAX_PATH) {
+                                                       strcat(filename, ".");
+                                                       strcat(filename, body->subtype);
+                                               }
+                                               EM_DEBUG_LOG(">>>>> FILENAME Identified the Extension [%s] ", filename);
+                                       }
+                                       else
+                                               EM_DEBUG_EXCEPTION("UnKnown Extesnsion  : _ (");
+                               }
+
+                       }
+                       else
+                               strncpy(filename, "unknown", MAX_PATH);
+               }
+               else {
+                       if ((body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I'))
+                               is_attachment = 0;
+               }
+       }
+
+       /* if (!is_pbd) */ {
+               EM_DEBUG_LOG("filename [%s]", filename);
+               if (*filename)  {
+                       decoded_filename = emcore_decode_rfc2047_text(filename, &err);
+                       strncpy(filename, decoded_filename, MAX_PATH);
+                       EM_SAFE_FREE(decoded_filename);
+                       filename_temp = em_parse_filename(filename);
+                       if (filename_temp) {
+                               strncpy(filename, filename_temp, MAX_PATH);
+                               EM_DEBUG_LOG("filename [%s]", filename);
+                       }
+               }
+       }
+       EM_DEBUG_LOG("is_attachment [%d]", is_attachment);
+
+       if (!is_attachment)  {  /*  Text or RFC822 Message */
+               EM_DEBUG_LOG("Multipart is not attachment, body->type = %d", body->type);
+               if ((cnt_info->grab_type & GRAB_TYPE_TEXT) && (body->type == TYPEMESSAGE || body->type == TYPETEXT || body->type == TYPEIMAGE))  {
+                       if (is_pbd)
+                               return SUCCESS;
+                       else {  /*  fetch body */
+                               if (!emcore_get_temp_file_name(&o_data, &err))  {
+                                       EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+
+                               if (!imap_mail_write_body_to_file(stream, account_id, mail_id, 0, o_data, msg_uid, body->sparep, body->encoding, &o_data_len, body->subtype, &err))  {
+                                       EM_DEBUG_EXCEPTION("imap_mail_write_body_to_file failed [%d]", err);
+                                       if(err == EMAIL_ERROR_INVALID_STREAM) {
+                                               email_session_t *session = NULL;
+                                               emcore_get_current_session(&session);
+                                               err = session->error;
+                                       }
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+
+               switch (body->type)  {
+                       case TYPETEXT:
+                               EM_DEBUG_LOG("TYPETEXT");
+                               if (body->subtype[0] == 'H')
+                                       cnt_info->text.html = o_data;
+                               else  {
+                                       cnt_info->text.plain = o_data;
+                                       memset(charset_value_buffer, 0, 512);
+                                       if (emcore_get_attribute_value_of_body_part(body->parameter, "CHARSET", charset_value_buffer, 512, true, &err))
+                                               cnt_info->text.plain_charset = EM_SAFE_STRDUP(charset_value_buffer);
+                               }
+                               break;
+                       case TYPEIMAGE:
+                       case TYPEAPPLICATION:
+                       case TYPEAUDIO:
+                       case TYPEVIDEO:
+                       /*  Inline Content - suspect of crash on partial body download */
+                               if (!is_pbd) {
+                                       EM_DEBUG_LOG("TYPEIMAGE or TYPEAPPLICATION  :  inline content");
+                                       ai = &(cnt_info->file);
+
+                                       dec_len = body->size.bytes;
+                                       if ((cnt_info->grab_type & GRAB_TYPE_ATTACHMENT) &&
+                                               (cnt_info->grab_type & GRAB_TYPE_TEXT))  {      /*  it is 'download all */
+                                               only_body_download = false;
+                                               cnt_info->file_no = 1;
+                                       }
+
+                                       /*  add attachment info to content info */
+                                       if (!(*ai = em_malloc(sizeof(struct attachment_info))))  {
+                                               EM_DEBUG_EXCEPTION("em_malloc failed...");
+                                               if (err_code != NULL)
+                                                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+                                               return FAILURE;
+                                       }
+
+                                       if (((body->id) || (body->location)) && body->type == TYPEIMAGE)
+                                               (*ai)->type = 1;                        /*  inline */
+                                       else
+                                               (*ai)->type = 2;                        /*  attachment */
+
+                                       (*ai)->name                 = EM_SAFE_STRDUP(filename);
+                                       (*ai)->size                 = body->size.bytes;
+                                       (*ai)->save                 = o_data;
+                                       (*ai)->content_id           = EM_SAFE_STRDUP(body->id);
+
+                                       memset(content_type_buffer, 0, 512);
+                                       if ( (err = emcore_get_content_type_from_mail_bodystruct(body, 512, content_type_buffer) ) == EMAIL_ERROR_NONE)
+                                               (*ai)->attachment_mime_type = EM_SAFE_STRDUP(content_type_buffer);
+
+                                       EM_DEBUG_LOG("name[%s], size[%d], save[%s], content_id[%s], content_type_buffer [%s]", cnt_info->file->name, cnt_info->file->size, cnt_info->file->save, content_type_buffer);
+#ifdef __ATTACHMENT_OPTI__
+                                       (*ai)->encoding = body->encoding;
+                                       if (body->sparep)
+                                               (*ai)->section = EM_SAFE_STRDUP(body->sparep);
+                                       EM_DEBUG_LOG(" Encoding - %d  Section No - %s ", (*ai)->encoding, (*ai)->section);
+#endif
+                               }
+                               break;
+
+                       case TYPEMESSAGE:  /*  RFC822 Message */
+                               EM_DEBUG_EXCEPTION("MESSAGE/RFC822");
+                               err = EMAIL_ERROR_NOT_SUPPORTED;
+                               goto FINISH_OFF;
+
+                       default:
+                               EM_DEBUG_EXCEPTION("Unknown type. body->type [%d]", body->type);
+                               err = EMAIL_ERROR_NOT_SUPPORTED;
+                               goto FINISH_OFF;
+               }
+
+               stream->text.data = NULL;  /*  ? ? ? ? ? ? ? ? */
+       }
+       else  { /*  Attachment */
+               prev_ai = NULL;
+               next_ai = NULL;
+               ai = &cnt_info->file;
+               EM_DEBUG_LOG(" ai - %p ", (*ai));
+
+               if ((body->id) || (body->location)) {
+                       /*  For Inline content append to the end */
+                       for (i = 1; *ai; ai = &(*ai)->next)
+                               i++;
+                       }
+               else {  /*  For attachment - search till Inline content found and insert before inline */
+                       for (i = 1; *ai; ai = &(*ai)->next) {
+                               if ((*ai)->type == 1)  {
+                                       /*  Means inline image */
+                                       EM_DEBUG_LOG("Found Inline Content ");
+                                       next_ai = (*ai);
+                                       break;
+                               }
+                               i++;
+                               prev_ai = (*ai);
+                       }
+               }
+
+               EM_DEBUG_LOG("i - %d next_ai - %p  prev_ai - %p", i, next_ai, prev_ai);
+
+               if ((cnt_info->grab_type & GRAB_TYPE_ATTACHMENT) &&
+               (cnt_info->grab_type & GRAB_TYPE_TEXT))  {      /*  it is 'download all */
+                       EM_DEBUG_LOG("Download All");
+                       only_body_download = false;
+                       cnt_info->file_no = 1;
+                       i = 1;
+               }
+               /*  meaningless code */
+               dec_len = body->size.bytes;
+
+               if (body->id)
+                       EM_DEBUG_LOG("BODY ID [ %s ]", body->id);
+               else
+                       EM_DEBUG_LOG("BODY ID IS NULL");
+
+               EM_DEBUG_LOG("i : %d, cnt_info->file_no : %d", i, cnt_info->file_no);
+
+               if (
+                       ((cnt_info->grab_type & GRAB_TYPE_ATTACHMENT) && i == cnt_info->file_no) ||   /*  Is it correct attachment  */
+                       (((body->id) || (body->location)) && (cnt_info->grab_type & GRAB_TYPE_TEXT))  /*  Is it inline contents  */
+               )  {
+                       /*  fetch attachment */
+                       EM_DEBUG_LOG("attachment (enc)  :  %s %ld bytes", filename, body->size.bytes);
+                       EM_DEBUG_LOG(">>>>> ONLY BODY DOWNLOAD [ %d ] ", only_body_download);
+
+                       if (only_body_download == false) {
+                               if (!emcore_get_temp_file_name(&savefile, &err))  {
+                                       EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+
+                               if (!is_pbd) {
+                                       if (!imap_mail_write_body_to_file(stream, account_id, mail_id, cnt_info->file_no, savefile, msg_uid, body->sparep, body->encoding, &dec_len, body->subtype, &err))  {
+                                               EM_DEBUG_EXCEPTION("imap_mail_write_body_to_file failed [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+                               }
+                       }
+               }
+
+               EM_DEBUG_LOG("attachment (dec)  :  %s %d bytes", filename, dec_len);
+
+               /*  add attachment info to content inf */
+               if (!(*ai = em_malloc(sizeof(struct attachment_info))))  {
+                       EM_DEBUG_EXCEPTION("em_malloc failed...");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               if ((body->id) || (body->location))
+                       (*ai)->type = 1;
+               else
+                       (*ai)->type = 2;
+
+               if (is_pbd) {
+                       if (savefile != NULL) {
+                               if (section_plain == 1)
+                                       strcat(filename, ".txt");
+                               if (section_html == 1)
+                                       strcat(filename, ".html");
+                               section_plain = 0;
+                               section_html = 0;
+                       }
+               } /*  is_pbd */
+               (*ai)->name                 = EM_SAFE_STRDUP(filename);
+               (*ai)->size                 = dec_len;
+               (*ai)->save                 = savefile;
+               (*ai)->content_id           = EM_SAFE_STRDUP(body->id);
+
+               memset(content_type_buffer, 0, 512);
+               if ( (err = emcore_get_content_type_from_mail_bodystruct(body, 512, content_type_buffer) ) == EMAIL_ERROR_NONE)
+                       (*ai)->attachment_mime_type = EM_SAFE_STRDUP(content_type_buffer);
+#ifdef __ATTACHMENT_OPTI__
+               (*ai)->encoding = body->encoding;
+               if (body->sparep)
+                       (*ai)->section = EM_SAFE_STRDUP(body->sparep);
+
+               EM_DEBUG_LOG(" Encoding - %d  Section No - %s ", (*ai)->encoding, (*ai)->section);
+#endif
+               if (body->type == TYPEAPPLICATION)  {
+                       if (!strcasecmp(body->subtype, MIME_SUBTYPE_DRM_OBJECT))
+                               (*ai)->drm = EMAIL_ATTACHMENT_DRM_OBJECT;
+                       else if (!strcasecmp(body->subtype, MIME_SUBTYPE_DRM_RIGHTS))
+                               (*ai)->drm = EMAIL_ATTACHMENT_DRM_RIGHTS;
+                       else if (!strcasecmp(body->subtype, MIME_SUBTYPE_DRM_DCF))
+                               (*ai)->drm = EMAIL_ATTACHMENT_DRM_DCF;
+               }
+
+               /*  All inline images information are stored at the end of list */
+               if ((*ai)->type != 1 && next_ai != NULL) {
+               /*  Means next_ai points to the inline attachment info structure */
+                       if (prev_ai == NULL) {
+                               /*  First node is inline attachment */
+                               (*ai)->next = next_ai;
+                               cnt_info->file = (*ai);
+                       }
+                       else {
+                               prev_ai->next = (*ai);
+                               (*ai)->next = next_ai;
+                       }
+               }
+       }
+
+       ret = 0;
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+/*  get body-part in nested part */
+
+static int emcore_get_allnested_part(MAILSTREAM *stream, int account_id, int mail_id, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+       PART *part_child = body->nested.part;
+
+       while (part_child)  {
+               if (emcore_get_body(stream, account_id, mail_id, msg_uid, &part_child->body, cnt_info, err_code) < 0)
+                       return FAILURE;
+
+               part_child = part_child->next;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+/* get body-part in alternative multiple part */
+static int emcore_get_alternative_multi_part(MAILSTREAM *stream, int account_id, int mail_id, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       PART *part_child = body->nested.part;
+
+       /* find the best sub part we can show */
+       while (part_child)  {
+               if (emcore_get_body(stream, account_id, mail_id, msg_uid, &part_child->body, cnt_info, err_code) < 0)
+                       return FAILURE;
+
+               part_child = part_child->next;
+       }
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+/* get body part in signed multiple part */
+static int emcore_get_signed_multi_part(MAILSTREAM *stream, int account_id, int mail_id, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+        PART *part_child = body->nested.part;
+
+        /* find the best sub part we can show */
+        while (part_child)  {
+                if (emcore_get_body(stream, account_id, mail_id, msg_uid, &part_child->body, cnt_info, err_code) < 0)
+                       return FAILURE;
+
+                part_child = part_child->next;
+        }
+
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+/* get body part in encrypted multiple part */
+static int emcore_get_encrypted_multi_part(MAILSTREAM *stream, int account_id, int mail_id, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+/* get body part in multiple part */
+static int emcore_get_multi_part(MAILSTREAM *stream, int account_id, int mail_id, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       if (!body) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter.");
+               if (err_code)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return FAILURE;
+       }
+
+       switch (body->subtype[0])  {
+               case 'A':               /*  ALTERNATIVE */
+                       EM_DEBUG_LOG("body->subtype[0] = ALTERNATIVE");
+                       return emcore_get_alternative_multi_part(stream, account_id, mail_id, msg_uid, body, cnt_info, err_code);
+
+               case 'S':               /*  SIGNED */
+                       EM_DEBUG_LOG("body->subtype[0] = SIGNED");
+                       return emcore_get_signed_multi_part(stream, account_id, mail_id, msg_uid, body, cnt_info, err_code);
+
+               case 'E':               /*  ENCRYPTED */
+                       EM_DEBUG_LOG("body->subtype[0] = ENCRYPTED");
+                       return emcore_get_encrypted_multi_part(stream, account_id, mail_id, msg_uid, body, cnt_info, err_code);
+
+               default:                /*  process all unknown as MIXED (according to the RFC 2047) */
+                       EM_DEBUG_LOG("body->subtype[0] = [%c].", body->subtype[0]);
+                       return emcore_get_allnested_part(stream, account_id, mail_id, msg_uid, body, cnt_info, err_code);
+       }
+       /* Delete the dead code */
+}
+
+/*  get body data by body structure */
+/*  if POP3, ignored */
+INTERNAL_FUNC int emcore_get_body(MAILSTREAM *stream, int account_id, int mail_id, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], cnt_info[%p], err_code[%p]", stream, msg_uid, body, cnt_info, err_code);
+
+       if (!stream || !body || !cnt_info)  {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return FAILURE;
+       }
+
+       EM_DEBUG_LOG("body->type [%d]", body->type);
+
+       switch (body->type)  {
+               case TYPEMULTIPART:
+                       return emcore_get_multi_part(stream, account_id, mail_id, msg_uid, body, cnt_info, err_code);
+
+               case TYPEMESSAGE:  /*  not support */
+                       if (strcasecmp(body->subtype, "RFC822") == 0)
+                               return emcore_get_body_part_imap(stream, account_id, mail_id, msg_uid, body, cnt_info, err_code);
+                       break;
+
+               case TYPETEXT:
+               case TYPEAPPLICATION:
+               case TYPEAUDIO:
+               case TYPEIMAGE:
+               case TYPEVIDEO:
+               case TYPEMODEL:
+               case TYPEOTHER:
+                       /*  exactly, get a pure body part (text and attachment */
+                       return emcore_get_body_part_imap(stream, account_id, mail_id, msg_uid, body, cnt_info, err_code);
+
+               default:
+                       break;
+       }
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+/* get body structure */
+INTERNAL_FUNC int emcore_get_body_structure(MAILSTREAM *stream, int msg_uid, BODY **body, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], msg_uid[%d], body[%p], err_code[%p]", stream, msg_uid, body, err_code);
+
+       EM_IF_NULL_RETURN_VALUE(stream, false);
+       EM_IF_NULL_RETURN_VALUE(body, false);
+
+#ifdef __FEATURE_HEADER_OPTIMIZATION__
+               ENVELOPE *env = mail_fetch_structure(stream, msg_uid, body, FT_UID | FT_PEEK | FT_NOLOOKAHEAD, 1);
+#else
+               ENVELOPE *env = mail_fetch_structure(stream, msg_uid, body, FT_UID | FT_PEEK | FT_NOLOOKAHEAD);
+#endif
+       if (!env) {
+               if (err_code)
+                       *err_code = EMAIL_ERROR_MAIL_NOT_FOUND_ON_SERVER;
+               EM_DEBUG_EXCEPTION("mail_fetch_structure failed");
+               return FAILURE;
+       }
+
+#ifdef FEATURE_CORE_DEBUG
+       _print_body(*body, true); /* shasikala.p@partner.samsung.com */
+#endif
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+int emcore_set_fetch_part_section(BODY *body, char *section_pfx, int section_subno, int enable_inline_list, int *total_mail_size, int *err_code);
+
+/* set body section to be fetched */
+INTERNAL_FUNC int emcore_set_fetch_body_section(BODY *body, int enable_inline_list, int *total_mail_size, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("body[%p], err_code[%p]", body, err_code);
+
+       if (!body)  {
+               EM_DEBUG_EXCEPTION("body [%p]", body);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return FAILURE;
+       }
+
+//     body->id = cpystr("1"); /*  top level body */
+       EM_DEBUG_LOG("body->id : [%s]", body->id);
+
+       g_inline_count = 0;
+       EM_SAFE_FREE(g_inline_list);
+       emcore_set_fetch_part_section(body, (char *)NULL, 0, enable_inline_list, total_mail_size, err_code);
+
+       if (body && body->id)
+               EM_DEBUG_LOG(">>>>> FILE NAME [%s] ", body->id);
+       else
+               EM_DEBUG_LOG(">>>>> BODY NULL ");
+
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+/* set part section of body to be fetched */
+int emcore_set_fetch_part_section(BODY *body, char *section_pfx, int section_subno, int enable_inline_list, int *total_mail_size, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("body[%p], section_pfx[%s], section_subno[%d], err_code[%p]", body, section_pfx, section_subno, err_code);
+
+       PART *part = NULL;
+       char section[64] = {0x00, };
+
+       /* multipart doesn't have a row to itself */
+       if (body->type == TYPEMULTIPART)  {
+               /* if not first time, extend prefix */
+               if (section_pfx) {
+                       SNPRINTF(section, sizeof(section), "%s%d.", section_pfx, ++section_subno);
+               }
+               else {
+                       section[0] = '\0';
+               }
+
+               for (section_subno = 0, part = body->nested.part; part; part = part->next)
+                       emcore_set_fetch_part_section(&part->body, section, section_subno++, enable_inline_list, total_mail_size, err_code);
+       }
+       else  {
+               if (!section_pfx) /* dummy prefix if top level */
+                       section_pfx = "";
+
+               SNPRINTF(section, sizeof(section), "%s%d", section_pfx, ++section_subno);
+
+               if (enable_inline_list && ((body->disposition.type && (body->disposition.type[0] == 'i' || body->disposition.type[0] == 'I')) ||
+                       (!body->disposition.type && body->id))) {
+                       BODY **temp = NULL;
+                       temp =  realloc(g_inline_list, sizeof(BODY *) *(g_inline_count + 1));
+                       if (NULL != temp) {
+                               memset(temp+g_inline_count, 0x00, sizeof(BODY *));
+                               g_inline_list = temp;
+                               g_inline_list[g_inline_count] = body;
+                               g_inline_count++;
+                               temp = NULL;
+                       }
+                       else {
+                               EM_DEBUG_EXCEPTION("realloc fails");
+                       }
+
+                       EM_DEBUG_LOG("Update g_inline_list with inline count [%d]", g_inline_count);
+               }
+
+               /*  if ((total_mail_size != NULL) && !(body->disposition.type && (body->disposition.type[0] == 'a' || body->disposition.type[0] == 'A')) */
+               if (total_mail_size != NULL) {
+                       *total_mail_size = *total_mail_size + (int)body->size.bytes;
+                       EM_DEBUG_LOG("body->size.bytes [%d]", body->size.bytes);
+               }
+
+               /* encapsulated message ? */
+               if ((body->type == TYPEMESSAGE) && !strcasecmp(body->subtype, "RFC822") && (body = ((MESSAGE *)body->nested.msg)->body))  {
+                       if (body->type == TYPEMULTIPART) {
+                               section[0] = '\0';
+                               emcore_set_fetch_part_section(body, section, section_subno-1, enable_inline_list, total_mail_size, err_code);
+                       }
+                       else  {         /*  build encapsulation prefi */
+                               SNPRINTF(section, sizeof(section), "%s%d.", section_pfx, section_subno);
+                               emcore_set_fetch_part_section(body, section, 0, enable_inline_list, total_mail_size, err_code);
+                       }
+               }
+               else  {
+                       /* set body section */
+                       if (body)
+                               body->sparep = cpystr(section);
+               }
+       }
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+
+static void parse_file_path_to_filename(char *src_string, char **out_string)
+{
+       char *token = NULL;
+       char *filepath = NULL;
+       char *str = NULL;
+       char *prev1 = NULL;
+       char *prev2 = NULL;
+
+       filepath = EM_SAFE_STRDUP(src_string);
+       token = strtok_r(filepath, "/", &str);
+
+       do {
+               prev2 = prev1;
+               prev1 = token;
+       } while ((token = strtok_r(NULL , "/", &str)));
+
+       *out_string = EM_SAFE_STRDUP(prev1);
+       EM_SAFE_FREE(filepath);
+}
+
+static char *emcore_decode_rfc2047_word(char *encoded_word, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("encoded_word[%s], err_code[%p]", encoded_word, err_code);
+
+       int err = EMAIL_ERROR_NONE;
+       int base64_encoded = false, length = 0;
+       SIZEDTEXT src = { NULL, 0 };
+       SIZEDTEXT dst = { NULL, 0 };
+       gchar *charset = NULL, *encoded_text = NULL;
+       char *decoded_text = NULL, *decoded_word = NULL;
+       char *current = NULL, *start = NULL, *end = NULL;
+       char *buffer = (char*) em_malloc(EM_SAFE_STRLEN(encoded_word) * 2 + 1);
+
+       if (buffer == NULL) {
+               EM_DEBUG_EXCEPTION("Memory allocation fail");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       strcpy(buffer, "");
+
+       /*  encoding format : =?charset?encoding?encoded-text ?=  */
+       /*  charset : UTF-8, EUC-KR, ... */
+       /*  encoding : b/B (BASE64), q/Q (QUOTED-PRINTABLE) */
+       current = encoded_word;
+
+       while (*current != NULL_CHAR) {
+               /* search next */
+               start = strstr(current, "=?");          /*  start of encoding */
+               end = strstr(current, "?=");            /*  end of encoding */
+
+#ifdef FEATURE_CORE_DEBUG
+               EM_DEBUG_LOG("current[%p][%s], start[%p][%s], end[%p][%s]", current, current, start, start, end, end);
+#endif
+               if (start != NULL) {
+                       if (current != start) { /*  copy the string between current and start to buffer */
+                               strncat(buffer, current, start - current);
+                               current = start;
+#ifdef FEATURE_CORE_DEBUG
+                               EM_DEBUG_LOG("1 - Buffer[%s]", buffer);
+#endif
+                       }
+
+                       if (end) {      /*  decode text between start and end */
+                               char *p = strstr(start, "?b?");
+
+                               if (p || (p = strstr(start, "?B?")))            /*  BASE64 */
+                                       base64_encoded = true;
+                               else {
+                                       p = strstr(start, "?q?");
+
+                                       if (p || (p = strstr(start, "?Q?")))            /*  QUOTED-PRINTABLE */
+                                               base64_encoded = false;
+                                       else {
+                                               EM_DEBUG_EXCEPTION("unknown encoding found...");
+
+                                               err = EMAIL_ERROR_UNKNOWN;
+                                               goto FINISH_OFF;
+                                       }
+                               }
+
+                               if (base64_encoded) {   /*  BASE64 */
+                                       charset = g_strndup(start + 2, p - (start + 2));
+                                       encoded_text = g_strndup(p + 3, end - (p + 3));
+                               }
+                               else {  /*  QUOTED-PRINTABLE */
+                                       charset = g_strndup(start + 2, p - (start + 2));
+                                       if (*(p+3) == '=') {    /*  encoded text might start with '='. ex) '?Q?=E0' */
+                                               end = strstr(p+3, "?=");                /*  find new end flag */
+                                               if (end) {
+                                                       encoded_text = g_strndup(p + 3, end - (p + 3));
+                                               }
+                                               else {  /*  end flag is not found */
+                                                       EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_word decoding error : '?=' is not found...");
+
+                                                       err = EMAIL_ERROR_UNKNOWN;
+                                                       goto FINISH_OFF;
+                                               }
+                                       }
+                                       else {
+                                               encoded_text = g_strndup(p + 3, end - (p + 3));
+                                       }
+                               }
+
+#ifdef FEATURE_CORE_DEBUG
+                               EM_DEBUG_LOG("\t >>>>>>>>>>>>>>> CHARSET[%s]", charset);
+                               EM_DEBUG_LOG("\t >>>>>>>>>>>>>>> ENCODED_TEXT[%s]", encoded_text);
+#endif
+
+                               unsigned long len = 0;
+                               if (encoded_text != NULL) {
+                               if (base64_encoded == true) {
+                                       if (!(decoded_text = (char *)rfc822_base64((unsigned char *)encoded_text, EM_SAFE_STRLEN(encoded_text), &len))) {
+                                               EM_DEBUG_EXCEPTION("rfc822_base64 falied...");
+                                               goto FINISH_OFF;
+                                       }
+                               }
+                               else  {
+                                       g_strdelimit(encoded_text, "_", ' ');
+
+                                       if (!(decoded_text = (char *)rfc822_qprint((unsigned char *)encoded_text, EM_SAFE_STRLEN(encoded_text), &len))) {
+                                               EM_DEBUG_EXCEPTION("rfc822_base64 falied...");
+                                               goto FINISH_OFF;
+                                       }
+                               }
+
+                               src.data = (unsigned char *)decoded_text;
+                               src.size = EM_SAFE_STRLEN(decoded_text);
+
+                               if (!utf8_text(&src, charset, &dst, 0))  {
+                                       EM_DEBUG_EXCEPTION("utf8_text falied...");
+                                       if (src.data)
+                                               strncat(buffer, (char *)src.data, src.size); /* Eventhough failed to decode, downloading should go on. Kyuho Jo */
+                               } else {
+                                       if (dst.data)
+                                               strncat(buffer, (char *)dst.data, dst.size);
+                               }
+#ifdef FEATURE_CORE_DEBUG
+                               EM_DEBUG_LOG("2 - Buffer[%s]", buffer);
+#endif
+
+                               /*  free all of the temp variables */
+                               if (dst.data != NULL && dst.data != src.data)
+                                       EM_SAFE_FREE(dst.data);
+
+                               EM_SAFE_FREE(decoded_text);
+
+                                       g_free(encoded_text);
+                                       encoded_text = NULL;
+                               }
+                               if (charset != NULL) {
+                                       g_free(charset);
+                                       charset = NULL;
+                               }
+
+                               current = end + 2;      /*  skip '?=' */
+                       }
+                       else {
+                               /*  unencoded text      */
+                               length = EM_SAFE_STRLEN(start);
+                               strncat(buffer, start, length);
+                               current = start + length;
+#ifdef FEATURE_CORE_DEBUG
+                               EM_DEBUG_LOG("3 - Buffer[%s]", buffer);
+#endif
+                       }
+               }
+               else {
+                       /*  unencoded text      */
+                       length = EM_SAFE_STRLEN(current);
+                       strncat(buffer, current, length);
+                       current = current + length;
+#ifdef FEATURE_CORE_DEBUG
+                       EM_DEBUG_LOG("4 - Buffer[%s]", buffer);
+#endif
+               }
+       }
+
+       decoded_word = EM_SAFE_STRDUP(buffer);
+
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG(">>>>>>>>>>>>>>> DECODED_WORD[%s]", decoded_word);
+#endif
+
+FINISH_OFF:
+       if (dst.data != NULL && dst.data != src.data)
+               EM_SAFE_FREE(dst.data);
+       EM_SAFE_FREE(decoded_text);
+       EM_SAFE_FREE(buffer);
+
+       if (encoded_text != NULL)
+               g_free(encoded_text);
+       if (charset != NULL)
+               g_free(charset);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return decoded_word;
+}
+
+INTERNAL_FUNC char *emcore_decode_rfc2047_text(char *rfc2047_text, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("rfc2047_text[%s], err_code[%p]", rfc2047_text, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!rfc2047_text)  {
+               EM_DEBUG_EXCEPTION("rfc2047_text[%p]", rfc2047_text);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return NULL;
+       }
+
+       char *text = NULL;
+
+       gchar **encoded_words = g_strsplit_set(rfc2047_text, " \t\r\n", -1);
+       gchar **decoded_words = g_new0(char *, g_strv_length(encoded_words) + 1);
+
+       /* EM_DEBUG_LOG("g_strv_length(encoded_words) [%d]", g_strv_length(encoded_words)); */
+
+       if (encoded_words != NULL)  {
+               int i = 0;
+
+               while (encoded_words[i] != NULL)  {
+                       if (!(decoded_words[i] = emcore_decode_rfc2047_word(encoded_words[i], &err)))  {
+                               EM_DEBUG_EXCEPTION("emcore_decode_rfc2047_word falied [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       i++;
+               }
+               text = g_strjoinv(" ", decoded_words);
+       }
+       else
+               text = EM_SAFE_STRDUP(rfc2047_text);
+
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG(">>>>>>>>>>>>>>>>> TEXT[%s]", text);
+#endif /*  FEATURE_CORE_DEBUG */
+
+       ret = true;
+
+FINISH_OFF:
+       g_strfreev(decoded_words);
+       g_strfreev(encoded_words);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return text;
+}
+
+INTERNAL_FUNC int emcore_make_mail_data_from_mime_data(struct _m_mesg *mmsg, struct _m_content_info *cnt_info, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int local_attachment_count = 0;
+       int local_inline_content_count = 0;
+       int attachment_num = 0;
+       int i = 0;
+       int eml_mail_id = 0;
+       char buf[512];
+       char html_body[MAX_PATH] = {0, };
+       struct tm temp_time_info;
+       struct timeval tv;
+       struct attachment_info *ai = NULL;
+       char *encoded_subject = NULL;
+       email_attachment_data_t *attachment = NULL;
+       email_mail_data_t *p_mail_data = NULL;
+       MESSAGECACHE mail_cache_element = {0, };
+
+       if (!mmsg || !cnt_info || !output_mail_data || !output_attachment_data) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       p_mail_data = (email_mail_data_t *)em_malloc(sizeof(email_mail_data_t));
+       if (p_mail_data == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(&mail_cache_element, 0x00, sizeof(MESSAGECACHE));
+       memset((void *)&temp_time_info, 0, sizeof(struct tm));
+
+       /* Create rand mail id of eml */
+       gettimeofday(&tv, NULL);
+       srand(tv.tv_usec);
+       eml_mail_id = rand();
+
+       p_mail_data->mail_id = eml_mail_id;
+       p_mail_data->account_id = EML_FOLDER;
+
+       if (mmsg->rfc822header->date)
+               mail_parse_date(&mail_cache_element, (unsigned char *)mmsg->rfc822header->date);
+
+       temp_time_info.tm_sec = mail_cache_element.seconds;
+       temp_time_info.tm_min = mail_cache_element.minutes - mail_cache_element.zminutes;
+       temp_time_info.tm_hour = mail_cache_element.hours - mail_cache_element.zhours;
+
+       if (mail_cache_element.hours - mail_cache_element.zhours < 0) {
+               temp_time_info.tm_mday = mail_cache_element.day - 1;
+               temp_time_info.tm_hour += 24;
+       } else
+               temp_time_info.tm_mday = mail_cache_element.day;
+
+       temp_time_info.tm_mon = mail_cache_element.month - 1;
+       temp_time_info.tm_year = mail_cache_element.year + 70;
+
+       encoded_subject = emcore_decode_rfc2047_text(mmsg->rfc822header->subject, NULL);
+
+       p_mail_data->date_time                   = timegm(&temp_time_info);
+       p_mail_data->full_address_return         = EM_SAFE_STRDUP(mmsg->rfc822header->return_path);
+       p_mail_data->email_address_recipient     = EM_SAFE_STRDUP(mmsg->rfc822header->received);
+       p_mail_data->full_address_from           = EM_SAFE_STRDUP(mmsg->rfc822header->from);
+       p_mail_data->subject                     = EM_SAFE_STRDUP(encoded_subject);
+       p_mail_data->email_address_sender        = EM_SAFE_STRDUP(mmsg->rfc822header->sender);
+       p_mail_data->full_address_to             = EM_SAFE_STRDUP(mmsg->rfc822header->to);
+       p_mail_data->full_address_cc             = EM_SAFE_STRDUP(mmsg->rfc822header->cc);
+       p_mail_data->full_address_bcc            = EM_SAFE_STRDUP(mmsg->rfc822header->bcc);
+       p_mail_data->full_address_reply          = EM_SAFE_STRDUP(mmsg->rfc822header->reply_to);
+       p_mail_data->body_download_status        = EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED;
+
+       EM_DEBUG_LOG("cnt_info->text.plain [%s], cnt_info->text.html [%s]", cnt_info->text.plain, cnt_info->text.html);
+
+       if (cnt_info->text.plain) {
+               EM_DEBUG_LOG("cnt_info->text.plain [%s]", cnt_info->text.plain);
+               if (!emstorage_create_dir(EML_FOLDER, eml_mail_id, 0, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_get_save_name(EML_FOLDER, eml_mail_id, 0, cnt_info->text.plain_charset ? cnt_info->text.plain_charset : UNKNOWN_CHARSET_PLAIN_TEXT_FILE, buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_move_file(cnt_info->text.plain, buf, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               p_mail_data->file_path_plain = EM_SAFE_STRDUP(buf);
+               EM_DEBUG_LOG("mail_data->file_path_plain [%s]", p_mail_data->file_path_plain);
+       }
+
+       if (cnt_info->text.html)  {
+               if (!emstorage_create_dir(EML_FOLDER, eml_mail_id, 0, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (cnt_info->text.html_charset != NULL) {
+                       SNPRINTF(html_body, MAX_PATH, "%s%s", cnt_info->text.html_charset, HTML_EXTENSION_STRING);
+               } else {
+                       strcpy(html_body, UNKNOWN_CHARSET_HTML_TEXT_FILE);
+               }
+
+               if (!emstorage_get_save_name(EML_FOLDER, eml_mail_id, 0, html_body, buf, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_move_file(cnt_info->text.html, buf, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               p_mail_data->file_path_html = EM_SAFE_STRDUP(buf);
+       }
+
+
+       for (ai = cnt_info->file; ai; ai = ai->next, attachment_num++) {}
+       EM_DEBUG_LOG("attachment_num : [%d]", attachment_num);
+
+       if (attachment_num > 0) {
+               attachment = (email_attachment_data_t *)em_malloc(sizeof(email_attachment_data_t) * attachment_num);
+               if (attachment == NULL) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               for (ai = cnt_info->file; ai; ai = ai->next, i++) {
+                       attachment[i].attachment_id          = 0;
+                       attachment[i].attachment_size        = ai->size;
+                       attachment[i].attachment_name        = EM_SAFE_STRDUP(ai->name);
+                       attachment[i].drm_status             = ai->drm;
+                       attachment[i].save_status            = 0;
+                       attachment[i].inline_content_status  = ai->type == 1;
+                       attachment[i].attachment_mime_type   = ai->attachment_mime_type;
+#ifdef __ATTACHMENT_OPTI__
+                       attachment[i].encoding               = ai->encoding;
+                       attachment[i].section                = ai->section;
+#endif
+                       EM_DEBUG_LOG("attachment[%d].attachment_id[%d]", i, attachment[i].attachment_id);
+                       EM_DEBUG_LOG("attachment[%d].attachment_size[%d]", i, attachment[i].attachment_size);
+                       EM_DEBUG_LOG("attachment[%d].attachment_name[%s]", i, attachment[i].attachment_name);
+                       EM_DEBUG_LOG("attachment[%d].drm_status[%d]", i, attachment[i].drm_status);
+                       EM_DEBUG_LOG("attachment[%d].inline_content_status[%d]", i, attachment[i].inline_content_status);
+
+                       if (ai->type == 1)
+                               local_inline_content_count ++;
+                       local_attachment_count++;
+
+                       if (ai->save)  {
+                               attachment[i].save_status = 1;
+                               if (ai->type == 1)  {           /*  it is inline content */
+                                       if (!emstorage_create_dir(EML_FOLDER, eml_mail_id, 0, &err))  {
+                                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+                                       if (!emstorage_get_save_name(EML_FOLDER, eml_mail_id, 0, attachment[i].attachment_name, buf, &err))  {
+                                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+                               }
+                               else  {
+                                       if (!emstorage_create_dir(EML_FOLDER, eml_mail_id, i, &err)) {
+                                               EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+
+                                       if (!emstorage_get_save_name(EML_FOLDER, eml_mail_id, i, attachment[i].attachment_name, buf, &err))  {
+                                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                                               goto FINISH_OFF;
+                                       }
+                               }
+
+                               if (!emstorage_move_file(ai->save, buf, false, &err))  {
+                                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+
+                                       /*  delete all created files. */
+                                       if (!emstorage_get_save_name(EML_FOLDER, eml_mail_id, 0, NULL, buf, NULL)) {
+                                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed...");
+                                               /* goto FINISH_OFF; */
+                                       }
+
+                                       if (!emstorage_delete_dir(buf, NULL)) {
+                                               EM_DEBUG_EXCEPTION("emstorage_delete_dir failed...");
+                                               /* goto FINISH_OFF; */
+                                       }
+
+
+                                       goto FINISH_OFF;
+                               }
+
+                               attachment[i].attachment_path = EM_SAFE_STRDUP(buf);
+
+                       }
+
+                       EM_DEBUG_LOG("attachment[%d].attachment_path[%s]", i, attachment[i].attachment_path);
+               }
+       }
+       EM_DEBUG_LOG("Check #1");
+
+       p_mail_data->attachment_count = local_attachment_count;
+       p_mail_data->inline_content_count = local_inline_content_count;
+
+       eml_data_count += 1;
+       ret = true;
+
+FINISH_OFF:
+
+       if (ret) {
+               if (output_mail_data)
+                       *output_mail_data = p_mail_data;
+
+               if (output_attachment_data)
+                       *output_attachment_data = attachment;
+
+               if (output_attachment_count)
+                       *output_attachment_count = local_attachment_count;
+       } else {
+               if (p_mail_data) {
+                       emcore_free_mail_data(p_mail_data);
+                       EM_SAFE_FREE(p_mail_data);
+               }
+
+               if (attachment)
+                       emcore_free_attachment_data(&attachment, attachment_num, NULL);
+       }
+
+       EM_SAFE_FREE(encoded_subject);
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret : [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_parse_mime_file_to_mail(char *eml_file_path, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("eml_file_path : [%s], output_mail_data : [%p]", eml_file_path, output_mail_data);
+
+       int err = EMAIL_ERROR_NONE;
+       int ret = false;
+       int is_file = 1;
+       FILE *eml_fp = NULL;
+       struct _m_content_info *cnt_info = NULL;
+       struct _m_mesg *mmsg = NULL;
+
+
+       if (!eml_file_path || !output_mail_data || !output_attachment_data || !output_attachment_count) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       cnt_info = (struct _m_content_info *)em_malloc(sizeof(struct _m_content_info));
+       if (cnt_info == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       cnt_info->grab_type = GRAB_TYPE_TEXT | GRAB_TYPE_ATTACHMENT;
+
+       mmsg = (struct _m_mesg *)em_malloc(sizeof(struct _m_mesg));
+       if (mmsg == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       eml_fp = fopen(eml_file_path, "r");
+       if (eml_fp == NULL) {
+               EM_DEBUG_EXCEPTION("file open failed");
+               err = EMAIL_ERROR_ON_PARSING;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_mime_parse_header(eml_fp, is_file, &mmsg->rfc822header, &mmsg->header, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_mime_parse_header failed : [%d]", err);
+               err = EMAIL_ERROR_INVALID_DATA;
+               goto FINISH_OFF;
+       }
+
+       if (!mmsg->header->part_header) {
+               EM_DEBUG_EXCEPTION("Invalid eml format");
+               err = EMAIL_ERROR_INVALID_DATA;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_mime_parse_body(eml_fp, is_file, mmsg, cnt_info, NULL, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_mime_parse_body failed : [%d]", err);
+               err = EMAIL_ERROR_INVALID_DATA;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_make_mail_data_from_mime_data(mmsg, cnt_info, output_mail_data, output_attachment_data, output_attachment_count, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_make_mail_tbl_data_from_mime failed : [%d]", err);
+               goto FINISH_OFF;
+
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (eml_fp)
+               fclose(eml_fp);
+
+       if (mmsg)
+               emcore_mime_free_mime(mmsg);
+
+       if (cnt_info)
+               emcore_free_content_info(cnt_info);
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("err : %d", err);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_delete_parsed_data(email_mail_data_t *input_mail_data, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data : [%p]", input_mail_data);
+       int err = EMAIL_ERROR_NONE;
+       int ret = false;
+       char buf[512];
+
+       if (!input_mail_data) {
+               EM_DEBUG_EXCEPTION("Invliad parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ((input_mail_data->account_id != EML_FOLDER) && (!input_mail_data->mail_id)) {
+               EM_DEBUG_EXCEPTION("Invliad parameter: account_id[%d], mail_id[%d]", input_mail_data->account_id, input_mail_data->mail_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       eml_data_count = eml_data_count - 1;
+
+       if (eml_data_count == 0) {
+               SNPRINTF(buf, sizeof(buf), "%s%s%d", MAILHOME, DIR_SEPERATOR, input_mail_data->account_id);
+       } else {
+               SNPRINTF(buf, sizeof(buf), "%s%s%d%s%d", MAILHOME, DIR_SEPERATOR, input_mail_data->account_id, DIR_SEPERATOR, input_mail_data->mail_id);
+       }
+
+       EM_DEBUG_LOG("Directory : [%s]", buf);
+
+       if (!emstorage_delete_dir(buf, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_delete_dir failed");
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_get_mime_entity(char *mime_path, char **output_path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mime_path : [%s], output_path : [%p]", mime_path, *output_path);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int is_file = 1;
+       int search = 0;
+       long start_mime_entity = 0;
+       long end_mime_entity = 0;
+       char buf[MIME_LINE_LEN] = {0x00, };
+       char *mime_entity_path = NULL;
+       char *content_type = NULL;
+       char boundary[BOUNDARY_LEN] = {0x00,};
+       char *boundary_string = NULL;
+       char *p_mime_entity = NULL;
+       FILE *fp_read = NULL;
+       FILE *fp_write = NULL;
+       struct _m_mesg *mmsg = NULL;
+
+       if (!mime_path) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* Get the header info */
+       mmsg = (struct _m_mesg *)em_malloc(sizeof(struct _m_mesg));
+       if (mmsg == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       fp_read = fopen(mime_path, "r");
+       if (fp_read == NULL) {
+               EM_DEBUG_EXCEPTION("File open(read) is failed : filename [%s]", mime_path);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_mime_parse_header(fp_read, is_file, &mmsg->rfc822header, &mmsg->header, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_mime_parse_header failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Parsing the mime header */
+       content_type = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_TYPE, NULL);
+       EM_DEBUG_LOG("Content_type : [%s]", content_type);
+       if (strcasestr(content_type, "signed") == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid parameter : No signed mail");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* Create mime_entity file */
+       if (!emcore_get_temp_file_name(&mime_entity_path, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_temp_file_name failed[%d]", err);
+               goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG("mime_entity_path = %s", mime_entity_path);
+
+       fp_write = fopen(mime_entity_path, "w");
+       if (fp_write == NULL) {
+               EM_DEBUG_EXCEPTION("File open(write) is failed : filename [%s]", mime_entity_path);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       boundary_string = emcore_mime_get_header_value(mmsg->header->part_header, CONTENT_BOUNDARY, NULL);
+       SNPRINTF(boundary, BOUNDARY_LEN, "--%s%s", boundary_string, CRLF_STRING);
+
+       while (TRUE) {
+               if (!emcore_get_line_from_file((void *)fp_read, buf, MIME_LINE_LEN, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_mime_get_line_from_file failed [%d]", err);
+                       EM_DEBUG_LOG("this mail is partial body");
+                       err = EMAIL_ERROR_INVALID_MAIL;
+                       break;
+               }
+
+               if (!strcmp(buf, boundary)) {
+                       search++;
+                       if (search == 1) {
+                               start_mime_entity = ftell(fp_read);
+                               if( start_mime_entity < 0 ) { /*prevent 24473*/
+                                       EM_DEBUG_EXCEPTION("ftell failed [%s]", EM_STRERROR(errno));
+                                       goto FINISH_OFF;
+                               }
+                       } else if (search == 2) {
+                               end_mime_entity = ftell(fp_read);
+                               if( end_mime_entity < 0 ) { /*prevent 24473*/
+                                       EM_DEBUG_EXCEPTION("ftell failed [%s]", EM_STRERROR(errno));
+                                       goto FINISH_OFF;
+                               }
+                               break;
+                       }
+               }
+       }
+
+       p_mime_entity = em_malloc(end_mime_entity - start_mime_entity);
+       if (p_mime_entity == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (fseek(fp_read, start_mime_entity, SEEK_SET) < 0) {
+               EM_DEBUG_EXCEPTION("fseek failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* +2 : CRLF line */
+       if ((ret = fread(p_mime_entity, 1, end_mime_entity - (start_mime_entity + EM_SAFE_STRLEN(boundary) + 2), fp_read)) < 0) {
+               EM_DEBUG_EXCEPTION("fread failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       fprintf(fp_write, "%s", p_mime_entity);
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (fp_read)
+               fclose(fp_read);
+
+       if (fp_write)
+               fclose(fp_write);
+
+       if (mmsg)
+               emcore_mime_free_mime(mmsg);
+
+       if (output_path)
+               *output_path = mime_entity_path;
+
+       if (err_code)
+               *err_code = err;
+
+       EM_SAFE_FREE(p_mime_entity);
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emcore_decode_body_text_from_file(FILE *stream, char *boundary_str, int encoding, int mode, int is_text, int fd, char **holder, int *end_of_parsing, int *size)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error = EMAIL_ERROR_NONE;
+       int p_size = 0;
+       int partial_body = 0;
+       int dec_len = 0;
+       long start_location = 0;
+       long end_location = 0;
+       char boundary[BOUNDARY_LEN] = {0x00, };
+       char boundary_end[BOUNDARY_LEN] = {0x00, };
+       char buf[MIME_LINE_LEN] = {0x00, };
+       char *body = NULL;
+       int modified_body_size = 0;
+       char *modified_body = NULL;
+
+       if (boundary_str) {
+               /*  if there boundary, this content is from current line to ending boundary */
+               memset(boundary, 0x00, BOUNDARY_LEN);
+               memset(boundary_end, 0x00, BOUNDARY_LEN);
+
+               SNPRINTF(boundary, BOUNDARY_LEN, "--%s%s", boundary_str, CRLF_STRING);
+               SNPRINTF(boundary_end, BOUNDARY_LEN, "--%s%s", boundary_str, "--\r\n");
+       }
+
+       start_location = ftell(stream);
+       if(start_location < 0 ) { /*prevent 35555*/
+               error = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("ftell failed : %s", EM_STRERROR(errno));
+               goto FINISH_OFF;
+       }
+
+       while (TRUE) {
+               if (!emcore_get_line_from_file(stream, buf, MIME_LINE_LEN, &error)) {
+                       if (error != EMAIL_ERROR_NO_MORE_DATA) {
+                               EM_DEBUG_EXCEPTION("emcore_get_line_from_file failed");
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+
+                       partial_body = 1;
+                       *end_of_parsing = 1;
+                       break;
+               }
+
+               if (boundary_str)  {
+                       if (!strcmp(buf, boundary))  {  /*  the other part started. the parsing of other part will be started */
+                               *end_of_parsing = 0;
+                               break;
+                       }
+                       else if (!strcmp(buf, boundary_end))  { /*  if ending boundary, the parsing of other multipart will be started */
+                               *end_of_parsing = 1;
+                               break;
+                       }
+               }
+       }
+
+       end_location = ftell(stream);
+       if(end_location < 0 ) { /*prevent 35555*/
+               error = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("ftell failed : %s", EM_STRERROR(errno));
+               goto FINISH_OFF;
+       }
+
+       if (partial_body)
+               p_size = end_location - start_location;
+       else
+               p_size = end_location - start_location - EM_SAFE_STRLEN(buf);
+
+       body = em_malloc(p_size + 1);
+       if (body == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       fseek(stream, start_location, SEEK_SET);
+       if (fread(body, sizeof(char), p_size, stream) != p_size) {
+               EM_DEBUG_EXCEPTION("fread failed");
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (mode > SAVE_TYPE_SIZE) {    /*  decode content */
+               emcore_decode_body_text(body, p_size, encoding, &dec_len, &error);
+
+               if (is_text) {
+                       modified_body = em_replace_all_string(body, "cid:", "");
+                       modified_body_size = EM_SAFE_STRLEN(modified_body); /*prevent 35585 */
+               }
+
+               if (modified_body == NULL) {
+                       modified_body = em_malloc(dec_len + 1);
+                       if (modified_body == NULL) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       memcpy(modified_body, body, dec_len);  /*prevent 35585 */
+                       modified_body_size = dec_len;
+               }
+
+               if (mode == SAVE_TYPE_BUFFER)  {   /*  save content to buffer */
+                       *holder = EM_SAFE_STRDUP(modified_body);
+               } else if (mode == SAVE_TYPE_FILE)  {   /*  save content to file */
+                       if (write(fd, modified_body, modified_body_size) != modified_body_size)  {
+                               EM_DEBUG_EXCEPTION("write failed");
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       fseek((FILE *)stream, end_location, SEEK_SET);
+
+FINISH_OFF:
+
+       if (size)
+               *size = modified_body_size;
+
+       EM_SAFE_FREE(modified_body);
+       EM_SAFE_FREE(body); /*prevent 35585 */
+       return error;
+}
+
+int emcore_decode_body_text_from_sock(void *stream, char *boundary_str, int encoding, int mode, int is_text, int fd, char **holder, int *end_of_parsing, int *size)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int error = EMAIL_ERROR_NONE;
+       int sz = 0;
+       int dec_len = 0;
+       char boundary[BOUNDARY_LEN] = {0x00, };
+       char boundary_end[BOUNDARY_LEN] = {0x00, };
+       char buf[MIME_LINE_LEN] = {0x00, };
+       char *result_buffer = NULL;
+       int result_buffer_size = 0;
+       char *pTemp = NULL;
+
+       if (boundary_str) {
+               /*  if there boundary, this content is from current line to ending boundary */
+               memset(boundary, 0x00, BOUNDARY_LEN);
+               memset(boundary_end, 0x00, BOUNDARY_LEN);
+
+               SNPRINTF(boundary, BOUNDARY_LEN, "--%s%s", boundary_str, CRLF_STRING);
+               SNPRINTF(boundary_end, BOUNDARY_LEN, "--%s%s", boundary_str, "--\r\n");
+       }
+
+       while (TRUE) {
+               if (!emcore_check_thread_status())  {
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_CANCELLED");
+                       error = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_mime_get_line_from_sock(stream, buf, MIME_LINE_LEN, &error)) {
+                       if (error != EMAIL_ERROR_NO_MORE_DATA) {
+                               EM_DEBUG_EXCEPTION("emcore_mime_get_line_from_sock failed");
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+
+                       EM_DEBUG_LOG("This mail is partial body");
+
+                       *end_of_parsing = 1;
+
+                       error = EMAIL_ERROR_NONE;
+
+                       break;
+               }
+
+               if (boundary_str)  {
+                       if (!strcmp(buf, boundary))  {  /*  the other part started. the parsing of other part will be started */
+                               *end_of_parsing = 0;
+                               break;
+                       }
+                       else if (!strcmp(buf, boundary_end))  { /*  if ending boundary, the parsing of other multipart will be started */
+                               *end_of_parsing = 1;
+                               break;
+                       }
+               }
+
+               /*  parsing string started by '.' in POP3 */
+               if ((buf[0] == '.' && buf[1] == '.') && (encoding == ENCQUOTEDPRINTABLE || encoding == ENC7BIT))  {
+                               strncpy(buf, buf+1, MIME_LINE_LEN-1);
+                               buf[EM_SAFE_STRLEN(buf)] = NULL_CHAR;
+               }
+
+               if (encoding == ENCBASE64)  {
+                               if (EM_SAFE_STRLEN(buf) >= 2)
+                                       buf[EM_SAFE_STRLEN(buf)-2] = NULL_CHAR;
+               } else if (encoding == ENCQUOTEDPRINTABLE)  {
+/*                     if (strcmp(buf, CRLF_STRING) == 0 */
+/*                                     continue */
+               }
+
+               dec_len = EM_SAFE_STRLEN(buf);
+
+               if (mode > SAVE_TYPE_SIZE) {    /*  decode content */
+                       emcore_decode_body_text(buf, dec_len, encoding, &dec_len, &error);
+
+                       if (is_text) {
+                               result_buffer = em_replace_string(buf, "cid:", "");
+                               if (result_buffer)
+                                       result_buffer_size = EM_SAFE_STRLEN(result_buffer);
+                       }
+
+                       if (result_buffer == NULL) {
+                               result_buffer      = strdup(buf); /*prevent 35499*/
+                               result_buffer_size = dec_len;
+                       }
+
+                       if (mode == SAVE_TYPE_BUFFER)  {   /*  save content to buffer */
+                               pTemp = realloc(*holder, sz + result_buffer_size + 2);
+                               if (!pTemp)  {
+                                       EM_DEBUG_EXCEPTION("realloc failed...");
+                                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+
+                                               EM_SAFE_FREE(*holder);
+                                               EM_SAFE_FREE(result_buffer);
+                                               goto FINISH_OFF;
+                               }
+                                       else
+                                       *holder = pTemp;
+
+                                       memcpy(*holder + sz, result_buffer, result_buffer_size);
+                                       (*holder)[sz + EM_SAFE_STRLEN(result_buffer) + 1] = NULL_CHAR;
+                       } else if (mode == SAVE_TYPE_FILE)  {   /*  save content to file */
+                               if (write(fd, result_buffer, result_buffer_size) != result_buffer_size)  {
+                                       EM_DEBUG_EXCEPTION("write failed");
+                                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                                       goto FINISH_OFF;
+                               }
+                       }
+
+                       EM_SAFE_FREE(result_buffer);
+               }
+               sz += dec_len;
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(result_buffer); /*prevent 35499*/
+
+       if (error == EMAIL_ERROR_NONE) {
+               if (size)
+                       *size = sz;
+       }
+
+       EM_DEBUG_FUNC_END("error [%d], sz[%d]", error, sz);
+       return error;
+}
+
diff --git a/email-core/email-core-mm-callbacks.c b/email-core/email-core-mm-callbacks.c
new file mode 100755 (executable)
index 0000000..1c39b6c
--- /dev/null
@@ -0,0 +1,464 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-mm_callbacks.c
+ * Desc :  mm_callbacks for IMAP-2004g
+ *
+ * Auth :  
+ *
+ * History : 
+ * 2006.08.22  :  created
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "email-internal-types.h"
+#include "c-client.h"
+#include "email-core-global.h"
+#include "email-core-utils.h"
+#include "email-debug-log.h"
+#include "email-core-mailbox.h"
+#include "email-core-account.h"
+
+static void mm_get_error(char *string, int *err_code);
+
+/*
+ * callback mm_lsub
+ *             get subscribed mailbox list
+ */
+INTERNAL_FUNC void mm_lsub(MAILSTREAM *stream, int delimiter, char *mailbox, long attributes)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       email_callback_holder_t *p_holder = (email_callback_holder_t *)stream->sparep;
+       email_mailbox_t *p, *p_old = p_holder->data;
+       int count = p_holder->num;
+       char *s, *enc_path;
+
+       /* memory allocation */
+       p = realloc(p_old, sizeof(email_mailbox_t) * (count + 1));
+       if (!p) return ;
+
+       /* uw-imap mailbox name format (ex : "{mail.test.com...}inbox" or "{mail.test.com...}anybox/anysubbox") */
+       enc_path = strchr(mailbox, '}');
+       if (enc_path)   
+               enc_path += 1;
+       else {
+               emcore_free_mailbox_list(&p, count+1);
+               return ;
+       }
+
+       /* Convert UTF7 mailbox name to UTF8 mailbox name */
+
+       /* convert directory delimiter to '/' */
+       for (s = enc_path; *s; s++) {
+               if (*s == (char)delimiter) {
+                       *s = '/';
+               }
+       }
+
+       /* coyp string */
+       p[count].mailbox_name = cpystr(enc_path);
+       p[count].alias        = cpystr(enc_path);
+       p[count].local        = 0;
+       p[count].account_id   = stream->spare8;
+
+
+       p_holder->data = p;
+       p_holder->num++;
+
+       /* ignore attributes */
+/*  if (attributes & latt_noinferiors) fputs (", no inferiors", fp_log); */
+/*  if (attributes & latt_noselect) fputs (", no select", fp_log); */
+/*  if (attributes & latt_marked) fputs (", marked", fp_log); */
+/*  if (attributes & latt_unmarked) fputs (", unmarked", fp_log); */
+       EM_DEBUG_FUNC_END();
+}
+
+
+/*
+ * callback mm_lsub
+ * get mailbox list
+ */
+INTERNAL_FUNC void mm_list(MAILSTREAM *stream, int delimiter, char *mailbox, long attributes)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       email_callback_holder_t *p_holder = (email_callback_holder_t *)stream->sparep;
+       email_internal_mailbox_t *p, *p_old = p_holder->data;
+       int count = p_holder->num;
+       char *s, *enc_path;
+
+       /* memory allocation */
+       p = realloc(p_old, sizeof(email_internal_mailbox_t) * (count + 1));
+       if (!p) return ;
+
+       /* uw-imap mailbox name format (ex : "{mail.test.com...}inbox" or "{mail.test.com...}anybox/anysubbox") */
+       enc_path = strchr(mailbox, '}');
+       if (enc_path)   
+               enc_path += 1;
+       else {
+               emcore_free_internal_mailbox(&p, count+1, NULL);
+               return ;
+       }
+
+       /* convert directory delimiter to '/' */
+       for (s = enc_path;*s;s++) 
+               if (*s == (char)delimiter) 
+                       *s = '/';
+
+       /* copy string */
+       memset(p + count, 0x00, sizeof(email_internal_mailbox_t));
+
+#ifdef __FEATURE_XLIST_SUPPORT__
+       if(attributes & LATT_XLIST_INBOX)
+               p[count].mailbox_type = EMAIL_MAILBOX_TYPE_INBOX;
+       else if(attributes & LATT_XLIST_ALL)
+               p[count].mailbox_type = EMAIL_MAILBOX_TYPE_ALL_EMAILS;
+       else if(attributes & LATT_XLIST_DRAFTS)
+               p[count].mailbox_type = EMAIL_MAILBOX_TYPE_DRAFT;
+       else if(attributes & LATT_XLIST_SENT)
+               p[count].mailbox_type = EMAIL_MAILBOX_TYPE_SENTBOX;
+       else if(attributes & LATT_XLIST_JUNK)
+               p[count].mailbox_type = EMAIL_MAILBOX_TYPE_SPAMBOX;
+       else if(attributes & LATT_XLIST_FLAGGED)
+               p[count].mailbox_type = EMAIL_MAILBOX_TYPE_FLAGGED;
+       else if(attributes & LATT_XLIST_TRASH)
+               p[count].mailbox_type = EMAIL_MAILBOX_TYPE_TRASH;
+#endif /* __FEATURE_XLIST_SUPPORT__ */
+
+       if(attributes & LATT_NOSELECT)
+               p[count].no_select    = true;
+
+       if(p[count].mailbox_type == EMAIL_MAILBOX_TYPE_INBOX) /* For exception handling of Gmail inbox*/
+               p[count].mailbox_name  = cpystr("INBOX");
+       else
+               p[count].mailbox_name  = cpystr(enc_path);
+
+       EM_DEBUG_LOG("mailbox name [%s] mailbox_type [%d] no_select [%d]", p[count].mailbox_name, p[count].mailbox_type, p[count].no_select);
+
+       p[count].alias = emcore_get_alias_of_mailbox((const char *)enc_path);
+       p[count].local = 0;
+
+       EM_DEBUG_LOG("mm_list account_id %d", stream->spare8);
+
+       char *tmp = NULL;
+       /* in mailbox name parse n get user = %d - which is account_id */
+       tmp = strstr(mailbox, "user=");
+       if (tmp) {
+               tmp = tmp+5;
+               for (s = tmp; *s != '/'; s++);
+               *s = '\0';
+               p[count].account_id = atoi(tmp);
+       }
+       EM_DEBUG_LOG("mm_list account_id %d ", p[count].account_id);
+
+       p_holder->data = p;
+       p_holder->num++;
+
+       /* ignore attributes */
+       EM_DEBUG_FUNC_END();
+}
+
+
+/*
+ * callback mm_status
+ * get mailbox status
+ */
+INTERNAL_FUNC void mm_status(MAILSTREAM *stream, char *mailbox, MAILSTATUS* status)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       email_callback_holder_t *p = stream->sparep;
+
+       EM_DEBUG_FUNC_BEGIN();
+       if (status->flags & SA_MESSAGES) 
+               p->num = status->messages;
+       if (status->flags & SA_UNSEEN) 
+               p->data = (void *)status->unseen;
+       EM_DEBUG_FUNC_END();
+}
+
+/* callback mm_login
+ * get user_name and password
+ */
+
+INTERNAL_FUNC void mm_login(NETMBX *mb, char *user, char *pwd, long trial)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int account_id;
+       email_account_t *ref_account = NULL;
+       char *username = NULL;
+       char *password = NULL;
+
+       if (!mb->user[0])  {
+               EM_DEBUG_EXCEPTION("invalid account_id...");
+               goto FINISH_OFF;
+       }
+       
+       account_id = atoi(mb->user);
+
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed");
+               goto FINISH_OFF;
+       }
+
+       if (ref_account->incoming_server_user_name == NULL) {
+               EM_DEBUG_EXCEPTION("invalid incoming_server_user_name...");
+               goto FINISH_OFF;
+       }
+       username = EM_SAFE_STRDUP(ref_account->incoming_server_user_name);
+
+       if (ref_account->incoming_server_password == NULL) {
+               EM_SAFE_FREE(username);
+               EM_DEBUG_EXCEPTION("invalid password...");
+               goto FINISH_OFF;
+       }
+
+       password = EM_SAFE_STRDUP(ref_account->incoming_server_password);
+
+       if(EM_SAFE_STRLEN(username) > 0 && EM_SAFE_STRLEN(password) > 0) { /*prevent 34355*/
+               strcpy(user, username);
+               strcpy(pwd, password);
+       }
+       else
+               EM_DEBUG_EXCEPTION("User Information is NULL || EM_SAFE_STRLEN is 0 ");
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       EM_SAFE_FREE(username);
+       EM_SAFE_FREE(password);
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+INTERNAL_FUNC void mm_dlog(char *string)
+{
+#ifdef FEATURE_CORE_DEBUG
+       EM_DEBUG_LOG("IMAP_TOOLKIT_DLOG [%s]", string);
+#endif
+}
+
+INTERNAL_FUNC void mm_log(char *string, long errflg)
+{
+       
+       switch ((short)errflg)  {
+               case NIL:
+                       EM_DEBUG_LOG("IMAP_TOOLKIT_LOG NIL [%s]", string);
+                       break;
+                       
+               case WARN:
+                       EM_DEBUG_LOG("IMAP_TOOLKIT_LOG WARN [%s]", string);
+                       break;
+                       
+               case PARSE:
+                       EM_DEBUG_LOG("IMAP_TOOLKIT_LOG PARSE [%s]", string);
+                       break;
+                       
+               case BYE:
+                       EM_DEBUG_LOG("IMAP_TOOLKIT_LOG BYE [%s]", string);
+                       break;
+                       
+               case TCPDEBUG:
+                       EM_DEBUG_LOG("IMAP_TOOLKIT_LOG TCPDEBUG [%s]", string);
+                       break;
+                       
+               case ERROR: {
+                       email_session_t *session = NULL;
+                       
+                       EM_DEBUG_EXCEPTION("IMAP_TOOLKIT_LOG ERROR [%s]", string);
+
+                       emcore_get_current_session(&session);
+                       
+                       if (session) {
+                               mm_get_error(string, &session->error);
+                               EM_DEBUG_EXCEPTION("IMAP_TOOLKIT_LOG ERROR [%d]", session->error);
+                       }
+                       
+                       break;
+               }
+       }
+}
+
+INTERNAL_FUNC void mm_searched(MAILSTREAM *stream, unsigned long number)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p], number [%d]", stream, number);
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC void mm_exists(MAILSTREAM *stream, unsigned long number)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p], number [%d]", stream, number);
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC void mm_expunged(MAILSTREAM *stream, unsigned long number)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p], number [%d]", stream, number);
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC void mm_flags(MAILSTREAM *stream, unsigned long number)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p], number [%d]", stream, number);
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC void mm_notify(MAILSTREAM *stream, char *string, long errflg)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       mm_log(string, errflg);
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC void mm_critical(MAILSTREAM *stream)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p]", stream);
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC void mm_nocritical(MAILSTREAM *stream)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p]", stream);
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC long mm_diskerror(MAILSTREAM *stream, long errcode, long serious)
+{
+       EM_DEBUG_FUNC_BEGIN("stream [%p] errcode[%d] serious[%d]", stream, errcode, serious);
+#if UNIXLIKE
+       kill(getpid(), SIGSTOP);
+#else
+       abort();
+#endif
+       EM_DEBUG_FUNC_END();
+       return NIL;
+}
+
+INTERNAL_FUNC void mm_fatal(char *string)
+{
+       EM_DEBUG_EXCEPTION("%s", string);
+}
+
+INTERNAL_FUNC void mm_get_error(char *string, int *err_code)
+{
+       if (!string || !err_code)
+               return ;
+
+       EM_DEBUG_LOG("string [%s]", string);
+
+       if (strstr(string, "login failure") || strstr(string, "Login aborted") || strstr(string, "Can't login"))
+               *err_code = EMAIL_ERROR_LOGIN_FAILURE;
+       else if (strstr(string, "Scan not valid"))
+               *err_code = EMAIL_ERROR_SCAN_NOT_SUPPORTED;
+       else if (strstr(string, "Authentication cancelled"))
+               *err_code = EMAIL_ERROR_AUTHENTICATE;
+       else if (strstr(string, "authuser"))
+               *err_code = EMAIL_ERROR_AUTH_NOT_SUPPORTED;
+       else if (strstr(string, "negotiate TLS"))
+               *err_code = EMAIL_ERROR_CANNOT_NEGOTIATE_TLS;
+       else if (strstr(string, "TLS/SSL failure"))
+               *err_code = EMAIL_ERROR_TLS_SSL_FAILURE;
+       else if (strstr(string, "STARTLS"))
+               *err_code = EMAIL_ERROR_STARTLS;
+       else if (strstr(string, "TLS unavailable"))
+               *err_code = EMAIL_ERROR_TLS_NOT_SUPPORTED;
+       else if (strstr(string, "Can't access"))
+               *err_code = EMAIL_ERROR_IMAP4_APPEND_FAILURE;
+       else if (strstr(string, "Can not authenticate"))
+               *err_code = EMAIL_ERROR_AUTHENTICATE;
+       else if (strstr(string, "Unexpected IMAP response") || strstr(string, "hello"))
+               *err_code = EMAIL_ERROR_INVALID_RESPONSE;
+       else if (strstr(string, "NOTIMAP4REV1"))
+               *err_code = EMAIL_ERROR_COMMAND_NOT_SUPPORTED;
+       else if (strstr(string, "Anonymous"))
+               *err_code = EMAIL_ERROR_ANNONYM_NOT_SUPPORTED;
+       else if (strstr(string, "connection broken"))
+               *err_code = EMAIL_ERROR_CONNECTION_BROKEN;
+       else if (strstr(string, "SMTP greeting"))
+               *err_code = EMAIL_ERROR_NO_RESPONSE;
+       else if (strstr(string, "ESMTP failure"))
+               *err_code = EMAIL_ERROR_SMTP_SEND_FAILURE;
+       else if (strstr(string, "socket") || strstr(string, "Socket"))
+               *err_code = EMAIL_ERROR_SOCKET_FAILURE;
+       else if (strstr(string, "connect to") || strstr(string, "Connection failed"))
+               *err_code = EMAIL_ERROR_CONNECTION_FAILURE;
+       else if (strstr(string, "Certificate failure"))
+               *err_code = EMAIL_ERROR_CERTIFICATE_FAILURE;
+       else if (strstr(string, "ESMTP failure"))
+               *err_code = EMAIL_ERROR_INVALID_PARAM;
+       else if (strstr(string, "No such host"))
+               *err_code = EMAIL_ERROR_NO_SUCH_HOST;
+       else if (strstr(string, "host") || strstr(string, "Host"))
+               *err_code = EMAIL_ERROR_INVALID_SERVER;
+       else if (strstr(string, "SELECT failed"))
+               *err_code = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+       else if (strstr(string, "15 minute"))
+               *err_code = EMAIL_ERROR_LOGIN_ALLOWED_EVERY_15_MINS;
+       else
+               *err_code = EMAIL_ERROR_UNKNOWN;
+}
+
+#ifdef __FEATURE_SUPPORT_IMAP_ID__
+INTERNAL_FUNC void mm_imap_id (char **id_string)
+{
+       EM_DEBUG_FUNC_BEGIN("id_string [%p]", id_string);
+
+       int   err = EMAIL_ERROR_NONE;
+       /*
+       char *result_string = NULL;
+       char *tag_string = "ID (\"os\" \"" IMAP_ID_OS "\" \"os-version\" \"" IMAP_ID_OS_VERSION "\" \"vendor\" \"" IMAP_ID_VENDOR "\" \"device\" \"" IMAP_ID_DEVICE_NAME "\" \"AGUID\" \"" IMAP_ID_AGUID "\" \"ACLID\" \"" IMAP_ID_ACLID "\"";
+       int   tag_length = 0;
+       */
+
+       if (id_string == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       *id_string = NULL;
+
+       /*
+       tag_length = EM_SAFE_STRLEN(tag_string);
+       result_string = EM_SAFE_STRDUP(tag_string);
+
+       if(result_string == NULL) {
+               EM_DEBUG_EXCEPTION("malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       *id_string = result_string;
+       */
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+}
+#endif /* __FEATURE_SUPPORT_IMAP_ID__ */
+/* EOF */
diff --git a/email-core/email-core-signal.c b/email-core/email-core-signal.c
new file mode 100755 (executable)
index 0000000..50cb794
--- /dev/null
@@ -0,0 +1,236 @@
+/*\r
+*  email-service\r
+*\r
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
+*\r
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
+*\r
+* Licensed under the Apache License, Version 2.0 (the "License");\r
+* you may not use this file except in compliance with the License.\r
+* You may obtain a copy of the License at\r
+*\r
+* http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*\r
+*/\r
+\r
+/*\r
+ * email-core-signal.c\r
+ *\r
+ *  Created on: 2012. 11. 22.\r
+ *      Author: kyuho.jo@samsung.com\r
+ */\r
+#include <dbus/dbus.h>\r
+\r
+#include "email-core-signal.h"\r
+#include "email-core-utils.h"\r
+#include "email-internal-types.h"\r
+#include "email-debug-log.h"\r
+\r
+#define EMAIL_STORAGE_CHANGE_NOTI       "User.Email.StorageChange"\r
+#define EMAIL_NETOWRK_CHANGE_NOTI       "User.Email.NetworkStatus"\r
+#define EMAIL_RESPONSE_TO_API_NOTI      "User.Email.ResponseToAPI"\r
+\r
+#define DBUS_SIGNAL_PATH_FOR_TASK_STATUS       "/User/Email/TaskStatus"\r
+#define DBUS_SIGNAL_INTERFACE_FOR_TASK_STATUS  "User.Email.TaskStatus"\r
+#define DBUS_SIGNAL_NAME_FOR_TASK_STATUS       "email"\r
+\r
+static pthread_mutex_t _dbus_noti_lock = PTHREAD_MUTEX_INITIALIZER;\r
+\r
+typedef enum\r
+{\r
+       _NOTI_TYPE_STORAGE         = 0,\r
+       _NOTI_TYPE_NETWORK         = 1,\r
+       _NOTI_TYPE_RESPONSE_TO_API = 2,\r
+} enotitype_t;\r
+\r
+INTERNAL_FUNC int emcore_initialize_signal()\r
+{\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_finalize_signal()\r
+{\r
+       DELETE_CRITICAL_SECTION(_dbus_noti_lock);\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+static int emcore_send_signal(enotitype_t notiType, int subType, int data1, int data2, char *data3, int data4)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN();\r
+       EM_PROFILE_BEGIN(profile_emcore_send_signal);\r
+\r
+       int ret = 0;\r
+       DBusConnection *connection;\r
+       DBusMessage     *signal = NULL;\r
+       DBusError          dbus_error;\r
+       dbus_uint32_t   error;\r
+       const char       *nullString = "";\r
+\r
+       ENTER_CRITICAL_SECTION(_dbus_noti_lock);\r
+\r
+       dbus_error_init (&dbus_error);\r
+       connection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_error);\r
+\r
+       if (connection == NULL) {\r
+               EM_DEBUG_LOG("dbus_bus_get is failed");\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       if (notiType == _NOTI_TYPE_STORAGE) {\r
+               signal = dbus_message_new_signal("/User/Email/StorageChange", EMAIL_STORAGE_CHANGE_NOTI, "email");\r
+\r
+               if (signal == NULL) {\r
+                       EM_DEBUG_EXCEPTION("dbus_message_new_signal is failed");\r
+                       goto FINISH_OFF;\r
+               }\r
+               EM_DEBUG_LOG("/User/Email/StorageChange Signal is created by dbus_message_new_signal");\r
+\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &subType, DBUS_TYPE_INVALID);\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &data1, DBUS_TYPE_INVALID);\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &data2, DBUS_TYPE_INVALID);\r
+               if (data3 == NULL)\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &nullString, DBUS_TYPE_INVALID);\r
+               else\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &data3, DBUS_TYPE_INVALID);\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &data4, DBUS_TYPE_INVALID);\r
+       }\r
+       else if (notiType == _NOTI_TYPE_NETWORK) {\r
+               signal = dbus_message_new_signal("/User/Email/NetworkStatus", EMAIL_NETOWRK_CHANGE_NOTI, "email");\r
+\r
+               if (signal == NULL) {\r
+                       EM_DEBUG_EXCEPTION("dbus_message_new_signal is failed");\r
+                       goto FINISH_OFF;\r
+               }\r
+\r
+               EM_DEBUG_LOG("/User/Email/NetworkStatus Signal is created by dbus_message_new_signal");\r
+\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &subType, DBUS_TYPE_INVALID);\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &data1, DBUS_TYPE_INVALID);\r
+               if (data3 == NULL)\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &nullString, DBUS_TYPE_INVALID);\r
+               else\r
+                       dbus_message_append_args(signal, DBUS_TYPE_STRING, &data3, DBUS_TYPE_INVALID);\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &data2, DBUS_TYPE_INVALID);\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &data4, DBUS_TYPE_INVALID);\r
+       }\r
+       else if (notiType == _NOTI_TYPE_RESPONSE_TO_API) {\r
+               signal = dbus_message_new_signal("/User/Email/ResponseToAPI", EMAIL_RESPONSE_TO_API_NOTI, "email");\r
+\r
+               if (signal == NULL) {\r
+                       EM_DEBUG_EXCEPTION("dbus_message_new_signal is failed");\r
+                       goto FINISH_OFF;\r
+               }\r
+\r
+               EM_DEBUG_LOG("/User/Email/ResponseToAPI Signal is created by dbus_message_new_signal");\r
+\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &subType, DBUS_TYPE_INVALID);\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &data1, DBUS_TYPE_INVALID);\r
+               dbus_message_append_args(signal, DBUS_TYPE_INT32, &data2, DBUS_TYPE_INVALID);\r
+       }\r
+       else {\r
+               EM_DEBUG_EXCEPTION("Wrong notification type [%d]", notiType);\r
+               error = EMAIL_ERROR_IPC_CRASH;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       if (!dbus_connection_send(connection, signal, &error)) {\r
+               EM_DEBUG_LOG("dbus_connection_send is failed [%d]", error);\r
+       }\r
+       else {\r
+               EM_DEBUG_LOG("dbus_connection_send is successful");\r
+               ret = 1;\r
+       }\r
+\r
+/*     EM_DEBUG_LOG("Before dbus_connection_flush");    */\r
+/*     dbus_connection_flush(connection);               */\r
+/*     EM_DEBUG_LOG("After dbus_connection_flush");     */\r
+\r
+       ret = true;\r
+FINISH_OFF:\r
+       if (signal)\r
+               dbus_message_unref(signal);\r
+\r
+       LEAVE_CRITICAL_SECTION(_dbus_noti_lock);\r
+       EM_PROFILE_END(profile_emcore_send_signal);\r
+       EM_DEBUG_FUNC_END("ret [%d]", ret);\r
+       return ret;\r
+}\r
+\r
+\r
+INTERNAL_FUNC int emcore_notify_storage_event(email_noti_on_storage_event transaction_type, int data1, int data2 , char *data3, int data4)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("transaction_type[%d], data1[%d], data2[%d], data3[%p], data4[%d]", transaction_type, data1, data2, data3, data4);\r
+       return emcore_send_signal(_NOTI_TYPE_STORAGE, (int)transaction_type, data1, data2, data3, data4);\r
+}\r
+\r
+INTERNAL_FUNC int emcore_notify_network_event(email_noti_on_network_event status_type, int data1, char *data2, int data3, int data4)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("status_type[%d], data1[%d], data2[%p], data3[%d], data4[%d]", status_type, data1, data2, data3, data4);\r
+       return emcore_send_signal(_NOTI_TYPE_NETWORK, (int)status_type, data1, data3, data2, data4);\r
+}\r
+\r
+INTERNAL_FUNC int emcore_notify_response_to_api(email_event_type_t event_type, int data1, int data2)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("event_type[%d], data1[%d], data2[%p], data3[%d], data4[%d]", event_type, data1, data2);\r
+       return emcore_send_signal(_NOTI_TYPE_RESPONSE_TO_API, (int)event_type, data1, data2, NULL, 0);\r
+}\r
+\r
+INTERNAL_FUNC int emcore_send_task_status_signal(email_task_type_t input_task_type, int input_task_id, email_task_status_type_t input_task_status, int input_param_1, int input_param_2)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_type [%d] input_task_id [%d] input_task_status [%d] input_param_1 [%d] input_param_2 [%d]", input_task_type, input_task_id, input_task_status, input_param_1, input_param_2);\r
+\r
+       int             err = EMAIL_ERROR_NONE;\r
+       DBusConnection *connection;\r
+       DBusMessage        *signal = NULL;\r
+       DBusError           dbus_error;\r
+       dbus_uint32_t   error;\r
+\r
+       ENTER_CRITICAL_SECTION(_dbus_noti_lock);\r
+\r
+       dbus_error_init (&dbus_error);\r
+       connection = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_error);\r
+\r
+       if (connection == NULL) {\r
+               EM_DEBUG_LOG("dbus_bus_get is failed");\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       signal = dbus_message_new_signal(DBUS_SIGNAL_PATH_FOR_TASK_STATUS, DBUS_SIGNAL_INTERFACE_FOR_TASK_STATUS, DBUS_SIGNAL_NAME_FOR_TASK_STATUS);\r
+\r
+       if (signal == NULL) {\r
+               EM_DEBUG_EXCEPTION("dbus_message_new_signal is failed");\r
+               goto FINISH_OFF;\r
+       }\r
+       EM_DEBUG_LOG("Signal for task status has been created by dbus_message_new_signal");\r
+\r
+       dbus_message_append_args(signal, DBUS_TYPE_INT32, &input_task_type, DBUS_TYPE_INVALID);\r
+       dbus_message_append_args(signal, DBUS_TYPE_INT32, &input_task_id, DBUS_TYPE_INVALID);\r
+       dbus_message_append_args(signal, DBUS_TYPE_INT32, &input_task_status, DBUS_TYPE_INVALID);\r
+       dbus_message_append_args(signal, DBUS_TYPE_INT32, &input_param_1, DBUS_TYPE_INVALID);\r
+       dbus_message_append_args(signal, DBUS_TYPE_INT32, &input_param_2, DBUS_TYPE_INVALID);\r
+\r
+       if (!dbus_connection_send(connection, signal, &error)) {\r
+               EM_DEBUG_LOG("dbus_connection_send is failed [%d]", error);\r
+       }\r
+       else {\r
+               EM_DEBUG_LOG("dbus_connection_send is successful");\r
+       }\r
+\r
+/*     EM_DEBUG_LOG("Before dbus_connection_flush");    */\r
+/*     dbus_connection_flush(connection);               */\r
+/*     EM_DEBUG_LOG("After dbus_connection_flush");     */\r
+\r
+FINISH_OFF:\r
+       if (signal)\r
+               dbus_message_unref(signal);\r
+\r
+       LEAVE_CRITICAL_SECTION(_dbus_noti_lock);\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
diff --git a/email-core/email-core-smime.c b/email-core/email-core-smime.c
new file mode 100755 (executable)
index 0000000..7783144
--- /dev/null
@@ -0,0 +1,943 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/* ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ***
+ *File :  email-core-smime.c
+ *Desc :  MIME Operation
+ *
+ *Auth :
+ *
+ *History :
+ *   2011.04.14  :  created
+ ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ***/
+#undef close
+
+#include <openssl/pkcs7.h>
+#include <openssl/pkcs12.h>
+#include <openssl/buffer.h>
+#include <openssl/pem.h>
+#include <openssl/err.h>
+
+#include "email-utilities.h"
+#include "email-core-global.h"
+#include "email-core-utils.h"
+#include "email-core-mail.h"
+#include "email-core-smtp.h"
+#include "email-storage.h"
+#include "email-core-smime.h"
+#include "email-core-cert.h"
+#include "email-debug-log.h"
+
+/* /opt/share/cert-svc/certs is a base path */
+
+#define SMIME_SIGNED_FILE "smime.p7s"
+#define SMIME_ENCRYPT_FILE "smime.p7m"
+#define DECRYPT_TEMP_FILE "decrypt_temp_file.eml"
+
+/* If not present then the default digest algorithm for signing key will be used SHA1 */
+static const EVP_MD *emcore_get_digest_algorithm(email_digest_type digest_type)
+{
+       const EVP_MD *digest_algo = NULL;
+       
+       switch (digest_type) {
+       case DIGEST_TYPE_MD5:
+               digest_algo = EVP_md5();
+               break;
+       case DIGEST_TYPE_SHA1:
+       default:
+               digest_algo = EVP_sha1();
+               break;
+       }
+
+       return digest_algo;
+}
+
+/* If not present then the default cipher algorithm for signing key will be used RC2(40) */
+static const EVP_CIPHER *emcore_get_cipher_algorithm(email_cipher_type cipher_type)
+{
+       const EVP_CIPHER *cipher = NULL;
+
+       switch (cipher_type) {
+       case CIPHER_TYPE_RC2_128 :
+               cipher = EVP_rc2_cbc();
+               break;
+       case CIPHER_TYPE_RC2_64 :
+               cipher = EVP_rc2_64_cbc();
+               break;
+       case CIPHER_TYPE_DES3 :
+               cipher = EVP_des_ede3_cbc();
+               break;
+       case CIPHER_TYPE_DES :
+               cipher = EVP_des_cbc();
+               break;
+#ifdef __FEATURE_USE_MORE_CIPHER_TYPE__
+       case CIPHER_TYPE_SEED :
+               cipher = EVP_seed_cbc();
+               break;
+       case CIPHER_TYPE_AES128 :
+               cipher = EVP_aes_128_cbc();
+               break;
+       case CIPHER_TYPE_AES192 :
+               cipher = EVP_aes_192_cbc();
+               break;
+       case CIPHER_TYPE_AES256 :
+               cipher = EVP_aes_256_cbc();
+               break;
+#ifndef OPENSSL_NO_CAMELLIA            
+       case CIPHER_TYPE_CAMELLIA128 :
+               cipher = EVP_camellia_128_cbc();
+               break;
+       case CIPHER_TYPE_CAMELLIA192 :
+               cipher = EVP_camellia_192_cbc();
+               break;
+       case CIPHER_TYPE_CAMELLIA256 :
+               cipher = EVP_camellia_256_cbc();
+               break;
+#endif
+#endif
+       case CIPHER_TYPE_RC2_40 :
+       default :
+               cipher = EVP_rc2_40_cbc();
+               break;
+       }
+
+       return cipher;
+}
+
+static int get_x509_stack_of_recipient_certs(char *recipients, STACK_OF(X509) **output_recipient_certs, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("recipients : [%s], STACK_OF(X509) : [%p]", recipients, output_recipient_certs);
+
+       int err = EMAIL_ERROR_NONE;
+       int ret = false;        
+       int cert_size = 0;
+       char *temp_recipients = NULL;
+       char *token = NULL;
+       char *str = NULL;
+       char file_name[512] = {0, };
+       const unsigned char *in_cert = NULL;
+
+       X509 *x509_cert = NULL;
+       STACK_OF(X509) *temp_recipient_certs = NULL;
+
+       CERT_CONTEXT *context = NULL;
+       emstorage_certificate_tbl_t *cert = NULL;
+
+       if (!recipients || !output_recipient_certs) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* Initialize the variable */
+       context = cert_svc_cert_context_init();
+       temp_recipient_certs = sk_X509_new_null();
+
+       temp_recipients = EM_SAFE_STRDUP(recipients);
+       temp_recipients = em_replace_all_string(temp_recipients, ",", ";");     
+       token = strtok_r(temp_recipients, ";", &str);
+
+       do {
+               if (!emstorage_get_certificate_by_email_address(token, &cert, false, 0, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_certificate_by_email_address failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+               
+               SNPRINTF(file_name, sizeof(file_name), "%s", cert->filepath);
+               EM_DEBUG_LOG("file_name : [%s]", file_name);
+               err = cert_svc_load_file_to_context(context, file_name);
+               if (err != CERT_SVC_ERR_NO_ERROR) {
+                       EM_DEBUG_EXCEPTION("cert_svc_load_file_to_context failed : [%d]", err);
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               in_cert = context->certBuf->data;
+               cert_size = context->certBuf->size;
+
+               if (d2i_X509(&x509_cert, &in_cert, cert_size) == NULL) {
+                       EM_DEBUG_EXCEPTION("d2i_X509 failed");
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if (!sk_X509_push(temp_recipient_certs, x509_cert)) {
+                       EM_DEBUG_EXCEPTION("sk_X509_push failed");
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               x509_cert = NULL;
+               context = NULL;
+               emstorage_free_certificate(&cert, 1, NULL);
+               cert = NULL;
+       } while ((token = strtok_r(NULL, ";", &str)));
+
+       *output_recipient_certs = temp_recipient_certs;
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (!ret) {
+               if (x509_cert)
+                       X509_free(x509_cert);
+
+               if (temp_recipient_certs)
+                       sk_X509_pop_free(temp_recipient_certs, X509_free);
+       }
+
+       if (cert)
+               emstorage_free_certificate(&cert, 1, NULL);
+
+       cert_svc_cert_context_final(context);
+
+       EM_SAFE_FREE(temp_recipients);
+
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+/* Opaque signed and encrypted method */
+/*
+static PKCS7 *opaque_signed_and_encrypt(STACK_OF(X509) *recipients_cert, X509 *signer, EVP_PKEY *private_key, BIO *mime_entity, const EVP_CIPHER *cipher, const EVP_MD *md, int flags)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int i = 0;
+       PKCS7 *pkcs7 = NULL;
+       BIO *p7bio = NULL;
+       X509 *x509;
+
+       if (!(pkcs7 = PKCS7_new())) {
+               EM_DEBUG_EXCEPTION("PKCS7 malloc failed");
+               return NULL;
+       }
+       
+       if (!PKCS7_set_type(pkcs7, NID_pkcs7_signedAndEnveloped)) {
+               EM_DEBUG_EXCEPTION("Set type failed");
+               goto FINISH_OFF;
+       }
+
+       if (!PKCS7_add_signature(pkcs7, signer, private_key, md)) {
+               EM_DEBUG_EXCEPTION("PKCS7_add_signature failed");
+               goto FINISH_OFF;
+       }
+
+       if (!PKCS7_add_certificate(pkcs7, signer)) {
+               EM_DEBUG_EXCEPTION("PKCS7_add_certificate failed");
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < sk_X509_num(recipients_cert); i++) {
+               x509 = sk_X509_value(recipients_cert, i);
+               if (!PKCS7_add_recipient(pkcs7, x509)) {
+                       EM_DEBUG_EXCEPTION("PKCS7_add_recipient failed");
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (!PKCS7_set_cipher(pkcs7, cipher)) {
+               EM_DEBUG_EXCEPTION("Cipher failed");
+               goto FINISH_OFF;
+       }
+
+       if (flags & PKCS7_STREAM)
+               return pkcs7;
+
+       if (PKCS7_final(pkcs7, mime_entity, flags))
+               return pkcs7;
+       
+FINISH_OFF:
+       BIO_free_all(p7bio);
+       PKCS7_free(pkcs7);
+       return NULL;
+}
+*/
+
+INTERNAL_FUNC int emcore_smime_set_signed_message(char *certificate, char *mime_entity, email_digest_type digest_type, char **file_path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate path : [%s], mime_entity : [%s]", certificate, mime_entity);
+       int err, ret = false;
+       char temp_smime_filepath[512];
+       X509 *cert = NULL;
+       STACK_OF(X509) *other_certs = NULL;
+       EVP_PKEY *private_key = NULL;
+       const EVP_MD *digest = NULL;
+       BIO *bio_mime_entity = NULL, *bio_cert = NULL, *bio_prikey = NULL;
+       BIO *smime_attachment = NULL;
+       PKCS7 *signed_message = NULL;
+       int flags = PKCS7_DETACHED | PKCS7_PARTIAL;
+
+       OpenSSL_add_all_algorithms();
+       ERR_load_crypto_strings();
+
+       SNPRINTF(temp_smime_filepath, sizeof(temp_smime_filepath), "%s%s%s", MAILTEMP, DIR_SEPERATOR, SMIME_SIGNED_FILE);
+       EM_DEBUG_LOG("attachment file path of smime : [%s]", temp_smime_filepath);
+
+       smime_attachment = BIO_new_file(temp_smime_filepath, OUTMODE);
+       if (!smime_attachment) {
+               EM_DEBUG_EXCEPTION("Cannot open output file %s", temp_smime_filepath);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Load certificate for getting the certificate and private key */
+       if (!emcore_load_PFX_file(certificate, &private_key, &cert, &other_certs, &err)) {
+               EM_DEBUG_EXCEPTION("Load the private certificate failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       bio_mime_entity = BIO_new_file(mime_entity, READMODE);
+       if (!bio_mime_entity) {
+               EM_DEBUG_EXCEPTION("Cannot open file[%s]", mime_entity);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       signed_message = PKCS7_sign(NULL, NULL, other_certs, bio_mime_entity, flags);
+       if (!signed_message) {
+               EM_DEBUG_EXCEPTION("Error creating PKCS#7 structure");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       
+       /* Get the digest algorithm */
+       digest = emcore_get_digest_algorithm(digest_type);
+
+       if (!PKCS7_sign_add_signer(signed_message, cert, private_key, digest, flags)) {
+               EM_DEBUG_EXCEPTION("PKCS7_sign_add_signer failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!PKCS7_final(signed_message, bio_mime_entity, flags)) {
+               EM_DEBUG_EXCEPTION("PKCS7_final failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!i2d_PKCS7_bio_stream(smime_attachment, signed_message, bio_mime_entity, flags)) {
+               EM_DEBUG_EXCEPTION("i2d_PKCS7_bio_stream failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       BIO_flush(smime_attachment);
+       ret = true;
+
+FINISH_OFF:
+       if (file_path && ret)
+               *file_path = EM_SAFE_STRDUP(temp_smime_filepath);
+
+       X509_free(cert);
+       sk_X509_pop_free(other_certs, X509_free);
+       EVP_PKEY_free(private_key);
+       PKCS7_free(signed_message);
+
+       BIO_free(bio_mime_entity);
+       BIO_free(bio_cert);
+       BIO_free(bio_prikey);
+       BIO_free_all(smime_attachment);
+
+       EVP_cleanup();
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_smime_set_encrypt_message(char *recipient_list, char *mime_entity, email_cipher_type cipher_type, char **file_path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate path : [%p], mime_entity : [%p]", recipient_list, mime_entity);
+       char temp_smime_filepath[512];
+       int err = EMAIL_ERROR_NONE, ret = false;
+//     int flags = PKCS7_DETACHED | PKCS7_STREAM;
+       int flags = 0;
+
+       CERT_CONTEXT *loaded_cert = NULL;
+       STACK_OF(X509) *recipient_certs = NULL;
+       X509 *cert = NULL;
+       BIO *bio_mime_entity = NULL, *bio_cert = NULL;
+       BIO *smime_attachment = NULL;
+       PKCS7 *encrypt_message = NULL;
+       const EVP_CIPHER *cipher = NULL;
+
+       OpenSSL_add_all_algorithms();
+       ERR_load_crypto_strings();
+
+       loaded_cert = cert_svc_cert_context_init();
+
+       SNPRINTF(temp_smime_filepath, sizeof(temp_smime_filepath), "%s%s%s", MAILTEMP, DIR_SEPERATOR, SMIME_ENCRYPT_FILE);
+       EM_DEBUG_LOG("attachment file path of smime : [%s]", temp_smime_filepath);
+
+       smime_attachment = BIO_new_file(temp_smime_filepath, OUTMODE);
+       if (!smime_attachment) {
+               EM_DEBUG_EXCEPTION("Cannot open output file %s", temp_smime_filepath);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!get_x509_stack_of_recipient_certs(recipient_list, &recipient_certs, &err)) {
+               EM_DEBUG_EXCEPTION("get_x509_stack_of_recipient_certs failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       bio_mime_entity = BIO_new_file(mime_entity, READMODE);
+       if (!bio_mime_entity) {
+               EM_DEBUG_EXCEPTION("Cannot open file[%s]", mime_entity);
+               goto FINISH_OFF;
+       }
+       
+       /* Get cipher algorithm */
+       cipher = emcore_get_cipher_algorithm(cipher_type);
+       
+       encrypt_message = PKCS7_encrypt(recipient_certs, bio_mime_entity, cipher, flags);
+       if (encrypt_message == NULL) {
+               EM_DEBUG_EXCEPTION("PKCS7_encrypt failed [%ld]", ERR_get_error());
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!i2d_PKCS7_bio_stream(smime_attachment, encrypt_message, bio_mime_entity, flags)) {
+               EM_DEBUG_EXCEPTION("i2d_PKCS7_bio_stream failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       BIO_flush(smime_attachment);
+
+       ret = true;
+
+FINISH_OFF:
+       if (file_path && ret)
+               *file_path = EM_SAFE_STRDUP(temp_smime_filepath);
+
+       PKCS7_free(encrypt_message);
+
+       X509_free(cert);
+       sk_X509_pop_free(recipient_certs, X509_free);
+
+       BIO_free(bio_cert);
+       BIO_free(bio_mime_entity);
+       BIO_free_all(smime_attachment);
+
+       cert_svc_cert_context_final(loaded_cert);
+       EVP_cleanup();
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_smime_set_signed_and_encrypt_message(char *recipient_list, char *certificate, char *mime_entity, email_cipher_type cipher_type, email_digest_type digest_type, char **file_path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate path : [%s], mime_entity : [%s]", recipient_list, mime_entity);
+       char temp_smime_filepath[512];
+       int err = EMAIL_ERROR_NONE, ret = false;
+       int flags = PKCS7_DETACHED | PKCS7_PARTIAL | PKCS7_STREAM;
+
+       STACK_OF(X509) *recipient_certs = NULL;
+       STACK_OF(X509) *other_certs = NULL;
+       BIO *bio_mime_entity = NULL, *bio_cert = NULL;
+       BIO *bio_signed_message = BIO_new(BIO_s_mem());
+       BIO *smime_attachment = NULL;
+       PKCS7 *signed_message = NULL;
+       PKCS7 *encrypt_message = NULL;
+       const EVP_CIPHER *cipher = NULL;
+       const EVP_MD *digest = NULL;
+
+       /* Variable for private certificate */
+       EVP_PKEY *private_key = NULL;
+       X509 *cert = NULL;
+
+       OpenSSL_add_all_algorithms();
+       ERR_load_crypto_strings();
+
+       SNPRINTF(temp_smime_filepath, sizeof(temp_smime_filepath), "%s%s%s", MAILTEMP, DIR_SEPERATOR, SMIME_ENCRYPT_FILE);
+       EM_DEBUG_LOG("attachment file path of smime : [%s]", temp_smime_filepath);
+
+       smime_attachment = BIO_new_file(temp_smime_filepath, OUTMODE);
+       if (!smime_attachment) {
+               EM_DEBUG_EXCEPTION("Cannot open output file %s", temp_smime_filepath);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Signing the mail */
+       /* 1. Load the private certificate */
+       if (!emcore_load_PFX_file(certificate, &private_key, &cert, &other_certs, &err)) {
+               EM_DEBUG_EXCEPTION("Load the private certificate failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* 2. Read mime entity */
+       bio_mime_entity = BIO_new_file(mime_entity, READMODE);
+       if (!bio_mime_entity) {
+               EM_DEBUG_EXCEPTION("Cannot open file[%s]", mime_entity);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* 3. signing */
+       signed_message = PKCS7_sign(NULL, NULL, other_certs, bio_mime_entity, flags);
+       if (!signed_message) {
+               EM_DEBUG_EXCEPTION("Error creating PKCS#7 structure");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       
+       /* 4. Get the digest algorithm */
+       digest = emcore_get_digest_algorithm(digest_type);
+
+       /* 5. Apply a digest algorithm */
+       if (!PKCS7_sign_add_signer(signed_message, cert, private_key, digest, flags)) {
+               EM_DEBUG_EXCEPTION("PKCS7_sign_add_signer failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* 6. Create signing message */
+       if (!SMIME_write_PKCS7(bio_signed_message, signed_message, bio_mime_entity, flags | SMIME_OLDMIME | SMIME_CRLFEOL)) {
+               EM_DEBUG_EXCEPTION("SMIME_write_PKCS7 error");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Encrypting the mail */
+       /* 1. Get the recipient certs */
+       if (!get_x509_stack_of_recipient_certs(recipient_list, &recipient_certs, &err)) {
+               EM_DEBUG_EXCEPTION("get_x509_stack_of_recipient_certs failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* 2. Get cipher algorithm */
+       cipher = emcore_get_cipher_algorithm(cipher_type);
+       
+       flags = 0;
+
+       /* 3. Encrypt the signing message */    
+       encrypt_message = PKCS7_encrypt(recipient_certs, bio_signed_message, cipher, flags);
+       if (encrypt_message == NULL) {
+               EM_DEBUG_EXCEPTION("PKCS7_encrypt failed [%ld]", ERR_get_error());
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       
+       /* 4. Write the encrypt message in file */
+       if (!i2d_PKCS7_bio_stream(smime_attachment, encrypt_message, bio_mime_entity, flags)) {
+               EM_DEBUG_EXCEPTION("i2d_PKCS7_bio_stream failed");
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       BIO_flush(smime_attachment);
+
+       ret = true;
+
+FINISH_OFF:
+       if (file_path && ret)
+               *file_path = EM_SAFE_STRDUP(temp_smime_filepath);
+
+       PKCS7_free(signed_message);
+       PKCS7_free(encrypt_message);
+       EVP_PKEY_free(private_key);
+
+       X509_free(cert);
+       sk_X509_pop_free(other_certs, X509_free);
+       sk_X509_pop_free(recipient_certs, X509_free);
+
+       BIO_free(bio_cert);
+       BIO_free(bio_mime_entity);
+       BIO_free(bio_signed_message);
+       BIO_free_all(smime_attachment);
+
+       EVP_cleanup();
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+
+
+
+INTERNAL_FUNC int emcore_smime_set_decrypt_message(char *encrypt_message, char *certificate, char **decrypt_message, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("encrypt_file : [%s], certificate : [%s]", encrypt_message, certificate);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       char temp_decrypt_filepath[512] = {0, };
+
+       X509 *cert = NULL;
+       EVP_PKEY *private_key = NULL;
+       BIO *infile = NULL, *out_buf = NULL;
+       PKCS7 *p7_encrypt_message = NULL;
+       STACK_OF(X509) *recipient_certs = NULL;
+
+       OpenSSL_add_all_algorithms();
+
+       /* Load the encrypted message */
+       infile = BIO_new_file(encrypt_message, INMODE);
+       if (infile == NULL) {
+               EM_DEBUG_EXCEPTION("Cannot open output file %s", encrypt_message);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       p7_encrypt_message = d2i_PKCS7_bio(infile, NULL);
+       if (!p7_encrypt_message) {
+               EM_DEBUG_EXCEPTION("Error reading S/MIME message");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* Initialize the output file for decrypted message */
+       SNPRINTF(temp_decrypt_filepath, sizeof(temp_decrypt_filepath), "%s%s%s", MAILTEMP, DIR_SEPERATOR, DECRYPT_TEMP_FILE);
+       EM_DEBUG_LOG("attachment file path of smime : [%s]", temp_decrypt_filepath);
+
+       out_buf = BIO_new_file(temp_decrypt_filepath, OUTMODE);
+       if (!out_buf) {
+               EM_DEBUG_EXCEPTION("Cannot open output file %s", temp_decrypt_filepath);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Search private cert */
+       if (!emcore_load_PFX_file(certificate, &private_key, &cert, NULL, &err)) {
+               EM_DEBUG_EXCEPTION("Load the private certificate failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!PKCS7_decrypt(p7_encrypt_message, private_key, cert, out_buf, 0)) {
+               EM_DEBUG_EXCEPTION("Decrpyt failed");
+               err = EMAIL_ERROR_DECRYPT_FAILED;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (decrypt_message && ret)
+               *decrypt_message = EM_SAFE_STRDUP(temp_decrypt_filepath);
+
+       EVP_cleanup();
+       X509_free(cert);
+       EVP_PKEY_free(private_key);
+       BIO_free(out_buf);
+       BIO_free_all(infile);
+       sk_X509_pop_free(recipient_certs, X509_free);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+
+/*
+INTERNAL_FUNC int emcore_smime_verify_signed_message(char *signed_message, char *ca_file, char *ca_path, int *verify)
+{
+       int ret = false;
+       int temp_verify = 0;
+       BIO *indata = NULL;
+       BIO *content = NULL;
+       X509_STORE *store = NULL;
+       X509_LOOKUP *lookup = NULL;
+       PKCS7 *p7 = NULL;
+
+       OpenSSL_add_all_algorithms();
+       ERR_load_crypto_strings();
+
+       if (BIO_write(indata, signed_message, sizeof(signed_message)) <= 0) {
+               EM_DEBUG_EXCEPTION("Char to Bio failed");
+               goto FINISH_OFF;
+       }
+
+       p7 = SMIME_read_PKCS7(indata, &content);
+       if (!p7) {
+               EM_DEBUG_EXCEPTION("SMIME_read_PKCS7 failed");
+               goto FINISH_OFF;
+       }
+
+       if (!(store = X509_STORE_new())) {
+               EM_DEBUG_EXCEPTION("Initialize x509_store failed");
+               goto FINISH_OFF;
+       }
+       
+       lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
+       if (lookup == NULL) {
+               EM_DEBUG_EXCEPTION("Initialize lookup store failed");
+               goto FINISH_OFF;
+       }
+
+       if (ca_file) {
+               if (!X509_LOOKUP_load_file(lookup, ca_file, X509_FILETYPE_PEM)) {
+                       EM_DEBUG_EXCEPTION("X509_LOOKUP_load_file failed");
+                       goto FINISH_OFF;
+               }
+       } else {
+               X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
+       }
+
+       lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
+       if (lookup == NULL) {
+               EM_DEBUG_EXCEPTION("X509_STORE_add_lookup failed");
+               goto FINISH_OFF;
+       }
+       
+       if (ca_path) {
+               if (!X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM)) {
+                       EM_DEBUG_EXCEPTION("CA path load failed");
+                       goto FINISH_OFF;
+               }
+       } else {
+               X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
+       }
+       
+       temp_verify = PKCS7_verify(p7, NULL, store, content, NULL, 0);
+       if (temp_verify) 
+               EM_DEBUG_LOG("Verification Successful\n");
+
+       ret = true;
+
+FINISH_OFF:
+       if (store)
+               X509_STORE_free(store);
+       if (p7)
+               PKCS7_free(p7);
+       
+       if (indata)
+               BIO_free(indata);
+
+       if (verify != NULL)
+               *verify = temp_verify;
+
+       ERR_clear_error();
+       EVP_cleanup();
+       return ret;
+}
+*/
+
+static char *emcore_set_mime_entity(char *mime_path)
+{
+       EM_DEBUG_FUNC_BEGIN("mime_path : [%s]", mime_path);
+       FILE *fp_read = NULL;
+       FILE *fp_write = NULL;
+       char *mime_entity = NULL;
+       char *mime_entity_path = NULL;
+       char temp_buffer[255] = {0,};
+       int err;
+       int searched = 0;
+
+       if (!emcore_get_temp_file_name(&mime_entity_path, &err))  {
+               EM_DEBUG_EXCEPTION(" em_core_get_temp_file_name failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* get mime entity */
+       if (mime_path != NULL) {
+               fp_read = fopen(mime_path, "r");
+               if (fp_read == NULL) {
+                       EM_DEBUG_EXCEPTION("File open(read) is failed : filename [%s]", mime_path);
+                       goto FINISH_OFF;
+               }
+
+               fp_write = fopen(mime_entity_path, "w");
+               if (fp_write == NULL) {
+                       EM_DEBUG_EXCEPTION("File open(write) is failed : filename [%s]", mime_entity_path);
+                       goto FINISH_OFF;
+               }
+
+               fseek(fp_read, 0, SEEK_SET);
+               fseek(fp_write, 0, SEEK_SET);           
+
+               while (fgets(temp_buffer, 255, fp_read) != NULL) {
+                       mime_entity = strcasestr(temp_buffer, "content-type");
+                       if (mime_entity != NULL && !searched)
+                               searched = 1;
+
+                       if (searched) {
+                               EM_DEBUG_LOG("temp_buffer : %s", temp_buffer);
+                               fprintf(fp_write, "%s", temp_buffer);
+                       }
+               }
+       }       
+
+FINISH_OFF:
+       if (fp_read)
+               fclose(fp_read);
+
+       if (fp_write)
+               fclose(fp_write);
+
+       EM_SAFE_FREE(mime_entity);
+       EM_SAFE_FREE(mime_path);
+
+       EM_DEBUG_FUNC_END();
+       return mime_entity_path;
+}
+
+INTERNAL_FUNC int emcore_convert_mail_data_to_smime_data(emstorage_account_tbl_t *account_tbl_item, email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data_list, int *output_attachment_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list [%p], input_attachment_count [%d], output_mail_data [%p], output_attachment_data_list [%p]", input_mail_data, input_attachment_data_list, input_attachment_count, output_mail_data, output_attachment_data_list);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int smime_type = EMAIL_SMIME_NONE;
+       int address_length = 0;
+       int attachment_count = input_attachment_count;
+       int file_size = 0;
+       char *name = NULL;
+       char *rfc822_file = NULL;
+       char *mime_entity = NULL;
+       char *smime_file_path = NULL;
+       char *other_certificate_list = NULL;
+       email_attachment_data_t new_attachment_data = {0};
+       email_attachment_data_t *new_attachment_list = NULL;
+
+       /* Validating parameters */
+       
+       if (!input_mail_data || !(input_mail_data->account_id) || !(input_mail_data->mailbox_id)) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_make_rfc822_file(input_mail_data, input_attachment_data_list, attachment_count, &rfc822_file, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_make_rfc822_file failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       mime_entity = emcore_set_mime_entity(rfc822_file);
+
+       smime_type = input_mail_data->smime_type;
+       if (!smime_type) 
+               smime_type = account_tbl_item->smime_type;
+
+       /* Signed and Encrypt the message */
+       switch (smime_type) {
+       case EMAIL_SMIME_SIGNED:                        /* Clear signed message */
+               if (!emcore_smime_set_signed_message(account_tbl_item->certificate_path, mime_entity, account_tbl_item->digest_type, &smime_file_path, &err)) {
+                       EM_DEBUG_EXCEPTION("em_core_smime_set_clear_signed_message is failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+       
+               EM_DEBUG_LOG("smime_file_path : %s", smime_file_path);  
+               name = strrchr(smime_file_path, '/');
+
+               new_attachment_data.attachment_name = EM_SAFE_STRDUP(name + 1);
+               new_attachment_data.attachment_path = EM_SAFE_STRDUP(smime_file_path);
+
+               attachment_count += 1;
+
+               break;
+       case EMAIL_SMIME_ENCRYPTED:                     /* Encryption message */
+               address_length = EM_SAFE_STRLEN(input_mail_data->full_address_to) + EM_SAFE_STRLEN(input_mail_data->full_address_cc) + EM_SAFE_STRLEN(input_mail_data->full_address_bcc);
+
+               other_certificate_list = em_malloc(address_length + 3);
+               
+               SNPRINTF(other_certificate_list, address_length + 2, "%s;%s;%s", input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
+
+               EM_DEBUG_LOG("to:[%s], cc:[%s], bcc:[%s]", input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
+               EM_DEBUG_LOG("length : [%d], email_address : [%s]", address_length, other_certificate_list);
+
+               if (!emcore_smime_set_encrypt_message(other_certificate_list, mime_entity, account_tbl_item->cipher_type, &smime_file_path, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_smime_set_encrypt_message is failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("smime_file_path : %s", smime_file_path);  
+               name = strrchr(smime_file_path, '/');
+
+               new_attachment_data.attachment_name = EM_SAFE_STRDUP(name + 1);
+               new_attachment_data.attachment_path = EM_SAFE_STRDUP(smime_file_path);
+
+               attachment_count = 1;
+
+               break;
+       default:                        /* Signed and Encryption message */
+               address_length = EM_SAFE_STRLEN(input_mail_data->full_address_to) + EM_SAFE_STRLEN(input_mail_data->full_address_cc) + EM_SAFE_STRLEN(input_mail_data->full_address_bcc);
+
+               other_certificate_list = em_malloc(address_length + 3);
+
+               SNPRINTF(other_certificate_list, address_length + 2, "%s;%s;%s", input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
+
+               EM_DEBUG_LOG("to:[%s], cc:[%s], bcc:[%s]", input_mail_data->full_address_to, input_mail_data->full_address_cc, input_mail_data->full_address_bcc);
+               EM_DEBUG_LOG("length : [%d], email_address : [%s]", address_length, other_certificate_list);
+
+               if (!emcore_smime_set_signed_and_encrypt_message(other_certificate_list, account_tbl_item->certificate_path, mime_entity, account_tbl_item->cipher_type, account_tbl_item->digest_type, &smime_file_path, &err)) {
+                       EM_DEBUG_EXCEPTION("em_core_smime_set_signed_and_encrypt_message is failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("smime_file_path : %s", smime_file_path);  
+               name = strrchr(smime_file_path, '/');
+
+               new_attachment_data.attachment_name = EM_SAFE_STRDUP(name + 1);
+               new_attachment_data.attachment_path = EM_SAFE_STRDUP(smime_file_path);
+
+               attachment_count = 1;
+
+               break;
+       }
+
+       if (!emcore_get_file_size(smime_file_path, &file_size, NULL)) {
+               EM_DEBUG_EXCEPTION("emcore_get_file_size failed");
+               goto FINISH_OFF;
+       }
+
+       new_attachment_data.attachment_size = file_size;
+       new_attachment_data.save_status = 1;
+
+       new_attachment_list = (email_attachment_data_t *)em_malloc(sizeof(email_attachment_data_t) * attachment_count);
+       if (new_attachment_list == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               goto FINISH_OFF;
+       }
+
+       if (input_attachment_data_list != NULL)
+               new_attachment_list = input_attachment_data_list;
+
+       new_attachment_list[attachment_count-1] = new_attachment_data;
+
+       input_mail_data->smime_type = smime_type;
+       input_mail_data->file_path_mime_entity = EM_SAFE_STRDUP(mime_entity);
+       input_mail_data->digest_type = account_tbl_item->digest_type;
+
+       ret = true;
+
+FINISH_OFF:    
+       if (output_attachment_count)
+               *output_attachment_count = attachment_count;
+       
+       if (output_attachment_data_list) 
+               *output_attachment_data_list = new_attachment_list;
+
+       *output_mail_data = input_mail_data;
+
+       return ret;                             
+}
+
+
diff --git a/email-core/email-core-smtp.c b/email-core/email-core-smtp.c
new file mode 100755 (executable)
index 0000000..96467e8
--- /dev/null
@@ -0,0 +1,3813 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <time.h>
+#include "email-internal-types.h"
+#include "c-client.h"
+#include "email-core-global.h"
+#include "email-core-utils.h"
+#include "email-storage.h"
+#include "email-core-api.h"
+#include "email-core-smtp.h"
+#include "email-core-event.h"
+#include "email-core-mailbox.h"
+#include "email-core-mail.h"
+#include "email-core-mime.h"
+#include "email-core-smime.h"
+#include "email-core-account.h"
+#include "email-core-imap-mailbox.h"
+#include "email-core-mailbox-sync.h"
+#include "email-core-signal.h"
+#include "email-utilities.h"
+#include "email-convert.h"
+
+
+#include <unistd.h>
+#include "email-debug-log.h"
+
+#ifdef __FEATURE_SUPPORT_REPORT_MAIL__
+static int emcore_get_report_mail_body(ENVELOPE *envelope, BODY **multipart_body, int *err_code);
+#endif
+static int emcore_make_envelope_from_mail(emstorage_mail_tbl_t *input_mail_tbl_data, ENVELOPE **output_envelope);
+static int emcore_send_mail_smtp(SENDSTREAM *stream, ENVELOPE *env, char *data_file, int account_id, int mail_id,  int *err_code);
+
+/* Functions from uw-imap-toolkit */
+/* extern void *fs_get(size_t size); */
+extern void rfc822_date(char *date);
+extern long smtp_send(SENDSTREAM *stream, char *command, char *args);
+extern long smtp_rcpt(SENDSTREAM *stream, ADDRESS *adr, long* error);
+
+#ifndef __FEATURE_SEND_OPTMIZATION__
+extern long smtp_soutr(void *stream, char *s);
+#endif
+
+#ifdef __FEATURE_SEND_OPTMIZATION__
+extern long smtp_soutr_test(void *stream, char *s);
+#endif
+
+
+
+
+void mail_send_notify(email_send_status_t status, int total, int sent, int account_id, int mail_id,  int err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("status[%d], total[%d], sent[%d], account_id[%d], mail_id[%d], err_code[%d]", status, total, sent, account_id, mail_id, err_code);
+
+       switch (status) {
+               case EMAIL_SEND_CONNECTION_FAIL:
+               case EMAIL_SEND_FINISH:
+               case EMAIL_SEND_FAIL:
+                       break;
+
+               case EMAIL_SEND_PROGRESS:
+               default:
+                       break;
+       }
+       emcore_execute_event_callback(EMAIL_ACTION_SEND_MAIL, total, sent, status, account_id, mail_id, -1, err_code);
+       EM_DEBUG_FUNC_END();
+}
+
+/* ------ rfc822 handle ---------------------------------------------------*/
+long buf_flush(void *stream, char *string)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], string[%s]", stream, string);
+       EM_DEBUG_FUNC_END();
+       return 1;
+}
+
+
+#define RFC822_READ_BLOCK_SIZE   1024
+#define RFC822_STRING_BUFFER_SIZE 1536
+
+static char *emcore_find_img_tag(char *source_string)
+{
+       EM_DEBUG_FUNC_BEGIN("source_string[%p]", source_string);
+
+       int cur = 0, string_length;
+       if (!source_string)
+               return false;
+
+       string_length = EM_SAFE_STRLEN(source_string);
+
+       for (cur = 0; cur < string_length; cur++) {
+               if (source_string[cur] == 'I' || source_string[cur] == 'i') {
+                       cur++;
+                       if (source_string[cur] == 'M' || source_string[cur] == 'm') {
+                               cur++;
+                               if (source_string[cur] == 'G' || source_string[cur] == 'g') {
+                                       EM_DEBUG_FUNC_END("%s", source_string + cur - 2);
+                                       return source_string + cur - 2;
+                               }
+                       }
+               }
+       }
+       EM_DEBUG_FUNC_END("Can't find");
+       return NULL;
+}
+
+#define CONTENT_ID_BUFFER_SIZE 512
+static char *emcore_replace_inline_image_path_with_content_id(char *source_string, BODY *html_body, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("source_string[%p], html_body[%p], err_code[%p]", source_string, html_body, err_code);
+
+       int  err = EMAIL_ERROR_NONE;
+       char content_id_buffer[CONTENT_ID_BUFFER_SIZE], file_name_buffer[512], new_string[512], *result_string = NULL, *input_string = NULL;
+       BODY *cur_body = NULL;
+       PART *cur_part = NULL;
+
+       if (!source_string || !html_body) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       input_string = EM_SAFE_STRDUP(source_string);
+
+       cur_part = html_body->nested.part;
+
+       while (cur_part) {
+               cur_body = &(cur_part->body);
+               result_string = NULL; /*prevent 37865*/
+               if (cur_body) {
+                       EM_DEBUG_LOG("Has body. id[%s]", cur_body->disposition.type);
+                       if (cur_body->disposition.type && cur_body->disposition.type[0] == 'i') {   /*  Is inline content? */
+                               EM_DEBUG_LOG("Has inline content");
+                               memset(content_id_buffer, 0, CONTENT_ID_BUFFER_SIZE);
+                               if (cur_body->id) {
+                                       EM_SAFE_STRNCPY(content_id_buffer, cur_body->id + 1, CONTENT_ID_BUFFER_SIZE - 1); /*  Removing <, > */
+                                       /* prevent 34413 */
+                                       char *last_bracket = rindex(content_id_buffer, '>');
+                                       *last_bracket = NULL_CHAR;
+
+                                       /* if (emcore_get_attribute_value_of_body_part(cur_body->parameter, "name", file_name_buffer, CONTENT_ID_BUFFER_SIZE, false, &err)) { */
+                                       if (emcore_get_attribute_value_of_body_part(cur_body->parameter, "name", file_name_buffer, CONTENT_ID_BUFFER_SIZE, true, &err)) {
+                                               EM_DEBUG_LOG("Content-ID[%s], filename[%s]", content_id_buffer, file_name_buffer);
+                                               SNPRINTF(new_string, CONTENT_ID_BUFFER_SIZE, "cid:%s", content_id_buffer);
+                                               result_string = em_replace_string(input_string, file_name_buffer, new_string);
+                                       }
+                               }
+                       }
+               }
+               if (result_string) {
+                       EM_SAFE_FREE(input_string);
+                       input_string = result_string;
+               }
+               cur_part = cur_part->next;
+       }
+
+       if (input_string)
+               result_string = EM_SAFE_STRDUP(input_string);
+FINISH_OFF:
+
+       EM_SAFE_FREE(input_string);
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret[%s]", result_string);
+       return result_string;
+}
+
+static int emcore_write_body(BODY *body, BODY *html_body, FILE *fp, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("fp[%d]", fp);
+       char *file_path = NULL;
+       char buf[RFC822_STRING_BUFFER_SIZE + 1];
+       char *img_tag_pos = NULL;
+       char *p = NULL;
+       char *replaced_string = NULL;
+       int fd, nread, nwrite, error = EMAIL_ERROR_NONE;
+       unsigned long len;
+
+       file_path = body->sparep;
+
+       if (!file_path || EM_SAFE_STRLEN(file_path) == 0)  {
+               EM_DEBUG_LOG("There is no file path");
+               switch (body->encoding)  {
+                       case 0:
+                               break;
+                       default:
+                               p = cpystr((const char *)body->contents.text.data);
+                               len = body->contents.text.size;
+                               break;
+               }
+
+               if (p)  {
+                       EM_DEBUG_LOG("p[%s]", p);
+                       fprintf(fp, "%s"CRLF_STRING CRLF_STRING, p);
+                       EM_SAFE_FREE(p);
+               }
+
+               EM_SAFE_FREE(body->sparep);
+               EM_DEBUG_FUNC_END();
+               return true;
+       }
+
+       EM_DEBUG_LOG("Opening a file[%s]", file_path);
+       fd = open(file_path, O_RDONLY);
+
+       if (fd < 0) {
+               EM_DEBUG_EXCEPTION("open(\"%s\") failed...", file_path);
+               return false;
+       }
+
+       while (1) {
+               memset(&buf, 0x00, RFC822_STRING_BUFFER_SIZE + 1);
+               nread = read(fd, buf, (body->encoding == ENCBASE64 ? 57 : RFC822_READ_BLOCK_SIZE - 2));
+
+               if (nread <= 0)  {
+                       EM_DEBUG_LOG("Can't read anymore : nread[%d]", nread);
+                       break;
+               }
+
+               p = NULL;
+               len = nread;
+
+               /* EM_DEBUG_LOG("body->type[%d], body->subtype[%c]", body->type, body->subtype[0]); */
+
+               if (body->type == TYPETEXT && (body->subtype && (body->subtype[0] == 'H' || body->subtype[0] == 'h'))) {
+                       EM_DEBUG_LOG("HTML Part");
+                       img_tag_pos = emcore_find_img_tag(buf);
+
+                       if (img_tag_pos) {
+                               replaced_string = emcore_replace_inline_image_path_with_content_id(buf, html_body, &error);
+                               if (replaced_string) {
+                                       EM_DEBUG_LOG("emcore_replace_inline_image_path_with_content_id succeeded");
+                                       strcpy(buf, replaced_string);
+                                       nread = len = EM_SAFE_STRLEN(buf);
+                                       EM_DEBUG_LOG("buf[%s], nread[%d], len[%d]", buf, nread, len);
+                               }
+                               else
+                                       EM_DEBUG_LOG("emcore_replace_inline_image_path_with_content_id failed[%d]", error);
+                       }
+               }
+               /* EM_DEBUG_LOG("body->encoding[%d]", body->encoding); */
+//             if (body->subtype[0] != 'S' || body->subtype[0] != 's') {
+               switch (body->encoding)  {
+                       case ENCQUOTEDPRINTABLE:
+                               p = (char *)rfc822_8bit((unsigned char *)buf, (unsigned long)nread, (unsigned long *)&len);
+                               break;
+                       case ENCBASE64:
+                               p = (char *)rfc822_binary((void *)buf, (unsigned long)nread, (unsigned long *)&len);
+                               break;
+                       default:
+                               buf[len] = '\0';
+                               break;
+               }
+//             }
+
+               nwrite = fprintf(fp, "%s", (p ? p : buf));
+               if (nwrite != len)  {
+                       fclose(fp);
+                       close(fd);
+                       EM_SAFE_FREE(p);
+                       EM_DEBUG_EXCEPTION("fprintf failed nwrite[%d], len[%d]", nwrite, len);
+                       return false;
+               }
+               EM_SAFE_FREE(p);
+       }
+
+       if (body->encoding == ENCQUOTEDPRINTABLE || body->encoding == ENCBASE64)
+               fprintf(fp, CRLF_STRING);
+
+       fprintf(fp, CRLF_STRING);
+
+       if (body->sparep)  {
+               free(body->sparep);
+               body->sparep = NULL;
+       }
+
+       close(fd);
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+static int emcore_write_rfc822_body(BODY *body, BODY *html_body, FILE *fp, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("body[%p], html_body[%p], fp[%p], err_code[%p]", body, html_body, fp, err_code);
+
+       PARAMETER *param = NULL;
+       PART *part = NULL;
+       char *p = NULL, *bndry = NULL, buf[1025];
+       int error = EMAIL_ERROR_NONE;
+
+       switch (body->type)  {
+               case TYPEMULTIPART:
+                       EM_DEBUG_LOG("body->type = TYPEMULTIPART");
+                       part = body->nested.part;
+
+                       for (param = body->parameter; param; param = param->next)  {
+                               if (strcasecmp(param->attribute, "BOUNDARY") == 0) {
+                                       bndry = param->value;
+                                       break;
+                               }
+                       }
+
+                       do  {
+                               p = buf; p[0] = '\0';
+
+                               rfc822_write_body_header(&p, &part->body);
+
+                               fprintf(fp, "--%s"CRLF_STRING, bndry);
+                               if (body->subtype[0] == 'S' || body->subtype[0] == 's') {
+                                       if (!emcore_write_body(body, html_body, fp, &error)) {
+                                               EM_DEBUG_EXCEPTION("emcore_write_body failed : [%d]", error);
+                                               return false;
+                                       }
+                                       fprintf(fp, "--%s"CRLF_STRING, bndry);
+                               }
+
+                               fprintf(fp, "%s"CRLF_STRING, buf);
+
+                               emcore_write_rfc822_body(&part->body, html_body, fp, err_code);
+                       } while ((part = part->next));
+
+                       fprintf(fp, "--%s--"CRLF_STRING, bndry);
+                       break;
+
+               default:  {
+                       EM_DEBUG_LOG("body->type is not TYPEMULTIPART");
+
+                       if (!emcore_write_body(body, html_body, fp, &error)) {
+                               EM_DEBUG_EXCEPTION("emcore_write_body failed : [%d]", error);
+                               return false;
+                       }
+
+                       break;
+               }       /*  default: */
+       }
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+static int emcore_write_rfc822(ENVELOPE *env, BODY *body, BODY *html_body, email_mail_priority_t input_priority, email_mail_report_t input_report_flag, char **data, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("env[%p], body[%p], data[%p], err_code[%p]", env, body, data, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       FILE *fp = NULL;
+       char *fname = NULL;
+       char *p = NULL;
+       size_t p_len = 0;
+
+       if (!env || !data)  {
+               EM_DEBUG_EXCEPTION("Invalid Parameters");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       srand(time(NULL));
+
+       rfc822_encode_body_7bit(env, body); /*  if contents.text.data isn't NULL, the data will be encoded. */
+
+       /*  FIXME : create memory map for this file */
+       p_len = (env->subject ? EM_SAFE_STRLEN(env->subject) : 0) + 8192;
+
+       if (!(p = em_malloc(p_len)))  {         /* (env->subject ? EM_SAFE_STRLEN(env->subject) : 0) + 8192))) */
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+
+       RFC822BUFFER buf;
+
+       /* write at start of buffer */
+       buf.end = (buf.beg = buf.cur = p) + p_len - 1;
+       /* buf.f = NIL; */
+       buf.f = buf_flush;
+       buf.s = NIL;
+
+       /*  rfc822_output_header(&buf, env, body, NIL, T); */           /*  including BCC  */
+       rfc822_output_header(&buf, env, body, NIL, NIL);                /*  Excluding BCC */
+
+       *buf.cur = '\0';                /* tie off buffer */
+       {
+               gchar **tokens = g_strsplit(p, "CHARSET=X-UNKNOWN", 2);
+
+               if (g_strv_length(tokens) > 1)  {
+                       gchar *charset;
+
+                       if (body->sparep) {
+                               charset = g_path_get_basename(body->sparep);
+                               char *pHtml = NULL;
+                               if (charset != NULL) {
+                                       if ((pHtml = strstr(charset, ".htm")) != NULL)
+                                               charset[pHtml-charset] = '\0';
+                               }
+
+                               SNPRINTF(p, p_len, "%sCHARSET=%s%s", tokens[0], charset, tokens[1]);
+                               g_free(charset);
+                       }
+                       else
+                               EM_DEBUG_EXCEPTION("body->sparep is NULL");
+               }
+
+               g_strfreev(tokens);
+       } {
+               gchar **tokens = g_strsplit(p, "To: undisclosed recipients: ;\015\012", 2);
+               if (g_strv_length(tokens) > 1)
+                       SNPRINTF(p, p_len, "%s%s", tokens[0], tokens[1]);
+               g_strfreev(tokens);
+       }
+
+
+       EM_DEBUG_LOG(" =============================================================================== "
+               LF_STRING"%s"LF_STRING
+               " =============================================================================== ", p);
+
+       if (EM_SAFE_STRLEN(p) > 2)
+               *(p + EM_SAFE_STRLEN(p) - 2) = '\0';
+
+
+       if (input_report_flag)  {
+               char buf[512] = {0x00, };
+
+               if(input_report_flag & EMAIL_MAIL_REPORT_DSN) {
+                       /*  DSN (delivery status) */
+                       /*  change content-type */
+                       /*  Content-Type: multipart/report; */
+                       /*              report-type= delivery-status; */
+                       /*              boundary="----=_NextPart_000_004F_01C76EFF.54275C50" */
+               }
+
+               if(input_report_flag & EMAIL_MAIL_REPORT_MDN) {
+                       /*  MDN (read receipt) */
+                       /*  Content-Type: multipart/report; */
+                       /*              report-type= disposition-notification; */
+                       /*              boundary="----=_NextPart_000_004F_01C76EFF.54275C50" */
+               }
+
+               if(input_report_flag & EMAIL_MAIL_REQUEST_MDN) {
+                       /*  require read status */
+                       rfc822_address(buf, env->from);
+                       if (EM_SAFE_STRLEN(buf))
+                               SNPRINTF(p + EM_SAFE_STRLEN(p), p_len-(EM_SAFE_STRLEN(p)), "Disposition-Notification-To: %s"CRLF_STRING, buf);
+               }
+       }
+
+       if (input_priority)  {          /*  priority (1:high 3:normal 5:low) */
+               SNPRINTF(p + EM_SAFE_STRLEN(p), p_len-(EM_SAFE_STRLEN(p)), "X-Priority: %d"CRLF_STRING, input_priority);
+
+               switch (input_priority)  {
+                       case EMAIL_MAIL_PRIORITY_HIGH:
+                               SNPRINTF(p + EM_SAFE_STRLEN(p), p_len-(EM_SAFE_STRLEN(p)), "X-MSMail-Priority: HIgh"CRLF_STRING);
+                               break;
+                       case EMAIL_MAIL_PRIORITY_NORMAL:
+                               SNPRINTF(p + EM_SAFE_STRLEN(p), p_len-(EM_SAFE_STRLEN(p)), "X-MSMail-Priority: Normal"CRLF_STRING);
+                               break;
+                       case EMAIL_MAIL_PRIORITY_LOW:
+                               SNPRINTF(p + EM_SAFE_STRLEN(p), p_len-(EM_SAFE_STRLEN(p)), "X-MSMail-Priority: Low"CRLF_STRING);
+                               break;
+               }
+       }
+
+       SNPRINTF(p + EM_SAFE_STRLEN(p), p_len-(EM_SAFE_STRLEN(p)), CRLF_STRING);
+
+       if (!emcore_get_temp_file_name(&fname, &error))  {
+               EM_DEBUG_EXCEPTION(" emcore_get_temp_file_name failed[%d]", error);
+               goto FINISH_OFF;
+       }
+
+       if (!(fp = fopen(fname, "w+")))  {
+               EM_DEBUG_EXCEPTION("fopen failed[%s]", fname);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       fprintf(fp, "%s", p);
+
+       if (body)  {
+               if (!emcore_write_rfc822_body(body, html_body, fp, &error))  {
+                       EM_DEBUG_EXCEPTION("emcore_write_rfc822_body failed[%d]", error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+
+FINISH_OFF:
+       if (fp != NULL)
+               fclose(fp);
+
+#ifdef USE_SYNC_LOG_FILE
+       emstorage_copy_file(fname, "/tmp/phone2pc.eml", false, NULL);
+#endif
+
+       if (ret == true)
+               *data = fname;
+       else if (fname != NULL)  {
+               remove(fname);
+               EM_SAFE_FREE(fname);
+       }
+
+       EM_SAFE_FREE(p);
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list [%p], input_attachment_count [%d], input_meeting_request [%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+
+       int err = EMAIL_ERROR_NONE;
+       int attachment_id = 0, thread_id = -1, thread_item_count = 0, latest_mail_id_in_thread = -1;
+       int i = 0, rule_len, rule_matched = -1, local_attachment_count = 0, local_inline_content_count = 0;
+       int mailbox_id_spam = 0, mailbox_id_target = 0;
+       char *ext = NULL;
+       char name_buf[MAX_PATH] = {0x00, };
+       char *body_text_file_name = NULL;
+
+       int attachment_count = 0;
+       email_mail_data_t *mail_data = NULL;
+       email_attachment_data_t *attachment_data_list = NULL;
+       emstorage_mail_tbl_t    *converted_mail_tbl = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+       emstorage_attachment_tbl_t attachment_tbl = { 0 };
+       emstorage_account_tbl_t *account_tbl_item = NULL;
+       emstorage_rule_tbl_t *rule = NULL;
+       struct stat st_buf = { 0 };
+       char mailbox_id_param_string[10] = {0,};
+
+       /* Validating parameters */
+       if (!input_mail_data || !(input_mail_data->account_id) || !(input_mail_data->mailbox_id))  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (emcore_is_storage_full(&err) == true) {
+               EM_DEBUG_EXCEPTION("Storage is full");
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_account_by_id(input_mail_data->account_id, EMAIL_ACC_GET_OPT_DEFAULT | EMAIL_ACC_GET_OPT_OPTIONS, &account_tbl_item, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed. account_id[%d] err[%d]", input_mail_data->account_id, err);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (input_from_eas == 0 && input_mail_data->smime_type && input_mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_DRAFT) {
+               if (!emcore_convert_mail_data_to_smime_data(account_tbl_item, input_mail_data, input_attachment_data_list, input_attachment_count, &mail_data, &attachment_data_list, &attachment_count)) {
+                       EM_DEBUG_EXCEPTION("S/MIME failed");
+                       goto FINISH_OFF;
+               }
+       } else {
+               mail_data = input_mail_data;
+               attachment_data_list = input_attachment_data_list;
+               attachment_count = input_attachment_count;
+       }
+
+       mailbox_id_target = mail_data->mailbox_id;
+
+       if (input_from_eas == 0 &&
+                       !(input_mail_data->message_class & EMAIL_MESSAGE_CLASS_SMART_REPLY) &&
+                       !(input_mail_data->message_class & EMAIL_MESSAGE_CLASS_SMART_FORWARD) ) {
+               if (mail_data->file_path_plain)  {
+                       if (stat(mail_data->file_path_plain, &st_buf) < 0)  {
+                               EM_DEBUG_EXCEPTION("mail_data->file_path_plain, stat(\"%s\") failed...", mail_data->file_path_plain);
+                               err = EMAIL_ERROR_INVALID_MAIL;
+                               goto FINISH_OFF;
+                       }
+               }
+
+               if (mail_data->file_path_html)  {
+                       if (stat(mail_data->file_path_html, &st_buf) < 0)  {
+                               EM_DEBUG_EXCEPTION("mail_data->file_path_html, stat(\"%s\") failed...", mail_data->file_path_html);
+                               err = EMAIL_ERROR_INVALID_MAIL;
+                               goto FINISH_OFF;
+                       }
+               }
+
+               if (attachment_count && attachment_data_list)  {
+                       for (i = 0; i < attachment_count; i++)  {
+                               if (attachment_data_list[i].save_status) {
+                                       if (!attachment_data_list[i].attachment_path || stat(attachment_data_list[i].attachment_path, &st_buf) < 0)  {
+                                               EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", attachment_data_list[i].attachment_path);
+                                               err = EMAIL_ERROR_INVALID_ATTACHMENT;
+                                               goto FINISH_OFF;
+                                       }
+                               }
+                       }
+               }
+
+               if (!input_mail_data->full_address_from)
+                       input_mail_data->full_address_from = EM_SAFE_STRDUP(account_tbl_item->user_email_address);
+
+               /* check for email_address validation */
+               if (!em_verify_email_address_of_mail_data(mail_data, false, &err)) {
+                       EM_DEBUG_EXCEPTION("em_verify_email_address_of_mail_data failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (mail_data->report_status & EMAIL_MAIL_REPORT_MDN)  {
+                       /* check read-report mail */
+                       if(!mail_data->full_address_to) { /* A report mail should have 'to' address */
+                               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+                               err = EMAIL_ERROR_INVALID_PARAM;
+                               goto FINISH_OFF;
+                       }
+                       /* Create report mail body */
+                       /*
+                       if (!emcore_make_rfc822_file_from_mail(mail_src, NULL, NULL, NULL, &err))  {
+                               EM_DEBUG_EXCEPTION("emcore_make_rfc822_file_from_mail failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+                       */
+               }
+       }
+       else {  /*  For Spam handling */
+               email_option_t *opt = &account_tbl_item->options;
+               EM_DEBUG_LOG("block_address [%d], block_subject [%d]", opt->block_address, opt->block_subject);
+
+               if (opt->block_address || opt->block_subject)  {
+                       int is_completed = false;
+                       int type = 0;
+
+                       if (!opt->block_address)
+                               type = EMAIL_FILTER_SUBJECT;
+                       else if (!opt->block_subject)
+                               type = EMAIL_FILTER_FROM;
+
+                       if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_len, &is_completed, &rule, true, &err) || !rule)
+                               EM_DEBUG_LOG("No proper rules. emstorage_get_rule returns [%d]", err);
+               }
+
+               if (rule) {
+                       if (!emstorage_get_mailbox_id_by_mailbox_type(mail_data->account_id, EMAIL_MAILBOX_TYPE_SPAMBOX, &mailbox_id_spam, false, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
+                               mailbox_id_spam = 0;
+                       }
+
+                       if (mailbox_id_spam && !emcore_check_rule(mail_data->full_address_from, mail_data->subject, rule, rule_len, &rule_matched, &err))  {
+                               EM_DEBUG_EXCEPTION("emcore_check_rule failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+               }
+
+               if (rule_matched >= 0 && mailbox_id_spam)
+                       mailbox_id_target = mailbox_id_spam;
+       }
+
+       if ((err = emstorage_get_mailbox_by_id(mailbox_id_target, (emstorage_mailbox_tbl_t**)&mailbox_tbl)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_increase_mail_id(&mail_data->mail_id, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_increase_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("mail_data->mail_size [%d]", mail_data->mail_size);
+
+       if(mail_data->mail_size == 0)
+               emcore_calc_mail_size(mail_data, attachment_data_list, attachment_count, &(mail_data->mail_size)); /*  Getting file size before file moved.  */
+
+       EM_DEBUG_LOG("input_from_eas [%d] mail_data->body_download_status [%d]", input_from_eas, mail_data->body_download_status);
+
+       if (input_from_eas == 0|| mail_data->body_download_status) {
+               if (!emstorage_create_dir(mail_data->account_id, mail_data->mail_id, 0, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (mail_data->file_path_plain) {
+                       EM_DEBUG_LOG("mail_data->file_path_plain [%s]", mail_data->file_path_plain);
+                       /* EM_SAFE_STRNCPY(body_text_file_name, "UTF-8", MAX_PATH); */
+
+                       if ( (err = em_get_file_name_from_file_path(mail_data->file_path_plain, &body_text_file_name)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("em_get_file_name_from_file_path failed [%d]", err);
+                               err = EMAIL_ERROR_INVALID_FILE_PATH;
+                               goto FINISH_OFF;
+                       }
+
+                       /*
+                       if (input_from_eas)
+                               EM_SAFE_STRNCPY(body_text_file_name, UNKNOWN_CHARSET_PLAIN_TEXT_FILE, MAX_PATH);
+                       else
+                               EM_SAFE_STRNCPY(body_text_file_name, "UTF-8", MAX_PATH);
+                       */
+
+                       if (!emstorage_get_save_name(mail_data->account_id, mail_data->mail_id, 0, body_text_file_name, name_buf, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if (!emstorage_move_file(mail_data->file_path_plain, name_buf, input_from_eas, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+                       if (mail_data->body_download_status == EMAIL_BODY_DOWNLOAD_STATUS_NONE)
+                               mail_data->body_download_status = EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED;
+
+                       EM_SAFE_FREE(mail_data->file_path_plain);
+                       mail_data->file_path_plain = EM_SAFE_STRDUP(name_buf);
+               }
+
+               if (mail_data->file_path_html) {
+                       EM_DEBUG_LOG("mail_data->file_path_html [%s]", mail_data->file_path_html);
+                       /* EM_SAFE_STRNCPY(body_text_file_name, "UTF-8.htm", MAX_PATH); */
+
+                       EM_SAFE_FREE(body_text_file_name);
+
+                       if ( (err = em_get_file_name_from_file_path(mail_data->file_path_html, &body_text_file_name)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("em_get_file_name_from_file_path failed [%d]", err);
+                               err = EMAIL_ERROR_INVALID_FILE_PATH;
+                               goto FINISH_OFF;
+                       }
+                       /*
+                       if (input_from_eas)
+                               EM_SAFE_STRNCPY(body_text_file_name, UNKNOWN_CHARSET_HTML_TEXT_FILE, MAX_PATH);
+                       else
+                               EM_SAFE_STRNCPY(body_text_file_name, "UTF-8.htm", MAX_PATH);
+                       */
+
+                       if (!emstorage_get_save_name(mail_data->account_id, mail_data->mail_id, 0, body_text_file_name, name_buf, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if (!emstorage_move_file(mail_data->file_path_html, name_buf, input_from_eas, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if (mail_data->body_download_status == EMAIL_BODY_DOWNLOAD_STATUS_NONE)
+                               mail_data->body_download_status = EMAIL_BODY_DOWNLOAD_STATUS_FULLY_DOWNLOADED;
+
+                       EM_SAFE_FREE(mail_data->file_path_html);
+                       mail_data->file_path_html = EM_SAFE_STRDUP(name_buf);
+               }
+       }
+
+       if (mail_data->file_path_mime_entity) {
+               EM_DEBUG_LOG("mail_data->file_path_mime_entity [%s]", mail_data->file_path_mime_entity);
+
+               if (!emstorage_get_save_name(mail_data->account_id, mail_data->mail_id, 0, "mime_entity", name_buf, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_move_file(mail_data->file_path_mime_entity, name_buf, input_from_eas, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_SAFE_FREE(mail_data->file_path_mime_entity);
+               mail_data->file_path_mime_entity = EM_SAFE_STRDUP(name_buf);
+       }
+
+       if (!mail_data->date_time)  {
+               /* time isn't set */
+               mail_data->date_time = time(NULL);
+       }
+
+
+       mail_data->mailbox_id           = mailbox_id_target;
+       mail_data->mailbox_type         = mailbox_tbl->mailbox_type;
+       mail_data->server_mail_status   = !input_from_eas;
+       mail_data->save_status          = EMAIL_MAIL_STATUS_SAVED;
+
+       /*  Getting attachment count */
+       for (i = 0; i < attachment_count; i++) {
+               if (attachment_data_list[i].inline_content_status== 1)
+                       local_inline_content_count++;
+               local_attachment_count++;
+       }
+
+       mail_data->inline_content_count = local_inline_content_count;
+       mail_data->attachment_count     = local_attachment_count;
+
+       EM_DEBUG_LOG("inline_content_count   [%d]", local_inline_content_count);
+       EM_DEBUG_LOG("attachment_count [%d]", local_attachment_count);
+
+       EM_DEBUG_LOG("preview_text[%p]", mail_data->preview_text);
+       if (mail_data->preview_text == NULL) {
+               if ( (err = emcore_get_preview_text_from_file(mail_data->file_path_plain, mail_data->file_path_html, MAX_PREVIEW_TEXT_LENGTH, &(mail_data->preview_text))) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_get_preview_text_from_file failed[%d]", err);
+
+                       if (err != EMAIL_ERROR_EMPTY_FILE)
+                               goto FINISH_OFF;
+               }
+       }
+
+       if (!em_convert_mail_data_to_mail_tbl(mail_data, 1, &converted_mail_tbl, &err)) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_data_to_mail_tbl failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       converted_mail_tbl->mailbox_id        = mailbox_tbl->mailbox_id;
+       converted_mail_tbl->mailbox_name      = EM_SAFE_STRDUP(mailbox_tbl->mailbox_name);
+
+       /* Fill address information */
+       emcore_fill_address_information_of_mail_tbl(converted_mail_tbl);
+
+       /* Fill thread id */
+       if(mail_data->thread_id == 0) {
+               if (emstorage_get_thread_id_of_thread_mails(converted_mail_tbl, &thread_id, &latest_mail_id_in_thread, &thread_item_count) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_LOG(" emstorage_get_thread_id_of_thread_mails is failed");
+
+               if (thread_id == -1) {
+                       converted_mail_tbl->thread_id         = mail_data->mail_id;
+                       converted_mail_tbl->thread_item_count = thread_item_count = 1;
+               }
+               else  {
+                       converted_mail_tbl->thread_id         = thread_id;
+                       thread_item_count++;
+               }
+       }
+       else {
+               thread_item_count                         = 2;
+       }
+
+       mail_data->thread_id = converted_mail_tbl->thread_id;
+
+       emstorage_begin_transaction(NULL, NULL, NULL);
+
+       /*  insert mail to mail table */
+       if (!emstorage_add_mail(converted_mail_tbl, 0, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_add_mail failed [%d]", err);
+               /*  ROLLBACK TRANSACTION; */
+               emstorage_rollback_transaction(NULL, NULL, NULL);
+
+               goto FINISH_OFF;
+       }
+
+       /* Update thread information */
+       EM_DEBUG_LOG("thread_item_count [%d]", thread_item_count);
+
+       if (thread_item_count > 1) {
+               if (!emstorage_update_latest_thread_mail(mail_data->account_id, converted_mail_tbl->thread_id, 0, 0, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_update_latest_thread_mail failed [%d]", err);
+                       emstorage_rollback_transaction(NULL, NULL, NULL);
+
+                       goto FINISH_OFF;
+               }
+       }
+
+       /*  Insert attachment information to DB */
+
+       for (i = 0; i < attachment_count; i++) {
+               if (attachment_data_list[i].attachment_size == 0) {
+                       /* set attachment size */
+                       if(attachment_data_list[i].attachment_path && stat(attachment_data_list[i].attachment_path, &st_buf) < 0)
+                               attachment_data_list[i].attachment_size = st_buf.st_size;
+               }
+
+               if (!attachment_data_list[i].inline_content_status) {
+                       if (!emstorage_get_new_attachment_no(&attachment_id, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_new_attachment_no failed [%d]", err);
+                               emstorage_rollback_transaction(NULL, NULL, NULL);
+                               goto FINISH_OFF;
+                       }
+               }
+
+               if (!emstorage_create_dir(mail_data->account_id, mail_data->mail_id, attachment_data_list[i].inline_content_status ? 0  :  attachment_id, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_create_dir failed [%d]", err);
+                       emstorage_rollback_transaction(NULL, NULL, NULL);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_get_save_name(mail_data->account_id, mail_data->mail_id, attachment_data_list[i].inline_content_status ? 0  :  attachment_id, attachment_data_list[i].attachment_name, name_buf, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_save_name failed [%d]", err);
+                       emstorage_rollback_transaction(NULL, NULL, NULL);
+                       goto FINISH_OFF;
+               }
+               /* if (input_from_eas == 0 || attachment_data_list[i].save_status) { */
+               if (attachment_data_list[i].save_status) {
+                       if (!emstorage_copy_file(attachment_data_list[i].attachment_path, name_buf, input_from_eas, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_copy_file failed [%d]", err);
+                               emstorage_rollback_transaction(NULL, NULL, NULL);
+                               goto FINISH_OFF;
+                       }
+
+                       if ((ext = strrchr(attachment_data_list[i].attachment_name, '.'))) {
+                               if (!strncmp(ext, ".vcs", strlen(".vcs")))
+                                       remove(attachment_data_list[i].attachment_path);
+                               else if (!strncmp(ext, ".vcf", strlen(".vcf")))
+                                       remove(attachment_data_list[i].attachment_path);
+                               else if (!strncmp(ext, ".vnt", strlen(".vnt")))
+                                       remove(attachment_data_list[i].attachment_path);
+                       }
+               }
+
+               memset(&attachment_tbl, 0, sizeof(emstorage_attachment_tbl_t));
+               attachment_tbl.attachment_name                  = attachment_data_list[i].attachment_name;
+               attachment_tbl.attachment_path                  = name_buf;
+               attachment_tbl.attachment_size                  = attachment_data_list[i].attachment_size;
+               attachment_tbl.mail_id                          = mail_data->mail_id;
+               attachment_tbl.account_id                       = mail_data->account_id;
+               attachment_tbl.mailbox_id                       = mail_data->mailbox_id;
+               attachment_tbl.attachment_save_status           = attachment_data_list[i].save_status;
+               attachment_tbl.attachment_drm_type              = attachment_data_list[i].drm_status;
+               attachment_tbl.attachment_inline_content_status = attachment_data_list[i].inline_content_status;
+
+               if (!emstorage_add_attachment(&attachment_tbl, 0, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_add_attachment failed [%d]", err);
+                       emstorage_rollback_transaction(NULL, NULL, NULL);
+
+                       goto FINISH_OFF;
+               }
+               attachment_data_list[i].attachment_id = attachment_tbl.attachment_id;
+       }
+
+       /*  Insert Meeting request to DB */
+       if (mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_REQUEST
+               || mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_RESPONSE
+               || mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST) {
+               EM_DEBUG_LOG("This mail has the meeting request");
+               input_meeting_request->mail_id = mail_data->mail_id;
+               if (!emstorage_add_meeting_request(mail_data->account_id, mailbox_tbl->mailbox_id, input_meeting_request, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_add_meeting_request failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+       }
+
+       emstorage_commit_transaction(NULL, NULL, NULL);
+
+       SNPRINTF(mailbox_id_param_string, 10, "%d", mailbox_tbl->mailbox_id);
+       if (!emcore_notify_storage_event(NOTI_MAIL_ADD, converted_mail_tbl->account_id, converted_mail_tbl->mail_id, mailbox_id_param_string, converted_mail_tbl->thread_id))
+               EM_DEBUG_LOG("emcore_notify_storage_event [NOTI_MAIL_ADD] failed.");
+
+       if (account_tbl_item->incoming_server_type != EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               if (!emcore_remove_overflowed_mails(mailbox_tbl, &err)) {
+                       if (err == EMAIL_ERROR_MAIL_NOT_FOUND || err == EMAIL_ERROR_NOT_SUPPORTED)
+                               err = EMAIL_ERROR_NONE;
+                       else
+                               EM_DEBUG_LOG("emcore_remove_overflowed_mails failed [%d]", err);
+               }
+       }
+
+       if ( input_from_eas && (mail_data->flags_seen_field == 0)
+                               && mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_TRASH
+                               && mail_data->mailbox_type != EMAIL_MAILBOX_TYPE_SPAMBOX) {
+               if ((err = emcore_update_sync_status_of_account(mail_data->account_id, SET_TYPE_SET, SYNC_STATUS_SYNCING | SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
+                               EM_DEBUG_LOG("emcore_update_sync_status_of_account failed [%d]", err);
+//             emcore_add_notification_for_unread_mail(converted_mail_tbl);
+               emcore_display_unread_in_badge();
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(body_text_file_name);
+
+       if (account_tbl_item)
+               emstorage_free_account(&account_tbl_item, 1, NULL);
+
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       if (converted_mail_tbl)
+               emstorage_free_mail(&converted_mail_tbl, 1, NULL);
+
+       EM_DEBUG_FUNC_END();
+       return err;
+}
+
+INTERNAL_FUNC int emcore_add_read_receipt(int input_read_mail_id, int *output_receipt_mail_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_read_mail_id [%d], output_receipt_mail_id [%p]", input_read_mail_id, output_receipt_mail_id);
+       int                      err = EMAIL_ERROR_NONE;
+       int                      attachment_count = 0;
+       ENVELOPE                *envelope = NULL;
+       email_mail_data_t       *read_mail_data = NULL;
+       email_mail_data_t       *receipt_mail_data = NULL;
+       emstorage_mail_tbl_t    *receipt_mail_tbl_data = NULL;
+       email_attachment_data_t *attachment_data = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+       BODY                    *root_body = NULL;
+
+       if( (err = emcore_get_mail_data(input_read_mail_id, &read_mail_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_data failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       receipt_mail_data = em_malloc(sizeof(email_mail_data_t));
+
+       if (!receipt_mail_data)  {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memcpy(receipt_mail_data, read_mail_data, sizeof(email_mail_data_t));
+
+       receipt_mail_data->full_address_to = EM_SAFE_STRDUP(read_mail_data->full_address_from);
+       receipt_mail_data->message_id      = EM_SAFE_STRDUP(read_mail_data->message_id);
+
+       if (read_mail_data->subject)  {
+               receipt_mail_data->subject = em_malloc(EM_SAFE_STRLEN(read_mail_data->subject) + 7);
+               if (!(receipt_mail_data->subject))  {
+                       EM_DEBUG_EXCEPTION("em_malloc failed...");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               SNPRINTF(receipt_mail_data->subject, EM_SAFE_STRLEN(read_mail_data->subject) + 7,  "Read: %s", read_mail_data->subject);
+       }
+
+       if (!emstorage_get_mailbox_by_mailbox_type(receipt_mail_data->account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &mailbox_tbl, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       receipt_mail_data->mailbox_id           = mailbox_tbl->mailbox_id;
+       receipt_mail_data->mailbox_type         = EMAIL_MAILBOX_TYPE_OUTBOX;
+       receipt_mail_data->file_path_html       = NULL;
+       receipt_mail_data->flags_draft_field    = 1;
+       receipt_mail_data->body_download_status = 1;
+       receipt_mail_data->save_status          = (unsigned char)EMAIL_MAIL_STATUS_SENDING;
+       receipt_mail_data->report_status        = (unsigned char)EMAIL_MAIL_REPORT_MDN;
+
+       if (!em_convert_mail_data_to_mail_tbl(receipt_mail_data, 1, &receipt_mail_tbl_data, &err)) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_data_to_mail_tbl failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( (err = emcore_make_envelope_from_mail(receipt_mail_tbl_data, &envelope)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_make_envelope_from_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       envelope->references = EM_SAFE_STRDUP(read_mail_data->message_id);
+
+       if (!emcore_get_report_mail_body(envelope, &root_body, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_get_report_mail_body failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       receipt_mail_data->file_path_plain  = EM_SAFE_STRDUP(root_body->nested.part->body.sparep);
+
+       /* Report attachment */
+       /* Final-Recipient :  rfc822;digipop@gmail.com
+          Original-Message-ID:  <r97a77ag0jdhkvvxke58u9i5.1345611508570@email.android.com>
+          Disposition :  manual-action/MDN-sent-manually; displayed */
+
+       /*
+       receipt_mail_data->attachment_count = 1;
+       attachment_count                    = 1;
+
+       attachment_data = em_malloc(sizeof(email_attachment_data_t));
+       if (!attachment_data)  {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       attachment_data->save_status     = 1;
+       attachment_data->attachment_path = EM_SAFE_STRDUP(root_body->nested.part->next->body.sparep);
+
+       if (!emcore_get_file_name(attachment_data->attachment_path, &p, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_get_file_name failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       attachment_data->attachment_name = cpystr(p);
+       */
+
+       if ( (err = emcore_add_mail(receipt_mail_data, attachment_data, attachment_count, NULL, 0)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_add_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       *output_receipt_mail_id = receipt_mail_data->mail_id;
+
+FINISH_OFF:
+       if(receipt_mail_data) {
+               EM_SAFE_FREE(receipt_mail_data->full_address_to);
+               EM_SAFE_FREE(receipt_mail_data->message_id);
+               EM_SAFE_FREE(receipt_mail_data->subject);
+               EM_SAFE_FREE(receipt_mail_data);
+       }
+
+       if(mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       if(read_mail_data)
+               emcore_free_mail_data_list(&read_mail_data, 1);
+
+       if(attachment_data)
+               emcore_free_attachment_data(&attachment_data, 1, NULL);
+
+       if(receipt_mail_tbl_data)
+               emstorage_free_mail(&receipt_mail_tbl_data, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_add_meeting_request(int account_id, int input_mailbox_id, email_meeting_request_t *meeting_req, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], input_mailbox_id[%d], meeting_req[%p], err_code[%p]", account_id, input_mailbox_id, meeting_req, err_code);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!meeting_req || meeting_req->mail_id <= 0) {
+               if (meeting_req)
+                       EM_DEBUG_EXCEPTION("mail_id[%d]", meeting_req->mail_id);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_add_meeting_request(account_id, input_mailbox_id, meeting_req, 1, &err))  {
+               EM_DEBUG_EXCEPTION(" emstorage_add_meeting_request failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+/*  send a mail */
+INTERNAL_FUNC int emcore_send_mail(int account_id, int input_mailbox_id, int mail_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], input_mailbox_id[%d], mail_id[%d], err_code[%p]", account_id, input_mailbox_id, mail_id, err_code);
+       EM_PROFILE_BEGIN(profile_emcore_send_mail);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE, err2 = EMAIL_ERROR_NONE;
+       int status = EMAIL_SEND_FAIL;
+       int attachment_tbl_count = 0;
+       int i = 0;
+       SENDSTREAM *stream = NULL;
+       ENVELOPE *envelope = NULL;
+       sslstart_t stls = NULL;
+       emstorage_mail_tbl_t       *mail_tbl_data = NULL;
+       emstorage_attachment_tbl_t *attachment_tbl_data = NULL;
+       email_account_t *ref_account = NULL;
+       email_option_t *opt = NULL;
+       void *tmp_stream = NULL;
+       char *fpath = NULL;
+       int sent_box = 0;
+       emstorage_mailbox_tbl_t* local_mailbox = NULL;
+       int dst_mailbox_id = 0;
+
+       if (!account_id || !mail_id)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(ref_account = emcore_get_account_reference(account_id))) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /*  get mail to send */
+       if (!emstorage_get_mail_by_id(mail_id, &mail_tbl_data, false, &err) || err != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_attachment_list(mail_id, false, &attachment_tbl_data, &attachment_tbl_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_check_send_mail_thread_status()) {
+               EM_DEBUG_EXCEPTION("emcore_check_send_mail_thread_status failed...");
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       if ((!mail_tbl_data->full_address_to) && (!mail_tbl_data->full_address_cc) && (!mail_tbl_data->full_address_bcc)) {
+               err = EMAIL_ERROR_NO_RECIPIENT;
+               EM_DEBUG_EXCEPTION("No Recipient information [%d]", err);
+               goto FINISH_OFF;
+       }
+       else {
+               if ((err = em_verify_email_address_of_mail_tbl(mail_tbl_data, false)) != EMAIL_ERROR_NONE) {
+                       err = EMAIL_ERROR_INVALID_ADDRESS;
+                       EM_DEBUG_EXCEPTION("em_verify_email_address_of_mail_tbl failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (!emcore_check_send_mail_thread_status()) {
+               EM_DEBUG_EXCEPTION("emcore_check_send_mail_thread_status failed...");
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       opt = &(ref_account->options);
+
+#ifdef __FEATURE_SUPPORT_VALIDATION_SYSTEM__
+       EM_VALIDATION_SYSTEM_LOG("INFO", mail_id, "Email Send Start, %s -> %s, success", mail_tbl_data->full_address_from, mail_tbl_data->full_address_to);
+       for (i = 0; i < attachment_tbl_count; i++) {
+               if(attachment_tbl_data)
+                       EM_VALIDATION_SYSTEM_LOG("FILE", mail_id, "[%s], %d", attachment_tbl_data[i].attachment_path, attachment_tbl_data[i].attachment_size);
+       }
+#endif /* __FEATURE_SUPPORT_VALIDATION_SYSTEM__ */
+
+       /*Update status flag to DB*/
+
+       /*  get rfc822 data */
+       if (!emcore_make_rfc822_file_from_mail(mail_tbl_data, attachment_tbl_data, attachment_tbl_count, &envelope, &fpath, opt, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_make_rfc822_file_from_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!envelope || (!envelope->to && !envelope->cc && !envelope->bcc))  {
+               EM_DEBUG_EXCEPTION(" no recipients found...");
+               err = EMAIL_ERROR_NO_RECIPIENT;
+               goto FINISH_OFF;
+       }
+
+       /*  if there is no security option, unset security. */
+       if (!ref_account->outgoing_server_secure_connection)  {
+               stls = (sslstart_t)mail_parameters(NULL, GET_SSLSTART, NULL);
+               mail_parameters(NULL, SET_SSLSTART, NULL);
+       }
+
+       if (!emcore_check_send_mail_thread_status()) {
+               EM_DEBUG_EXCEPTION("emcore_check_send_mail_thread_status failed...");
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       if (ref_account->pop_before_smtp != FALSE)  {
+               if (!emcore_connect_to_remote_mailbox(account_id, 0, (void **)&tmp_stream, &err))  {
+                       EM_DEBUG_EXCEPTION(" POP before SMTP Authentication failed [%d]", err);
+                       status = EMAIL_LIST_CONNECTION_FAIL;
+                       if (err == EMAIL_ERROR_CONNECTION_BROKEN)
+                               err = EMAIL_ERROR_CANCELLED;
+                       goto FINISH_OFF;
+               }
+       }
+       if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_DRAFT, &local_mailbox, false, &err))  {
+               EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       dst_mailbox_id = local_mailbox->mailbox_id;
+
+       if(local_mailbox)
+               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
+
+       if (!emcore_connect_to_remote_mailbox(account_id, EMAIL_CONNECT_FOR_SENDING, (void **)&tmp_stream, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_connect_to_remote_mailbox failed [%d]", err);
+
+               if (err == EMAIL_ERROR_CONNECTION_BROKEN)
+                       err = EMAIL_ERROR_CANCELLED;
+               status = EMAIL_SEND_CONNECTION_FAIL;
+               goto FINISH_OFF;
+       }
+
+       stream = (SENDSTREAM *)tmp_stream;
+
+       if (!emcore_check_send_mail_thread_status()) {
+               EM_DEBUG_EXCEPTION(" emcore_check_send_mail_thread_status failed...");
+               err = EMAIL_ERROR_CANCELLED;
+               goto FINISH_OFF;
+       }
+
+       /*  set request of delivery status. */
+       EM_DEBUG_LOG("opt->req_delivery_receipt [%d]", opt->req_delivery_receipt);
+       EM_DEBUG_LOG("mail_tbl_data->report_status [%d]", mail_tbl_data->report_status);
+
+       if (opt->req_delivery_receipt == EMAIL_OPTION_REQ_DELIVERY_RECEIPT_ON || (mail_tbl_data->report_status & EMAIL_MAIL_REQUEST_DSN))  {
+               EM_DEBUG_LOG("DSN is required.");
+               stream->protocol.esmtp.dsn.want = 1;
+               stream->protocol.esmtp.dsn.full = 0;
+               stream->protocol.esmtp.dsn.notify.failure = 1;
+               stream->protocol.esmtp.dsn.notify.success = 1;
+       }
+
+       mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SENDING;
+
+       /*Update status save_status to DB*/
+       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, false, &err))
+               EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err);
+
+       /*  send mail to server. */
+       if (!emcore_send_mail_smtp(stream, envelope, fpath, account_id, mail_id, &err)) {
+               EM_DEBUG_EXCEPTION(" emcore_send_mail_smtp failed [%d]", err);
+#ifndef __FEATURE_MOVE_TO_OUTBOX_FIRST__
+               if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &local_mailbox, false, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               dst_mailbox_id = local_mailbox->mailbox_id;
+
+               if(local_mailbox)
+                       emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
+               /*  unsent mail is moved to 'OUTBOX'. */
+               if (!emcore_move_mail(&mail_id, 1, dst_mailbox_id, EMAIL_MOVED_BY_COMMAND, 0, NULL))
+                       EM_DEBUG_EXCEPTION(" emcore_mail_move falied...");
+#endif
+               goto FINISH_OFF;
+       }
+
+       /*  sent mail is moved to 'SENT' box or deleted. */
+       if (opt->keep_local_copy)  {
+               if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_SENTBOX, &local_mailbox, true, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+               dst_mailbox_id = local_mailbox->mailbox_id;
+
+               if (!emcore_move_mail(&mail_id, 1, dst_mailbox_id, EMAIL_MOVED_AFTER_SENDING, 0, &err))
+                       EM_DEBUG_EXCEPTION(" emcore_mail_move falied [%d]", err);
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+               else if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) /* To be synced to Sent box only IMAP not for POP */ {
+
+                       emstorage_activity_tbl_t new_activity;
+                       int activityid = 0;
+
+                       if (false == emcore_get_next_activity_id(&activityid, &err)) {
+                               EM_DEBUG_EXCEPTION(" emcore_get_next_activity_id Failed [%d] ", err);
+                       }
+
+                       memset(&new_activity, 0x00, sizeof(emstorage_activity_tbl_t));
+                       new_activity.activity_id  =  activityid;
+                       new_activity.server_mailid = NULL;
+                       new_activity.account_id = account_id;
+                       new_activity.mail_id    = mail_id;
+                       new_activity.activity_type = ACTIVITY_SAVEMAIL;
+                       new_activity.dest_mbox  = NULL;
+                       new_activity.src_mbox   = NULL;
+
+                       if (!emcore_add_activity(&new_activity, &err)) {
+                               EM_DEBUG_EXCEPTION(" emcore_add_activity Failed [%d] ", err);
+                       }
+
+                       if (!emcore_move_mail_on_server(dest_mbox.account_id, dst_mailbox_id, &mail_id, 1, dest_mbox.name, &err)) {
+                               EM_DEBUG_EXCEPTION(" emcore_move_mail_on_server falied [%d]", err);
+                       }
+                       else {
+                               /* Remove ACTIVITY_SAVEMAIL activity */
+                               new_activity.activity_id  =  activityid;
+                               new_activity.activity_type = ACTIVITY_SAVEMAIL;
+                               new_activity.account_id = account_id;
+                               new_activity.mail_id    = mail_id;
+                               new_activity.dest_mbox  = NULL;
+                               new_activity.server_mailid = NULL;
+                               new_activity.src_mbox   = NULL;
+
+                               if (!emcore_delete_activity(&new_activity, &err)) {
+                                       EM_DEBUG_EXCEPTION(">>>>>>Local Activity [ACTIVITY_SAVEMAIL] [%d] ", err);
+                               }
+                       }
+                       sent_box = 1;
+               }
+#endif
+#endif
+
+               /* On Successful Mail sent remove the Draft flag */
+               mail_tbl_data->flags_draft_field = 0;
+
+               if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "flags_draft_field", mail_tbl_data->flags_draft_field, false, &err))
+                       EM_DEBUG_EXCEPTION("Failed to modify extra flag [%d]", err);
+
+               sent_box = 1;
+       }
+       else  {
+               if (!emcore_delete_mail(account_id, &mail_id, 1, EMAIL_DELETE_LOCALLY, EMAIL_DELETED_AFTER_SENDING, false, &err))
+                       EM_DEBUG_EXCEPTION(" emcore_delete_mail failed [%d]", err);
+       }
+
+       /* Set the phone log */
+       if ((err = emcore_set_sent_contacts_log(mail_tbl_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_set_sent_contacts_log failed : [%d]", err);
+       }
+
+       /*Update status save_status to DB*/
+       mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SENT;
+       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, false, &err))
+               EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err);
+
+       if (!emcore_delete_transaction_info_by_mailId(mail_id))
+               EM_DEBUG_EXCEPTION(" emcore_delete_transaction_info_by_mailId failed for mail_id[%d]", mail_id);
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == false && err != EMAIL_ERROR_INVALID_PARAM && mail_tbl_data)  {
+               if (err != EMAIL_ERROR_CANCELLED) {
+                       mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SEND_FAILURE;
+                       if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, false, &err2))
+                               EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err2);
+               }
+               else {
+                       if (EMAIL_MAIL_STATUS_SEND_CANCELED == mail_tbl_data->save_status)
+                               EM_DEBUG_LOG("EMAIL_MAIL_STATUS_SEND_CANCELED Already set for ");
+                       else {
+                               mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SEND_CANCELED;
+                               if (!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", mail_tbl_data->save_status, false, &err2))
+                                       EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]", err2);
+                       }
+               }
+       }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+#ifndef __FEATURE_KEEP_CONNECTION__
+       if (stream)
+               smtp_close(stream);
+#endif /* __FEATURE_KEEP_CONNECTION__ */
+       if (stls)
+               mail_parameters(NULL, SET_SSLSTART, (void  *)stls);
+
+       if (attachment_tbl_data)
+               emstorage_free_attachment(&attachment_tbl_data, attachment_tbl_count, NULL);
+
+       if (envelope)
+               mail_free_envelope(&envelope);
+
+       if (fpath) {
+               EM_DEBUG_LOG("REMOVE TEMP FILE  :  %s", fpath);
+               remove(fpath);
+               free(fpath);
+       }
+
+       if(local_mailbox)
+               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
+       if (ret == true) {
+               if (!emcore_notify_network_event(NOTI_SEND_FINISH, account_id, NULL, mail_id, 0))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEND_FINISH] Failed");
+#ifdef __FEATURE_SUPPORT_VALIDATION_SYSTEM__
+               if(mail_tbl_data)
+                       EM_VALIDATION_SYSTEM_LOG("INFO", mail_id, "Email Send End, %s -> %s, success", mail_tbl_data->full_address_from, mail_tbl_data->full_address_to);
+#endif
+       }
+       else {
+               if (!emcore_notify_network_event(NOTI_SEND_FAIL, account_id, NULL, mail_id, err))
+                       EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEND_FAIL] Failed");
+#ifdef __FEATURE_SUPPORT_VALIDATION_SYSTEM__
+               if(mail_tbl_data)
+               EM_VALIDATION_SYSTEM_LOG("INFO", mail_id, "Email Send End, %s -> %s, failed", mail_tbl_data->full_address_from, mail_tbl_data->full_address_to);
+#endif
+               emcore_show_user_message(mail_id, EMAIL_ACTION_SEND_MAIL, err);
+       }
+
+       if (mail_tbl_data)
+               emstorage_free_mail(&mail_tbl_data, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_PROFILE_END(profile_emcore_send_mail);
+       EM_DEBUG_FUNC_END("ret [%d], err [%d]", ret, err);
+       return ret;
+}
+
+/*  send a saved all mails */
+INTERNAL_FUNC int emcore_send_saved_mail(int account_id, char *input_mailbox_name, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], input_mailbox_name[%p], err_code[%p]", account_id, input_mailbox_name, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int status = EMAIL_SEND_FAIL;
+       int *mail_ids = NULL;
+       int handle = 0;
+       int i = 0;
+       int total = 0;
+       int attachment_tbl_count = 0;
+       char *fpath = NULL;
+       SENDSTREAM *stream = NULL;
+       ENVELOPE *envelope = NULL;
+       email_account_t *ref_account = NULL;
+       emstorage_mail_tbl_t       *searched_mail_tbl_data = NULL;
+       emstorage_attachment_tbl_t *attachment_tbl_data    = NULL;
+       email_option_t *opt = NULL;
+       sslstart_t      stls = NULL;
+       void *tmp_stream = NULL;
+       emstorage_mailbox_tbl_t* local_mailbox = NULL;
+       int dst_mailbox_id = 0;
+
+       if (!account_id || !input_mailbox_name)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+
+       if (!(ref_account = emcore_get_account_reference(account_id)))  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       FINISH_OFF_IF_CANCELED;
+
+       opt = &(ref_account->options);
+
+       /*  search mail. */
+       if (!emstorage_mail_search_start(NULL, account_id, input_mailbox_name, 0, &handle, &total, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_mail_search_start failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       mail_ids = em_malloc(sizeof(int) * total);
+       if (mail_ids == NULL) {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < total ; i++) {
+               if (!emstorage_mail_search_result(handle, RETRIEVE_ID, (void **)&mail_ids[i], true, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_mail_search_result failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (!emstorage_mail_search_end(handle, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_mail_search_end failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       handle = 0;
+
+       mail_send_notify(EMAIL_SEND_PREPARE, 0, 0, account_id, mail_ids[total], err);
+
+       for (i = 0; i < total; i++) {
+               FINISH_OFF_IF_CANCELED;
+
+               if (!emstorage_get_mail_by_id(mail_ids[i], &searched_mail_tbl_data, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mail_by_id failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               /* Skip the mail canceled */
+               if (searched_mail_tbl_data->save_status == EMAIL_MAIL_STATUS_SEND_CANCELED)  {
+                       EM_DEBUG_EXCEPTION("The mail was canceled. [%d]", mail_ids[i]);
+                       emstorage_free_mail(&searched_mail_tbl_data, 1, &err);
+                       searched_mail_tbl_data = NULL;
+                       continue;
+               }
+
+               if ( (err = emstorage_get_attachment_list(mail_ids[i], false, &attachment_tbl_data, &attachment_tbl_count)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               /* check for email_address validation */
+               if ( (err = em_verify_email_address_of_mail_tbl(searched_mail_tbl_data, false)) != EMAIL_ERROR_NONE ) {
+                       err = EMAIL_ERROR_INVALID_ADDRESS;
+                       EM_DEBUG_EXCEPTION("em_verify_email_address_of_mail_tbl failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               searched_mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SENDING;
+
+               if (!emcore_make_rfc822_file_from_mail(searched_mail_tbl_data, attachment_tbl_data, attachment_tbl_count, &envelope, &fpath, opt, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_make_rfc822_file_from_mail falied [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               FINISH_OFF_IF_CANCELED;
+
+               /*  connect mail server. */
+               if (!stream) {
+                       /*  if there no security option, unset security. */
+                       if (!ref_account->outgoing_server_secure_connection) {
+                               stls = (sslstart_t)mail_parameters(NULL, GET_SSLSTART, NULL);
+                               mail_parameters(NULL, SET_SSLSTART, NULL);
+                       }
+
+                       stream = NULL;
+                       if (!emcore_connect_to_remote_mailbox(account_id, EMAIL_CONNECT_FOR_SENDING, &tmp_stream, &err) || !tmp_stream)  {
+                               EM_DEBUG_EXCEPTION("emcore_connect_to_remote_mailbox failed [%d]", err);
+
+                               if (err == EMAIL_ERROR_CONNECTION_BROKEN)
+                                       err = EMAIL_ERROR_CANCELLED;
+
+                               status = EMAIL_SEND_CONNECTION_FAIL;
+                               goto FINISH_OFF;
+                       }
+
+                       stream = (SENDSTREAM *)tmp_stream;
+
+                       FINISH_OFF_IF_CANCELED;
+
+                       mail_send_notify(EMAIL_SEND_CONNECTION_SUCCEED, 0, 0, account_id, mail_ids[i], err);
+
+                       /*  reqest of delivery status. */
+                       if (opt && opt->req_delivery_receipt == EMAIL_OPTION_REQ_DELIVERY_RECEIPT_ON)  {
+                               stream->protocol.esmtp.dsn.want = 1;
+                               stream->protocol.esmtp.dsn.full = 0;
+                               stream->protocol.esmtp.dsn.notify.failure = 1;
+                               stream->protocol.esmtp.dsn.notify.success = 1;
+                       }
+
+                       mail_send_notify(EMAIL_SEND_START, 0, 0, account_id, mail_ids[i], err);
+               }
+
+               searched_mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SENDING;
+
+               /*  update mail status to sending. */
+               if (!emstorage_change_mail_field(mail_ids[i], UPDATE_EXTRA_FLAG, searched_mail_tbl_data, true, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
+
+                       goto FINISH_OFF;
+               }
+
+               if (!emcore_send_mail_smtp(stream, envelope, fpath, account_id, mail_ids[i], &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_send_mail_smtp failed [%d]", err);
+
+                       searched_mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SEND_FAILURE;
+
+                       /*  update mail status to failure. */
+                       if (!emstorage_change_mail_field(mail_ids[i], UPDATE_EXTRA_FLAG, searched_mail_tbl_data, true, &err))
+                               EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
+
+                       if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &local_mailbox, true, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+                       dst_mailbox_id = local_mailbox->mailbox_id;
+
+                       emcore_move_mail(&mail_ids[i], 1, dst_mailbox_id, EMAIL_MOVED_AFTER_SENDING, 0, NULL);
+
+                       if(local_mailbox)
+                               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
+                       goto FINISH_OFF;
+               }
+
+               searched_mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SENT;
+
+               /*  update mail status to sent mail. */
+               if (!emstorage_change_mail_field(mail_ids[i], UPDATE_EXTRA_FLAG, searched_mail_tbl_data, true, &err))  {
+                       EM_DEBUG_EXCEPTION("emstorage_change_mail_field failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               /*  sent mail is moved to 'SENT' box or deleted. */
+               if (opt->keep_local_copy)  {
+                       if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_SENTBOX, &local_mailbox, true, &err))  {
+                               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+                       dst_mailbox_id = local_mailbox->mailbox_id;
+
+                       if (!emcore_move_mail(&mail_ids[i], 1, dst_mailbox_id, EMAIL_MOVED_AFTER_SENDING, 0, &err))
+                               EM_DEBUG_EXCEPTION("emcore_mail_move falied [%d]", err);
+
+                       if(local_mailbox)
+                               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+               }
+               else  {
+                       if (!emcore_delete_mail(account_id, &mail_ids[i], 1, EMAIL_DELETE_LOCALLY, EMAIL_DELETED_AFTER_SENDING, false, &err))
+                               EM_DEBUG_EXCEPTION("emcore_delete_mail falied [%d]", err);
+               }
+
+               /* Set the phone log */
+               if ((err = emcore_set_sent_contacts_log(searched_mail_tbl_data)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_set_sent_contacts_log failed : [%d]", err);
+               }
+
+               if(searched_mail_tbl_data) {
+                       emstorage_free_mail(&searched_mail_tbl_data, 1, NULL);
+                       searched_mail_tbl_data = NULL;
+               }
+
+               if(attachment_tbl_data)
+                       emstorage_free_attachment(&attachment_tbl_data, attachment_tbl_count, NULL);
+
+               mail_free_envelope(&envelope); envelope = NULL;
+
+               if (fpath)  {
+                       remove(fpath);
+                       EM_SAFE_FREE(fpath);
+               }
+       }
+
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (stream)
+               smtp_close(stream);
+
+       if (stls)
+               mail_parameters(NIL, SET_SSLSTART, (void  *)stls);
+
+       if (envelope)
+               mail_free_envelope(&envelope);
+
+       if (handle)  {
+               if (!emstorage_mail_search_end(handle, true, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_mail_search_end failed [%d]", err);
+       }
+
+       if (searched_mail_tbl_data)
+               emstorage_free_mail(&searched_mail_tbl_data, 1, NULL);
+
+       if(attachment_tbl_data)
+               emstorage_free_attachment(&attachment_tbl_data, attachment_tbl_count, NULL);
+
+       if (fpath)  {
+               remove(fpath);
+               EM_SAFE_FREE(fpath);
+       }
+
+       if(local_mailbox)
+               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
+       if (ret == true)
+               mail_send_notify(EMAIL_SEND_FINISH, 0, 0, account_id, mail_ids[total], err);
+       else {
+               if(mail_ids) /* prevent 34385 */
+                       mail_send_notify(status, 0, 0, account_id, mail_ids[total], err);
+               emcore_show_user_message(account_id, EMAIL_ACTION_SEND_MAIL, err);
+       }
+
+       EM_SAFE_FREE(mail_ids);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       return ret;
+}
+
+static int emcore_send_mail_smtp(SENDSTREAM *stream, ENVELOPE *env, char *data_file, int account_id, int mail_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("stream[%p], env[%p], data_file[%s], account_id[%d], mail_id[%d], err_code[%p]", stream, env, data_file, account_id, mail_id, err_code);
+       EM_PROFILE_BEGIN(profile_emcore_send_mail_smtp);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int recipients = 0;
+       long total = 0, sent = 0, send_ret = 0, send_err = 0, sent_percent = 0, last_sent_percent = 0;
+       char buf[2048] = { 0, };
+       email_account_t *ref_account = NULL;
+       FILE *fp = NULL;
+
+       if (!env || !env->from || (!env->to && !env->cc && !env->bcc)) {
+               if (env != NULL)
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!env->from->mailbox || !env->from->host) {
+               EM_DEBUG_EXCEPTION("env->from->mailbox[%p], env->from->host[%p]", env->from->mailbox, env->from->host);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(ref_account = emcore_get_account_reference(account_id))) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("Modifying - MAIL FROM ");
+       if (ref_account->user_email_address == NULL) {
+               EM_DEBUG_LOG("ref_account->user_email_address is null!!");
+               SNPRINTF(buf, sizeof(buf), "FROM:<%s@%s>", env->from->mailbox, env->from->host);
+       }
+       else
+               SNPRINTF(buf, sizeof(buf), "FROM:<%s>", ref_account->user_email_address);
+
+       /*  set DSN for ESMTP */
+       if (stream->protocol.esmtp.ok) {
+               if (stream->protocol.esmtp.eightbit.ok && stream->protocol.esmtp.eightbit.want)
+                       strncat (buf, " BODY=8BITMIME", sizeof(buf)-(EM_SAFE_STRLEN(buf)+1));
+
+               EM_DEBUG_LOG("stream->protocol.esmtp.dsn.ok [%d]", stream->protocol.esmtp.dsn.ok);
+
+               if (stream->protocol.esmtp.dsn.ok && stream->protocol.esmtp.dsn.want) {
+                       EM_DEBUG_LOG("stream->protocol.esmtp.dsn.want is required");
+                       strncat (buf, stream->protocol.esmtp.dsn.full ? " RET=FULL" : " RET=HDRS", sizeof(buf)-EM_SAFE_STRLEN(buf)-1);
+                       if (stream->protocol.esmtp.dsn.envid)
+                               SNPRINTF (buf + EM_SAFE_STRLEN (buf), sizeof(buf)-(EM_SAFE_STRLEN(buf)), " ENVID=%.100s", stream->protocol.esmtp.dsn.envid);
+               }
+               else
+                       EM_DEBUG_LOG("stream->protocol.esmtp.dsn.want is not required or DSN is not supported");
+       }
+
+       EM_PROFILE_BEGIN(profile_prepare_and_head);
+       send_ret = smtp_send(stream, "RSET", 0);
+       EM_DEBUG_LOG("[SMTP] RSET --------> %s", stream->reply);
+
+       if (send_ret != SMTP_RESPONSE_OK) {
+               err = send_ret;
+               goto FINISH_OFF;
+       }
+
+       send_ret = smtp_send(stream, "MAIL", buf);
+       EM_DEBUG_LOG("[SMTP] MAIL %s --------> %s", buf, stream->reply);
+
+       switch (send_ret) {
+               case SMTP_RESPONSE_OK:
+                       break;
+
+               case SMTP_RESPONSE_WANT_AUTH  :
+               case SMTP_RESPONSE_WANT_AUTH2:
+                       EM_DEBUG_EXCEPTION("SMTP error : authentication required...");
+                       err = EMAIL_ERROR_AUTH_REQUIRED;
+                       goto FINISH_OFF;
+
+               case SMTP_RESPONSE_UNAVAIL:
+                       EM_DEBUG_EXCEPTION("SMTP error : sending unavailable...");
+                       err = EMAIL_ERROR_SMTP_SEND_FAILURE;
+                       goto FINISH_OFF;
+               case SMTP_RESPONSE_CONNECTION_BROKEN:
+                       EM_DEBUG_EXCEPTION("SMTP error : SMTP connection broken...");
+                       err = EMAIL_ERROR_SMTP_SEND_FAILURE;
+                       goto FINISH_OFF;
+               default:
+                       EM_DEBUG_EXCEPTION("SMTP error : sending unavailable...");
+                       err = EMAIL_ERROR_SMTP_SEND_FAILURE;
+                       goto FINISH_OFF;
+       }
+
+       if (env->to) {
+               send_ret = smtp_rcpt(stream, env->to, &send_err);
+               EM_DEBUG_LOG("[SMTP] RCPT TO : <%s@%s> ... --------> %s", env->to->mailbox, env->to->host, env->to->error ? env->to->error  :  stream->reply);
+               if (send_ret) {
+                       err = stream->replycode;
+                       goto FINISH_OFF;
+               }
+
+               if (!send_err)
+                       recipients++;
+       }
+
+       if (env->cc) {
+               send_ret = smtp_rcpt(stream, env->cc, &send_err);
+               EM_DEBUG_LOG("[SMTP] RCPT TO : <%s@%s> ... --------> %s", env->cc->mailbox, env->cc->host, env->cc->error ? env->cc->error  :  stream->reply);
+               if (send_ret) {
+                       err = stream->replycode;
+                       goto FINISH_OFF;
+               }
+
+               if (!send_err)
+                       recipients++;
+       }
+
+       if (env->bcc) {
+               send_ret = smtp_rcpt(stream, env->bcc, &send_err);
+               EM_DEBUG_LOG("[SMTP] RCPT TO : <%s@%s> ... --------> %s", env->bcc->mailbox, env->bcc->host, env->bcc->error ? env->bcc->error  :  stream->reply);
+               if (send_ret) {
+                       err = stream->replycode;
+                       goto FINISH_OFF;
+               }
+
+               if (!send_err)
+                       recipients++;
+       }
+
+
+       if (send_err) {
+               EM_DEBUG_EXCEPTION("One or more recipients failed...");
+               err = EMAIL_ERROR_INVALID_ADDRESS;
+       }
+
+       if (!recipients) {
+               EM_DEBUG_EXCEPTION("No valid recipients...");
+
+               switch (stream->replycode) {
+                       case SMTP_RESPONSE_UNAVAIL:
+                       case SMTP_RESPONSE_WANT_AUTH  :
+                       case SMTP_RESPONSE_WANT_AUTH2:
+                               err = EMAIL_ERROR_AUTH_REQUIRED;
+                               break;
+
+                       default:
+                               err = EMAIL_ERROR_INVALID_ADDRESS;
+                               break;
+               }
+               goto FINISH_OFF;
+       }
+
+       send_ret = smtp_send(stream, "DATA", 0);
+       EM_DEBUG_LOG("[SMTP] DATA --------> %s", stream->reply);
+       EM_PROFILE_END(profile_prepare_and_head);
+
+       if (send_ret != SMTP_RESPONSE_READY) {
+               err = send_ret;
+               goto FINISH_OFF;
+       }
+
+       if (data_file) {
+               EM_PROFILE_BEGIN(profile_open_file);
+               if (!(fp = fopen(data_file, "r+"))) {
+                       EM_DEBUG_EXCEPTION("fopen(\"%s\") failed...", data_file);
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+               EM_PROFILE_END(profile_open_file);
+
+
+#ifdef __FEATURE_SEND_OPTMIZATION__
+       {
+               char *data = NULL;
+               int read_size, allocSize, dataSize, gMaxAllocSize = 40960; /*  40KB */
+
+               fseek(fp, 0, SEEK_END);
+               total = ftell(fp);
+               fseek(fp, 0, SEEK_SET);
+               EM_DEBUG_LOG("total size [%d]", total);
+
+               if (total < gMaxAllocSize)
+                       allocSize = total + 1;
+               else
+                       allocSize = gMaxAllocSize;
+
+               EM_PROFILE_BEGIN(profile_allocation);
+               /* Allocate a buffer of max 2MB to read from file */
+               data = (char *)em_malloc(allocSize);
+               allocSize--;
+               EM_PROFILE_END(profile_allocation);
+
+               if (NULL == data) {
+                       err = EMAIL_ERROR_SMTP_SEND_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               while (total) {
+                       if (total  < allocSize)
+                               dataSize = total;
+                       else
+                               dataSize = allocSize;
+
+                       memset(data, 0x0, dataSize+1);
+                       read_size = fread(data, sizeof (char), dataSize, fp);
+
+                       if (read_size != dataSize) {
+                               /* read fail. */
+                               EM_SAFE_FREE(data);
+                               EM_DEBUG_EXCEPTION("Read from file failed");
+                               err = EMAIL_ERROR_SMTP_SEND_FAILURE;
+                               goto FINISH_OFF;
+                       }
+                       sent += read_size;
+
+                       EM_DEBUG_LOG("before smtp_soutr_test");
+                       if (!(send_ret = smtp_soutr_test(stream->netstream, data))) {
+                               EM_SAFE_FREE(data);
+                               EM_DEBUG_EXCEPTION("Failed to send the data ");
+                               err = EMAIL_ERROR_SMTP_SEND_FAILURE;
+                               goto FINISH_OFF;
+                       }
+                       else {
+                               sent_percent = (int) ((double)sent / (double)total * 100.0);
+                               if (last_sent_percent + 5 <= sent_percent) {
+                                       if (!emcore_notify_network_event(NOTI_SEND_START, account_id, NULL, mail_id, sent_percent))
+                                               EM_DEBUG_EXCEPTION("emcore_notify_network_event [NOTI_SEND_START] Failed >>>>");
+                                       last_sent_percent = sent_percent;
+                               }
+                               EM_DEBUG_LOG("Sent data Successfully. sent[%d] total[%d]", sent, total);
+                       }
+                       total -= dataSize;
+               }
+
+               EM_SAFE_FREE(data);
+       }
+#else
+               fseek(fp, 0, SEEK_END);
+               total = ftell(fp);
+               fseek(fp, 0, SEEK_SET);
+
+               while (fgets(buf, 1024, fp)) {
+#ifdef FEATURE_SEND_DATA_DEBUG
+                       EM_DEBUG_LOG("%s", buf);
+#endif
+                       sent += EM_SAFE_STRLEN(buf);
+
+                       if (!(send_ret = smtp_soutr(stream->netstream, buf)))
+                               break;
+                       /*  Sending Progress Notification */
+                       sent_percent = (int) ((double)sent / (double)total * 100.0);
+                       if (last_sent_percent + 5 <= sent_percent) {
+                               /* Disabled Temporary
+                               if (!emcore_notify_network_event(NOTI_SEND_START, account_id, NULL, mail_id, sent_percent))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_network_event [NOTI_SEND_START] Failed >>>>");
+                               */
+                               last_sent_percent = sent_percent;
+                       }
+               }
+
+#endif
+               if (!send_ret) {
+                       EM_DEBUG_EXCEPTION("smtp_soutr failed - %ld", send_ret);
+                       err = EMAIL_ERROR_SMTP_SEND_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       send_ret = smtp_send(stream, ".", 0);
+       EM_DEBUG_LOG("[SMTP] . --------> %s", stream->reply);
+
+       if (send_ret != SMTP_RESPONSE_OK) {
+               err = send_ret;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == false)
+               smtp_send(stream, "RSET", 0);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       if (fp)
+               fclose(fp);
+       EM_PROFILE_END(profile_emcore_send_mail_smtp);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/* ------ rfc822 handle --------------------------------------------------- */
+#define RANDOM_NUMBER_LENGTH 35
+
+char *emcore_generate_content_id_string(const char *hostname, int *err)
+{
+       EM_DEBUG_FUNC_BEGIN("hostname[%p]", hostname);
+
+       if (!hostname) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err)
+                       *err = EMAIL_ERROR_INVALID_PARAM;
+               return NULL;
+       }
+
+       int cid_length = RANDOM_NUMBER_LENGTH + EM_SAFE_STRLEN(hostname) + 2, random_number_1, random_number_2, random_number_3, random_number_4;
+       char *cid_string = NULL;
+
+       cid_string = malloc(cid_length);
+
+       if (!cid_string) {
+               if (err)
+                       *err = EMAIL_ERROR_OUT_OF_MEMORY;
+               return NULL;
+       }
+
+       memset(cid_string, 0, cid_length);
+
+       srand(time(NULL) + rand());
+       random_number_1 = rand() * rand();
+       random_number_2 = rand() * rand();
+       random_number_3 = rand() * rand();
+       random_number_4 = rand() * rand();
+
+       SNPRINTF(cid_string, cid_length, "<%08x%08x%08x%08x@%s>", random_number_1, random_number_2, random_number_3, random_number_4, hostname);
+
+       if (err)
+               *err = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END("cid_string [%s]", cid_string);
+       return cid_string;
+}
+
+
+/* ------ attach_part ----------------------------------------------------- */
+/*  data  :  if filename NULL, content data. */
+/*             else absolute path of file to be attached. */
+/*  data_len  :  length of data. if filename not NULL, ignored. */
+/*  file_name :  attahcment name. */
+static int attach_part(BODY *body, const unsigned char *data, int data_len, char *filename, char *content_sub_type, int is_inline, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("body[%p], data[%s], data_len[%d], filename[%s], content_sub_type[%s], err_code[%p]", body, data, data_len, filename, content_sub_type, err_code);
+
+       int        ret = false;
+       int        error = EMAIL_ERROR_NONE;
+       int        has_special_character = 0;
+       int        base64_file_name_length = 0;
+       int        i= 0;
+       gsize      bytes_read;
+       gsize      bytes_written;
+       char      *encoded_file_name = NULL;
+       char      *extension = NULL;
+       char      *base64_file_name = NULL;
+       char      *result_file_name = NULL;
+       char       content_disposition[100] = { 0, };
+       PARAMETER *last_param = NULL;
+       PARAMETER *param = NULL;
+       PART      *last_part = NULL;
+       PART      *part = NULL;
+       SIZEDTEXT  source_text;
+       GError    *glib_error = NULL;
+       CHARSET   *result_charset = NULL;
+
+       if (!body)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (body->nested.part)  {
+               last_part = body->nested.part;
+
+               if (last_part != NULL)  {
+                       while (last_part->next)
+                               last_part = last_part->next;
+               }
+       }
+
+       /*  PART */
+       part = mail_newbody_part();
+       if (part == NULL)  {
+               EM_DEBUG_EXCEPTION("mail_newbody_part failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       part->next = NULL;
+
+       if (last_part)
+               last_part->next = part;
+       else
+               body->nested.part = part;
+
+       last_part = part;
+
+       /* set data..  */
+       /* content_data = (unsigned char  *)fs_get(data_len + 1); */
+       /* memcpy(content_data, data, data_len); */
+       /* content_data[data_len] = 0; */
+
+       /* part->body.contents.text.data = content_data; */
+       /* part->body.contents.text.size = data_len; */
+
+       if (filename)  {   /*  attachment */
+               source_text.data = (unsigned char*)filename;
+               source_text.size = EM_SAFE_STRLEN(filename);
+
+               result_charset   = (CHARSET*)utf8_infercharset(&source_text);
+
+               if(result_charset) {
+                       EM_DEBUG_LOG("return_charset->name [%s]", result_charset->name);
+                       encoded_file_name = (char*)g_convert (filename, -1, "UTF-8", result_charset->name, &bytes_read, &bytes_written, &glib_error);
+               }
+               else {
+                       i = 0;
+                       while(filename[i]) {
+                               if(filename[i++] & 0x80) {
+                                       has_special_character = 1;
+                                       break;
+                               }
+                       }
+                       EM_DEBUG_LOG("has_special_character [%d]", has_special_character);
+                       if(has_special_character)
+                               encoded_file_name = (char*)g_convert (filename, -1, "UTF-8", "EUC-KR", &bytes_read, &bytes_written, &glib_error);
+               }
+
+               EM_DEBUG_LOG("encoded_file_name [%s]", encoded_file_name);
+
+               if(encoded_file_name == NULL)
+                       encoded_file_name = strdup(filename);
+
+               if(!em_encode_base64(encoded_file_name, EM_SAFE_STRLEN(encoded_file_name), &base64_file_name, (unsigned long*)&base64_file_name_length, &error)) {
+                       EM_DEBUG_EXCEPTION("em_encode_base64 failed. error [%d]", error);
+                       goto FINISH_OFF;
+               }
+
+               result_file_name = em_replace_string(base64_file_name, "\015\012", "");
+
+               EM_DEBUG_LOG("base64_file_name_length [%d]", base64_file_name_length);
+
+               if(result_file_name) {
+                       EM_SAFE_FREE(encoded_file_name);
+                       encoded_file_name = em_malloc(EM_SAFE_STRLEN(result_file_name) + 15);
+                       if(!encoded_file_name) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed.");
+                               goto FINISH_OFF;
+                       }
+                       snprintf(encoded_file_name, EM_SAFE_STRLEN(result_file_name) + 15, "=?UTF-8?B?%s?=", result_file_name);
+                       EM_DEBUG_LOG("encoded_file_name [%s]", encoded_file_name);
+               }
+
+               extension = em_get_extension_from_file_path(filename, NULL);
+
+               part->body.type = em_get_content_type_from_extension_string(extension, NULL);
+               if(part->body.type == TYPEIMAGE) {
+                       part->body.subtype = strdup(extension);
+               } else if (part->body.type == TYPEPKCS7_SIGN) {
+                       part->body.subtype = strdup("pkcs7-signature");
+                       part->body.type = TYPEAPPLICATION;
+               } else if (part->body.type == TYPEPKCS7_MIME) {
+                       part->body.subtype = strdup("pkcs7-mime");
+                       part->body.type = TYPEAPPLICATION;
+               } else
+                       part->body.subtype = strdup("octet-stream");
+
+               part->body.encoding = ENCBINARY;
+               part->body.size.bytes = data_len;
+
+               if (data)
+                       part->body.sparep = EM_SAFE_STRDUP((char *)data); /*  file path */
+               else
+                       part->body.sparep = NULL;
+
+               SNPRINTF(content_disposition, sizeof(content_disposition), "%s", "attachment");
+
+               part->body.disposition.type = cpystr(content_disposition);
+
+               /*  BODY PARAMETER */
+               /*  another parameter or get parameter-list from this   function-parameter */
+               param = mail_newbody_parameter();
+               if (param == NULL)  {
+                       EM_DEBUG_EXCEPTION("mail_newbody_parameter failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               param->attribute          = cpystr("name");
+               param->value              = cpystr(encoded_file_name);
+               param->next               = NULL;
+               last_param                = param;
+               last_part->body.parameter = last_param;
+
+               if (is_inline) {
+                       /*  CONTENT-ID */
+                       part->body.id = emcore_generate_content_id_string("com.samsung.slp.email", &error);
+                       part->body.type = TYPEIMAGE;
+                       /*  EM_SAFE_FREE(part->body.subtype); */
+                       /*  part->body.subtype = EM_SAFE_STRDUP(content_sub_type); */
+               }
+
+               /*  DISPOSITION PARAMETER */
+               param = mail_newbody_parameter();
+               if (param == NULL)  {
+                       EM_DEBUG_EXCEPTION("mail_newbody_parameter failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               param->attribute                      = cpystr("filename");
+               param->value                          = cpystr(encoded_file_name);
+               param->next                           = NULL;
+               last_param                            = param;
+               last_part->body.disposition.parameter = last_param;
+
+               if (is_inline)
+                       last_part->body.disposition.type = strdup("inline");
+       }
+       else  {
+               /*  text body (plain/html) */
+               part->body.type = TYPETEXT;
+               part->body.size.bytes = data_len;
+
+               if (data)
+                       part->body.sparep = EM_SAFE_STRDUP((char *)data); /*  file path */
+               else
+                       part->body.sparep = NULL;
+
+
+               if (!content_sub_type)  {
+                       /* Plain text body */
+                       part->body.encoding = ENC8BIT;
+                       part->body.subtype = cpystr("plain");
+                       last_param = part->body.parameter;
+
+                       if (last_param != NULL)  {
+                               while (last_param->next)
+                                       last_param = last_param->next;
+                       }
+
+                       param = mail_newbody_parameter();
+
+                       if (param == NULL)  {
+                               EM_DEBUG_EXCEPTION("mail_newbody_parameter failed...");
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       param->attribute = cpystr("CHARSET");
+
+                       if (data != NULL) {
+                               gchar *extract_charset_plain = g_path_get_basename((const gchar *)data);
+                               if (extract_charset_plain != NULL && extract_charset_plain[0] != '\0')
+                                       param->value = cpystr(extract_charset_plain);
+                               g_free(extract_charset_plain);
+                       }
+                       else
+                               param->value = cpystr("UTF-8");
+
+                       if(!param->value)
+                               param->value = cpystr("UTF-8");
+
+                       param->next = NULL;
+
+                       if (last_param != NULL)
+                               last_param->next = param;
+                       else
+                               part->body.parameter = param;
+               }
+               else {
+                       /* HTML text body */
+                       part->body.encoding = ENC8BIT;
+                       part->body.subtype  = cpystr(content_sub_type);
+
+                       last_param = part->body.parameter;
+
+                       if (last_param != NULL)  {
+                               while (last_param->next)
+                                       last_param = last_param->next;
+                       }
+
+                       param = mail_newbody_parameter();
+
+                       if (param == NULL)  {
+                               EM_DEBUG_EXCEPTION("mail_newbody_parameter failed...");
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       param->attribute = cpystr("CHARSET");
+
+                       char *pHtml = NULL;
+                       if (data != NULL) {
+                               gchar *extract_charset = g_path_get_basename((const gchar *)data);
+                               if (extract_charset != NULL) {
+                                       if ((pHtml = strstr(extract_charset, ".htm")) != NULL) {
+                                               extract_charset[pHtml-extract_charset] = '\0';
+                                               param->value = cpystr(extract_charset);
+                                       }
+                               }
+
+                               if(!param->value)
+                                       param->value = cpystr("UTF-8");
+
+                               EM_SAFE_FREE(extract_charset);
+                       }
+                       else
+                               param->value = cpystr("UTF-8");
+                       param->next = NULL;
+
+                       if (last_param != NULL)
+                               last_param->next = param;
+                       else
+                               part->body.parameter = param;
+               }
+
+               /* NOTE : need to require this code. */
+               /* sprintf(content_disposition, "%s\0", "inline"); */
+               if (is_inline) {
+                       SNPRINTF(content_disposition, sizeof(content_disposition), "%s", "inline");
+                       part->body.disposition.type = cpystr(content_disposition);
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(encoded_file_name);
+       EM_SAFE_FREE(result_file_name); /*prevent 26242*/
+       EM_SAFE_FREE(base64_file_name);
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+static PART *attach_mutipart_with_sub_type(BODY *parent_body, char *sub_type, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("parent_body[%p], sub_type [%s], err_code[%p]", parent_body, sub_type, err_code);
+
+       int error = EMAIL_ERROR_NONE;
+
+       PART *tail_part_cur = NULL;
+       PART *new_part = NULL;
+
+       if (!parent_body || !sub_type)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (parent_body->nested.part)  {
+               tail_part_cur = parent_body->nested.part;
+
+               if (tail_part_cur != NULL)  {
+                       while (tail_part_cur->next)
+                               tail_part_cur = tail_part_cur->next;
+               }
+       }
+
+       new_part = mail_newbody_part();
+
+       if (new_part == NULL)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+
+       }
+
+       new_part->next = NULL;
+       new_part->body.type = TYPEMULTIPART;
+       new_part->body.subtype = EM_SAFE_STRDUP(sub_type);
+
+       if (tail_part_cur)
+               tail_part_cur->next = new_part;
+       else
+               parent_body->nested.part = new_part;
+
+FINISH_OFF:
+
+       if (err_code)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END();
+
+       return new_part;
+}
+#ifdef __FEATURE_SUPPORT_REPORT_MAIL__
+static int attach_attachment_to_body(BODY **multipart_body, BODY *text_body, emstorage_attachment_tbl_t *input_attachment_tbl, int input_attachment_tbl_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("multipart_body[%p], text_body[%p], input_attachment_tbl[%p], input_attachment_tbl_count [%d], err_code[%p]", multipart_body, text_body, input_attachment_tbl, input_attachment_tbl_count, err_code);
+
+       int ret = false;
+       int i = 0;
+       int error = EMAIL_ERROR_NONE;
+       BODY *frame_body = NULL;
+       /*  make multipart body(multipart frame_body..) .. that has not content..  */
+
+       if (!multipart_body || !text_body || !input_attachment_tbl) {
+               EM_DEBUG_EXCEPTION(" multipart_body[%p], text_body[%p], input_attachment_tbl[%p]", multipart_body, text_body, input_attachment_tbl);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       frame_body = mail_newbody();
+       if (frame_body == NULL) {
+               EM_DEBUG_EXCEPTION("mail_newbody failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       frame_body->type = TYPEMULTIPART;
+       frame_body->contents.text.data = NULL;
+       frame_body->contents.text.size = 0;
+       frame_body->size.bytes = 0;
+
+       /*  insert original text_body to frame_body.. */
+       if (!attach_part(frame_body, text_body->sparep, 0, NULL, NULL, false, &error))  {
+               EM_DEBUG_EXCEPTION(" attach_part failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       /*  insert files..  */
+       emstorage_attachment_tbl_t *temp_attachment_tbl = NULL;
+       char *name = NULL;
+       struct stat st_buf;
+
+       for(i = 0; i < input_attachment_tbl_count; i++) {
+               temp_attachment_tbl = input_attachment_tbl + i;
+
+               EM_DEBUG_LOG("insert files - attachment id[%d]", temp_attachment_tbl->attachment_id);
+
+               if (stat(temp_attachment_tbl->attachment_path, &st_buf) == 0)  {
+                       if (!temp_attachment_tbl->attachment_name)  {
+                               if (!emcore_get_file_name(temp_attachment_tbl->attachment_path, &name, &error))  {
+                                       EM_DEBUG_EXCEPTION("emcore_get_file_name failed [%d]", error);
+                                       goto FINISH_OFF;
+                               }
+                       }
+                       else
+                               name = temp_attachment_tbl->attachment_name;
+
+                       if (!attach_part(frame_body, (unsigned char *)temp_attachment_tbl->attachment_path, 0, name, NULL, false, &error))  {
+                               EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *multipart_body = frame_body;
+       else if (frame_body != NULL)
+               mail_free_body(&frame_body);
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+#endif
+static char *emcore_encode_rfc2047_text(char *utf8_text, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("utf8_text[%s], err_code[%p]", utf8_text, err_code);
+
+       if (utf8_text == NULL)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return NULL;
+       }
+
+       gsize len = EM_SAFE_STRLEN(utf8_text);
+
+       EM_DEBUG_FUNC_END();
+
+       if (len > 0)
+               return g_strdup_printf("=?UTF-8?B?%s?=", g_base64_encode((const guchar  *)utf8_text, len));
+       else
+               return strdup("");
+}
+
+static void emcore_encode_rfc2047_address(ADDRESS *address, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("address[%p], err_code[%p]", address, err_code);
+
+       while (address)  {
+               if (address->personal)  {
+                       char *rfc2047_personal = emcore_encode_rfc2047_text(address->personal, err_code);
+                       EM_SAFE_FREE(address->personal);
+                       address->personal = rfc2047_personal;
+               }
+               address = address->next;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+#define DATE_STR_LENGTH 100
+
+static int emcore_make_envelope_from_mail(emstorage_mail_tbl_t *input_mail_tbl_data, ENVELOPE **output_envelope)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_tbl_data[%p], output_envelope[%p]", input_mail_tbl_data, output_envelope);
+
+       int     ret = false;
+       int       error                   = EMAIL_ERROR_NONE;
+       int       is_incomplete           = 0;
+       char     *pAdd                    = NULL;
+       ENVELOPE *envelope                = NULL;
+       email_account_t *ref_account      = NULL;
+
+       if (!input_mail_tbl_data || !output_envelope)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               return error; /* prevent 32729 */
+       }
+
+       if ( (input_mail_tbl_data->report_status & EMAIL_MAIL_REPORT_MDN) != 0 && !input_mail_tbl_data->body_download_status) {
+               EM_DEBUG_EXCEPTION("input_mail_tbl_data->body_download_status[%p]", input_mail_tbl_data->body_download_status);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(envelope = mail_newenvelope()))  {
+               EM_DEBUG_EXCEPTION("mail_newenvelope failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       is_incomplete = input_mail_tbl_data->flags_draft_field || (input_mail_tbl_data->save_status == EMAIL_MAIL_STATUS_SENDING);
+
+       if (is_incomplete && (input_mail_tbl_data->account_id > 0))  {
+               ref_account = emcore_get_account_reference(input_mail_tbl_data->account_id);
+               if (!ref_account)  {
+                       EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", input_mail_tbl_data->account_id);
+                       error = EMAIL_ERROR_INVALID_ACCOUNT;
+                       goto FINISH_OFF;
+               }
+
+               if (ref_account->user_email_address && ref_account->user_email_address[0] != '\0')  {
+                       char *p = cpystr(ref_account->user_email_address);
+
+                       if (p == NULL)  {
+                               EM_DEBUG_EXCEPTION("cpystr failed...");
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       EM_DEBUG_LOG("Assign envelope->from");
+
+                       if (input_mail_tbl_data->full_address_from) {
+                               char *temp_address_string = NULL ;
+                               em_skip_whitespace(input_mail_tbl_data->full_address_from , &temp_address_string);
+                               EM_DEBUG_LOG("address[temp_address_string][%s]", temp_address_string);
+                               rfc822_parse_adrlist(&envelope->from, temp_address_string, NULL);
+                               EM_SAFE_FREE(temp_address_string);
+                               temp_address_string = NULL ;
+                       }
+                       else
+                               envelope->from = rfc822_parse_mailbox(&p, NULL);
+
+                       EM_SAFE_FREE(p);
+                       if (!envelope->from) {
+                               EM_DEBUG_EXCEPTION("rfc822_parse_mailbox failed...");
+                               error = EMAIL_ERROR_INVALID_ADDRESS;
+                               goto FINISH_OFF;
+                       }
+                       else  {
+                               if (envelope->from->personal == NULL) {
+                                       if (ref_account->options.display_name_from && ref_account->options.display_name_from[0] != '\0')
+                                               envelope->from->personal = cpystr(ref_account->options.display_name_from);
+                                       else
+                                               envelope->from->personal =
+                                                               (ref_account->user_display_name && ref_account->user_display_name[0] != '\0') ?
+                                                               cpystr(ref_account->user_display_name)  :  NULL;
+                               }
+                       }
+               }
+
+               if (ref_account->return_address && ref_account->return_address[0] != '\0')  {
+                       char *p = cpystr(ref_account->return_address);
+
+                       if (p == NULL)  {
+                               EM_DEBUG_EXCEPTION("cpystr failed...");
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+                       envelope->return_path = rfc822_parse_mailbox(&p, NULL);
+                       EM_SAFE_FREE(p);
+               }
+       }
+       else  {
+               if (!input_mail_tbl_data->full_address_from || !input_mail_tbl_data->full_address_to)  {
+                       EM_DEBUG_EXCEPTION("input_mail_tbl_data->full_address_from[%p], input_mail_tbl_data->full_address_to[%p]", input_mail_tbl_data->full_address_from, input_mail_tbl_data->full_address_to);
+                       error = EMAIL_ERROR_INVALID_MAIL;
+                       goto FINISH_OFF;
+               }
+
+               int i, j;
+
+               if (input_mail_tbl_data->full_address_from)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_from); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_from[i] == ';')
+                                       input_mail_tbl_data->full_address_from[i] = ',';
+                       }
+               }
+
+               if (input_mail_tbl_data->full_address_return)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_return); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_return[i] == ';')
+                                       input_mail_tbl_data->full_address_return[i] = ',';
+                       }
+               }
+               em_skip_whitespace(input_mail_tbl_data->full_address_from , &pAdd);
+               EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+
+               rfc822_parse_adrlist(&envelope->from, pAdd, NULL);
+               EM_SAFE_FREE(pAdd);
+               pAdd = NULL;
+
+               em_skip_whitespace(input_mail_tbl_data->full_address_return , &pAdd);
+               EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+
+               rfc822_parse_adrlist(&envelope->return_path, pAdd, NULL);
+               EM_SAFE_FREE(pAdd);
+               pAdd = NULL;
+       }
+
+       {
+               int i, j;
+
+               if (input_mail_tbl_data->full_address_to)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_to); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_to[i] == ';')
+                                       input_mail_tbl_data->full_address_to[i] = ',';
+                       }
+               }
+
+               if (input_mail_tbl_data->full_address_cc)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_cc); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_cc[i] == ';')
+                                       input_mail_tbl_data->full_address_cc[i] = ',';
+                       }
+               }
+
+               if (input_mail_tbl_data->full_address_bcc)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_bcc); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_bcc[i] == ';')
+                                       input_mail_tbl_data->full_address_bcc[i] = ',';
+                       }
+               }
+       }
+
+       em_skip_whitespace(input_mail_tbl_data->full_address_to , &pAdd);
+       EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+
+       rfc822_parse_adrlist(&envelope->to, pAdd, NULL);
+       EM_SAFE_FREE(pAdd);
+       pAdd = NULL ;
+
+       EM_DEBUG_LOG("address[input_mail_tbl_data->full_address_cc][%s]", input_mail_tbl_data->full_address_cc);
+       em_skip_whitespace(input_mail_tbl_data->full_address_cc , &pAdd);
+       EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+
+       rfc822_parse_adrlist(&envelope->cc, pAdd, NULL);
+       EM_SAFE_FREE(pAdd);
+       pAdd = NULL ;
+
+       em_skip_whitespace(input_mail_tbl_data->full_address_bcc , &pAdd);
+       rfc822_parse_adrlist(&envelope->bcc, pAdd, NULL);
+       EM_SAFE_FREE(pAdd);
+               pAdd = NULL ;
+
+       emcore_encode_rfc2047_address(envelope->return_path, &error);
+       emcore_encode_rfc2047_address(envelope->from, &error);
+       emcore_encode_rfc2047_address(envelope->sender, &error);
+       emcore_encode_rfc2047_address(envelope->reply_to, &error);
+       emcore_encode_rfc2047_address(envelope->to, &error);
+       emcore_encode_rfc2047_address(envelope->cc, &error);
+       emcore_encode_rfc2047_address(envelope->bcc, &error);
+
+       if (input_mail_tbl_data->subject)
+               envelope->subject = emcore_encode_rfc2047_text(input_mail_tbl_data->subject, &error);
+
+       char rfc822_date_string[DATE_STR_LENGTH] = { 0, };
+       rfc822_date(rfc822_date_string);
+
+       if (!is_incomplete)  {
+               char  localtime_string[DATE_STR_LENGTH] = { 0, };
+               strftime(localtime_string, 128, "%a, %e %b %Y %H : %M : %S ", localtime(&input_mail_tbl_data->date_time));
+               /* append last 5byes("+0900") */
+               g_strlcat(localtime_string, rfc822_date_string + (EM_SAFE_STRLEN(rfc822_date_string) -  5), DATE_STR_LENGTH);
+               envelope->date = (unsigned char *)cpystr((const char *)localtime_string);
+       }
+       else {
+               envelope->date = (unsigned char *)cpystr((const char *)rfc822_date_string);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ret)
+               *output_envelope = envelope;
+       else {
+               mail_free_envelope(&envelope);
+               *output_envelope = NULL;
+       }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+/*  Description : Make RFC822 text file from mail_tbl data */
+/*  Parameters :  */
+/*                     input_mail_tbl_data :   */
+/*                     is_draft  :  this mail is draft mail. */
+/*                     file_path :  path of file that rfc822 data will be written to. */
+INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_mail_tbl_data, emstorage_attachment_tbl_t *input_attachment_tbl, int input_attachment_count, ENVELOPE **env, char **file_path, email_option_t *sending_option, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_tbl_data[%p], env[%p], file_path[%p], sending_option[%p], err_code[%p]", input_mail_tbl_data, env, file_path, sending_option, err_code);
+
+       int       ret = false;
+       int       error = EMAIL_ERROR_NONE;
+       int       i = 0;
+       ENVELOPE *envelope      = NULL;
+       BODY     *text_body     = NULL;
+       BODY     *html_body     = NULL;
+       BODY     *root_body     = NULL;
+       PART     *part_for_html = NULL;
+       PARAMETER *param = NULL;
+       PART     *part_for_text = NULL;
+       char     *fname = NULL;
+
+       if (!input_mail_tbl_data)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ( (input_mail_tbl_data->report_status & EMAIL_MAIL_REPORT_MDN) != 0 && !input_mail_tbl_data->body_download_status) {
+               EM_DEBUG_EXCEPTION("input_mail_tbl_data->body_download_status[%p]", input_mail_tbl_data->body_download_status);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ( (error = emcore_make_envelope_from_mail(input_mail_tbl_data, &envelope)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_make_envelope_from_mail failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("input_mail_tbl_data->file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+       EM_DEBUG_LOG("input_mail_tbl_data->file_path_html[%s]", input_mail_tbl_data->file_path_html);
+       EM_DEBUG_LOG("input_mail_tbl_data->file_path_mime_entity[%s]", input_mail_tbl_data->file_path_mime_entity);
+       EM_DEBUG_LOG("input_mail_tbl_data->body->attachment_num[%d]", input_mail_tbl_data->attachment_count);
+
+       if ((input_mail_tbl_data->attachment_count > 0) || (input_mail_tbl_data->file_path_plain && input_mail_tbl_data->file_path_html))  {
+               EM_DEBUG_LOG("attachment_num [%d]", input_mail_tbl_data->attachment_count);
+
+               root_body = mail_newbody();
+
+               if (root_body == NULL)  {
+                       EM_DEBUG_EXCEPTION("mail_newbody failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               param = mail_newbody_parameter();
+
+               if (param == NULL) {
+                       EM_DEBUG_EXCEPTION("mail_newbody_parameter failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               if (input_mail_tbl_data->smime_type == EMAIL_SMIME_NONE) {
+
+                       root_body->type               = TYPEMULTIPART;
+                       root_body->subtype            = strdup("MIXED");
+
+                       mail_free_body_parameter(&param);
+                       param = NULL;
+
+               } else if (input_mail_tbl_data->smime_type == EMAIL_SMIME_SIGNED) {
+                       PARAMETER *protocol_param     = mail_newbody_parameter();
+
+                       root_body->type               = TYPEMULTIPART;
+                       root_body->subtype            = strdup("SIGNED");
+
+                       param->attribute       = cpystr("micalg");
+                       switch (input_mail_tbl_data->digest_type) {
+                       case DIGEST_TYPE_SHA1:
+                               param->value   = cpystr("sha1");
+                               break;
+                       case DIGEST_TYPE_MD5:
+                               param->value   = cpystr("md5");
+                               break;
+                       default:
+                               EM_DEBUG_EXCEPTION("Invalid digest type");
+                               break;
+                       }
+
+                       protocol_param->attribute   = cpystr("protocol");
+                       protocol_param->value       = cpystr("application/pkcs7-signature");
+                       protocol_param->next        = NULL;
+                       param->next                 = protocol_param;
+
+                       input_mail_tbl_data->file_path_plain = NULL;
+                       input_mail_tbl_data->file_path_html = NULL;
+
+                       input_attachment_tbl = input_attachment_tbl + (input_attachment_count - 1);
+
+                       input_attachment_count = 1;
+
+               } else {
+
+                       root_body->type    = TYPEAPPLICATION;
+                       root_body->subtype = strdup("PKCS7-MIME");
+
+                       param->attribute = cpystr("name");
+                       param->value = cpystr("smime.p7m");
+                       param->next = NULL;
+
+                       input_mail_tbl_data->file_path_plain = NULL;
+                       input_mail_tbl_data->file_path_html = NULL;
+                       input_mail_tbl_data->file_path_mime_entity = NULL;
+
+                       input_attachment_count = 1;
+               }
+
+               root_body->contents.text.data = NULL;
+               root_body->contents.text.size = 0;
+               root_body->size.bytes         = 0;
+               root_body->parameter          = param;
+
+               if (input_mail_tbl_data->smime_type == EMAIL_SMIME_NONE && input_mail_tbl_data->file_path_plain && input_mail_tbl_data->file_path_html) {
+                       part_for_text = attach_mutipart_with_sub_type(root_body, "ALTERNATIVE", &error);
+
+                       if (!part_for_text) {
+                               EM_DEBUG_EXCEPTION("attach_mutipart_with_sub_type [part_for_text] failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+
+                       text_body = &part_for_text->body;
+
+                       if (input_mail_tbl_data->file_path_plain && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_plain) > 0) {
+                               EM_DEBUG_LOG("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+                               if (!attach_part(text_body, (unsigned char *)input_mail_tbl_data->file_path_plain, 0, NULL, NULL, false, &error)) {
+                                       EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                                       goto FINISH_OFF;
+                               }
+                       }
+
+                       if (input_mail_tbl_data->file_path_html && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_html) > 0) {
+                               EM_DEBUG_LOG("file_path_html[%s]", input_mail_tbl_data->file_path_html);
+
+                               part_for_html = attach_mutipart_with_sub_type(text_body, "RELATED", &error);
+                               if (!part_for_html) {
+                                       EM_DEBUG_EXCEPTION("attach_mutipart_with_sub_type [part_for_html] failed [%d]", error);
+                                       goto FINISH_OFF;
+                               }
+
+                               if (!attach_part(&(part_for_html->body) , (unsigned char *)input_mail_tbl_data->file_path_html, 0, NULL, "html", false, &error)) {
+                                       EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+
+               if (input_mail_tbl_data->file_path_mime_entity && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_mime_entity) > 0) {
+                       EM_DEBUG_LOG("file_path_mime_entity[%s]", input_mail_tbl_data->file_path_mime_entity);
+                       root_body->sparep = EM_SAFE_STRDUP(input_mail_tbl_data->file_path_mime_entity);
+               }
+
+               if (input_attachment_tbl && input_attachment_count)  {
+                       emstorage_attachment_tbl_t *temp_attachment_tbl = NULL;
+                       char *name = NULL;
+                       BODY *body_to_attach = NULL;
+                       struct stat st_buf;
+
+                       for(i = 0; i < input_attachment_count; i++) {
+                               temp_attachment_tbl = input_attachment_tbl + i;
+                               EM_DEBUG_LOG("attachment_name[%s], attachment_path[%s]", temp_attachment_tbl->attachment_name, temp_attachment_tbl->attachment_path);
+                               if (stat(temp_attachment_tbl->attachment_path, &st_buf) == 0)  {
+                                       if (!temp_attachment_tbl->attachment_name)  {
+                                               if (!emcore_get_file_name(temp_attachment_tbl->attachment_path, &name, &error))  {
+                                                       EM_DEBUG_EXCEPTION("emcore_get_file_name failed [%d]", error);
+                                                       continue;
+                                               }
+                                       }
+                                       else
+                                               name = temp_attachment_tbl->attachment_name;
+
+                                       EM_DEBUG_LOG("name[%s]", name);
+
+                                       if (temp_attachment_tbl->attachment_inline_content_status && part_for_html)
+                                               body_to_attach = &(part_for_html->body);
+                                       else
+                                               body_to_attach = root_body;
+
+                                       if (!attach_part(body_to_attach, (unsigned char *)temp_attachment_tbl->attachment_path, 0, name, NULL, temp_attachment_tbl->attachment_inline_content_status, &error))  {
+                                               EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                                               continue;
+                                       }
+                               }
+                       }
+               }
+               text_body = NULL;
+       }
+       else {
+               text_body = mail_newbody();
+
+               if (text_body == NULL)  {
+                       EM_DEBUG_EXCEPTION("mail_newbody failed...");
+
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               text_body->type = TYPETEXT;
+               text_body->encoding = ENC8BIT;
+               if (input_mail_tbl_data->file_path_plain || input_mail_tbl_data->file_path_html)
+                       text_body->sparep = EM_SAFE_STRDUP(input_mail_tbl_data->file_path_plain ? input_mail_tbl_data->file_path_plain  :  input_mail_tbl_data->file_path_html);
+               else
+                       text_body->sparep = NULL;
+
+               if (input_mail_tbl_data->file_path_html != NULL && input_mail_tbl_data->file_path_html[0] != '\0')
+                       text_body->subtype = strdup("html");
+               if (text_body->sparep)
+                       text_body->size.bytes = EM_SAFE_STRLEN(text_body->sparep);
+               else
+                       text_body->size.bytes = 0;
+       }
+
+
+       if (input_mail_tbl_data->report_status & EMAIL_MAIL_REPORT_MDN) {
+               /*  Report mail */
+               EM_DEBUG_LOG("REPORT MAIL");
+               envelope->references = cpystr(input_mail_tbl_data->message_id);
+       }
+
+       if (file_path)  {
+               EM_DEBUG_LOG("write rfc822 : file_path[%p]", file_path);
+
+               if (part_for_html)
+                       html_body = &(part_for_html->body);
+
+               if (!emcore_write_rfc822(envelope, root_body ? root_body : text_body, html_body, input_mail_tbl_data->priority, input_mail_tbl_data->report_status, &fname, &error))  {
+                       EM_DEBUG_EXCEPTION("emcore_write_rfc822 failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+
+               *file_path = fname;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if ((ret == true) && (env != NULL))
+               *env = envelope;
+       else if (envelope != NULL)
+               mail_free_envelope(&envelope);
+
+       if (text_body != NULL)
+               mail_free_body(&text_body);
+
+       if (root_body != NULL)
+               mail_free_body(&root_body);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data, email_attachment_data_t *input_attachment_tbl, int input_attachment_count, char **file_path, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_tbl_data[%p], file_path[%p], err_code[%p]", input_mail_tbl_data, file_path, err_code);
+
+       int       ret                  = false;
+       int       error                = EMAIL_ERROR_NONE;
+       int       is_incomplete        = 0;
+       int       i                    = 0;
+       ENVELOPE *envelope             = NULL;
+       BODY     *text_body            = NULL;
+       BODY     *html_body            = NULL;
+       BODY     *root_body            = NULL;
+       PART     *part_for_html        = NULL;
+       PART     *part_for_text        = NULL;
+       char      temp_file_path_plain[512];
+       char      temp_file_path_html[512];
+       char     *pAdd                 = NULL;
+       char     *fname                = NULL;
+       emstorage_account_tbl_t *ref_account     = NULL;
+
+       if (!input_mail_tbl_data)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ( (input_mail_tbl_data->report_status & EMAIL_MAIL_REPORT_MDN) != 0 && !input_mail_tbl_data->body_download_status) {
+               EM_DEBUG_EXCEPTION("input_mail_tbl_data->body_download_status[%p]", input_mail_tbl_data->body_download_status);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_account_by_id(input_mail_tbl_data->account_id, GET_FULL_DATA_WITHOUT_PASSWORD, &ref_account, true, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed : [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", input_mail_tbl_data->account_id);
+               error = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!(envelope = mail_newenvelope()))  {
+               EM_DEBUG_EXCEPTION("mail_newenvelope failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       is_incomplete = input_mail_tbl_data->flags_draft_field || (input_mail_tbl_data->save_status == EMAIL_MAIL_STATUS_SENDING);
+
+       if (is_incomplete)  {
+               if (ref_account->user_email_address && ref_account->user_email_address[0] != '\0')  {
+                       char *p = cpystr(ref_account->user_email_address);
+
+                       if (p == NULL)  {
+                               EM_DEBUG_EXCEPTION("cpystr failed...");
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       EM_DEBUG_LOG("Assign envelop->from");
+
+                       if (input_mail_tbl_data->full_address_from) {
+                               char *temp_address_string = NULL ;
+                               em_skip_whitespace(input_mail_tbl_data->full_address_from , &temp_address_string);
+                               EM_DEBUG_LOG("address[temp_address_string][%s]", temp_address_string);
+                               rfc822_parse_adrlist(&envelope->from, temp_address_string, ref_account->outgoing_server_address);
+                               EM_SAFE_FREE(temp_address_string);
+                               temp_address_string = NULL ;
+                       }
+                       else
+                               envelope->from = rfc822_parse_mailbox(&p, NULL);
+
+                       EM_SAFE_FREE(p);
+                       if (!envelope->from)  {
+                               EM_DEBUG_EXCEPTION("rfc822_parse_mailbox failed...");
+                               error = EMAIL_ERROR_INVALID_ADDRESS;
+                               goto FINISH_OFF;
+                       }
+                       else  {
+
+                               if (envelope->from->personal == NULL) {
+                                       envelope->from->personal =
+                                               (ref_account->user_display_name && ref_account->user_display_name[0] != '\0')?
+                                               cpystr(ref_account->user_display_name)  :  NULL;
+                               }
+                       }
+               }
+       }
+
+       if (ref_account->return_address && ref_account->return_address[0] != '\0')  {
+               char *p = cpystr(ref_account->return_address);
+
+               if (p == NULL)  {
+                       EM_DEBUG_EXCEPTION("cpystr failed...");
+
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               envelope->return_path = rfc822_parse_mailbox(&p, NULL);
+               EM_SAFE_FREE(p);
+       }
+       else  {
+               if (!input_mail_tbl_data->full_address_from || !input_mail_tbl_data->full_address_to)  {
+                       EM_DEBUG_EXCEPTION("input_mail_tbl_data->full_address_from[%p], input_mail_tbl_data->full_address_to[%p]", input_mail_tbl_data->full_address_from, input_mail_tbl_data->full_address_to);
+                       error = EMAIL_ERROR_INVALID_MAIL;
+                       goto FINISH_OFF;
+               }
+
+               int i, j;
+
+               if (input_mail_tbl_data->full_address_from)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_from); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_from[i] == ';')
+                                       input_mail_tbl_data->full_address_from[i] = ',';
+                       }
+               }
+
+               if (input_mail_tbl_data->full_address_return)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_return); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_return[i] == ';')
+                                       input_mail_tbl_data->full_address_return[i] = ',';
+                       }
+               }
+                       em_skip_whitespace(input_mail_tbl_data->full_address_from , &pAdd);
+               EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+
+               rfc822_parse_adrlist(&envelope->from, pAdd, ref_account->outgoing_server_address);
+               EM_SAFE_FREE(pAdd);
+                       pAdd = NULL ;
+
+               em_skip_whitespace(input_mail_tbl_data->full_address_return , &pAdd);
+               EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+
+               rfc822_parse_adrlist(&envelope->return_path, pAdd, ref_account->outgoing_server_address);
+               EM_SAFE_FREE(pAdd);
+               pAdd = NULL ;
+       }
+
+       {
+               int i, j;
+
+               if (input_mail_tbl_data->full_address_to)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_to); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_to[i] == ';')
+                                       input_mail_tbl_data->full_address_to[i] = ',';
+                       }
+               }
+
+               if (input_mail_tbl_data->full_address_cc)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_cc); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_cc[i] == ';')
+                                       input_mail_tbl_data->full_address_cc[i] = ',';
+                       }
+               }
+
+               if (input_mail_tbl_data->full_address_bcc)  {
+                       for (i = 0, j = EM_SAFE_STRLEN(input_mail_tbl_data->full_address_bcc); i < j; i++)  {
+                               if (input_mail_tbl_data->full_address_bcc[i] == ';')
+                                       input_mail_tbl_data->full_address_bcc[i] = ',';
+                       }
+               }
+       }
+
+       em_skip_whitespace(input_mail_tbl_data->full_address_to , &pAdd);
+       EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+
+       rfc822_parse_adrlist(&envelope->to, pAdd, ref_account->outgoing_server_address);
+       EM_SAFE_FREE(pAdd);
+       pAdd = NULL ;
+
+       EM_DEBUG_LOG("address[input_mail_tbl_data->full_address_cc][%s]", input_mail_tbl_data->full_address_cc);
+       em_skip_whitespace(input_mail_tbl_data->full_address_cc , &pAdd);
+       EM_DEBUG_LOG("address[pAdd][%s]", pAdd);
+
+       rfc822_parse_adrlist(&envelope->cc, pAdd, ref_account->outgoing_server_address);
+       EM_SAFE_FREE(pAdd);
+               pAdd = NULL ;
+
+       em_skip_whitespace(input_mail_tbl_data->full_address_bcc , &pAdd);
+       rfc822_parse_adrlist(&envelope->bcc, pAdd, ref_account->outgoing_server_address);
+       EM_SAFE_FREE(pAdd);
+               pAdd = NULL ;
+
+       emcore_encode_rfc2047_address(envelope->return_path, &error);
+       emcore_encode_rfc2047_address(envelope->from, &error);
+       emcore_encode_rfc2047_address(envelope->sender, &error);
+       emcore_encode_rfc2047_address(envelope->reply_to, &error);
+       emcore_encode_rfc2047_address(envelope->to, &error);
+       emcore_encode_rfc2047_address(envelope->cc, &error);
+       emcore_encode_rfc2047_address(envelope->bcc, &error);
+
+       if (input_mail_tbl_data->subject)
+               envelope->subject = emcore_encode_rfc2047_text(input_mail_tbl_data->subject, &error);
+
+       char rfc822_date_string[DATE_STR_LENGTH] = { 0, };
+       char localtime_string[DATE_STR_LENGTH] = {0, };
+
+       rfc822_date(rfc822_date_string);
+
+       if (!is_incomplete)  {
+               strftime(localtime_string, 128, "%a, %e %b %Y %H : %M : %S ", localtime(&input_mail_tbl_data->date_time));
+               /*  append last 5byes("+0900") */
+               g_strlcat(localtime_string, rfc822_date_string + (EM_SAFE_STRLEN(rfc822_date_string) -  5), DATE_STR_LENGTH);
+               envelope->date = (unsigned char *)cpystr((const char *)localtime_string);
+       }
+       else {
+               envelope->date = (unsigned char *)cpystr((const char *)rfc822_date_string);
+       }
+       /*  check report input_mail_tbl_data */
+
+       /* Non-report input_mail_tbl_data */
+       EM_DEBUG_LOG("input_mail_tbl_data->file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+       EM_DEBUG_LOG("input_mail_tbl_data->file_path_html[%s]", input_mail_tbl_data->file_path_html);
+       EM_DEBUG_LOG("input_mail_tbl_data->body->attachment_num[%d]", input_mail_tbl_data->attachment_count);
+
+       if (input_mail_tbl_data->file_path_plain) {
+               memset(temp_file_path_plain, 0x00, sizeof(temp_file_path_plain));
+               SNPRINTF(temp_file_path_plain, sizeof(temp_file_path_plain), "%s%s%s", MAILTEMP, DIR_SEPERATOR, "UTF-8");
+
+               if (!emstorage_copy_file(input_mail_tbl_data->file_path_plain, temp_file_path_plain, 0, &error)) {
+                       EM_DEBUG_EXCEPTION("emstorage_copy_file failed : [%d]", error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (input_mail_tbl_data->file_path_html) {
+               memset(temp_file_path_html, 0x00, sizeof(temp_file_path_html));
+               SNPRINTF(temp_file_path_html, sizeof(temp_file_path_html), "%s%s%s", MAILTEMP, DIR_SEPERATOR, "UTF-8.htm");
+
+               if (!emstorage_copy_file(input_mail_tbl_data->file_path_html, temp_file_path_html, 0, &error)) {
+                       EM_DEBUG_EXCEPTION("emstorage_copy_file failed : [%d]", error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if ((input_mail_tbl_data->attachment_count > 0) || (input_mail_tbl_data->file_path_plain && input_mail_tbl_data->file_path_html))  {
+               EM_DEBUG_LOG("attachment_num  :  %d", input_mail_tbl_data->attachment_count);
+               root_body = mail_newbody();
+
+               if (root_body == NULL)  {
+                       EM_DEBUG_EXCEPTION("mail_newbody failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               root_body->type               = TYPEMULTIPART;
+               root_body->subtype            = strdup("MIXED");
+               root_body->contents.text.data = NULL;
+               root_body->contents.text.size = 0;
+               root_body->size.bytes         = 0;
+
+               part_for_text = attach_mutipart_with_sub_type(root_body, "ALTERNATIVE", &error);
+
+               if (!part_for_text) {
+                       EM_DEBUG_EXCEPTION("attach_mutipart_with_sub_type [part_for_text] failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+
+               text_body = &part_for_text->body;
+
+               if (input_mail_tbl_data->file_path_plain && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_plain) > 0)  {
+                       EM_DEBUG_LOG("file_path_plain[%s]", input_mail_tbl_data->file_path_plain);
+                       if (!attach_part(text_body, (unsigned char *)temp_file_path_plain, 0, NULL, NULL, false, &error))  {
+                               EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+               }
+
+               if (input_mail_tbl_data->file_path_html && EM_SAFE_STRLEN(input_mail_tbl_data->file_path_html) > 0)  {
+                       EM_DEBUG_LOG("file_path_html[%s]", input_mail_tbl_data->file_path_html);
+
+                       part_for_html = attach_mutipart_with_sub_type(text_body, "RELATED", &error);
+                       if (!part_for_html) {
+                               EM_DEBUG_EXCEPTION("attach_mutipart_with_sub_type [part_for_html] failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+
+                       if (!attach_part(&(part_for_html->body) , (unsigned char *)temp_file_path_html, 0, NULL, "html", false, &error))  {
+                               EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+               }
+
+               if (input_attachment_tbl && input_attachment_count)  {
+                       email_attachment_data_t *temp_attachment_tbl = NULL;
+                       char *name = NULL;
+                       BODY *body_to_attach = NULL;
+                       struct stat st_buf;
+
+                       for(i = 0; i < input_attachment_count; i++) {
+                               temp_attachment_tbl = input_attachment_tbl + i;
+                               EM_DEBUG_LOG("attachment_name[%s], attachment_path[%s]", temp_attachment_tbl->attachment_name, temp_attachment_tbl->attachment_path);
+                               if (stat(temp_attachment_tbl->attachment_path, &st_buf) == 0)  {
+                                       if (!temp_attachment_tbl->attachment_name)  {
+                                               if (!emcore_get_file_name(temp_attachment_tbl->attachment_path, &name, &error))  {
+                                                       EM_DEBUG_EXCEPTION("emcore_get_file_name failed [%d]", error);
+                                                       continue;
+                                               }
+                                       }
+                                       else
+                                               name = temp_attachment_tbl->attachment_name;
+                                       EM_DEBUG_LOG("name[%s]", name);
+
+                                       if (temp_attachment_tbl->inline_content_status && part_for_html)
+                                               body_to_attach = &(part_for_html->body);
+                                       else
+                                               body_to_attach = root_body;
+
+                                       if (!attach_part(body_to_attach, (unsigned char *)temp_attachment_tbl->attachment_path, 0, name, NULL, temp_attachment_tbl->inline_content_status, &error))  {
+                                               EM_DEBUG_EXCEPTION("attach_part failed [%d]", error);
+                                               continue;
+                                       }
+                               }
+                       }
+               }
+               text_body = NULL;
+       } else  {
+               text_body = mail_newbody();
+
+               if (text_body == NULL)  {
+                       EM_DEBUG_EXCEPTION("mail_newbody failed...");
+
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               text_body->type = TYPETEXT;
+               text_body->encoding = ENC8BIT;
+               if (input_mail_tbl_data->file_path_plain || input_mail_tbl_data->file_path_html)
+                       text_body->sparep = EM_SAFE_STRDUP(input_mail_tbl_data->file_path_plain ? temp_file_path_plain  :  temp_file_path_html);
+               else
+                       text_body->sparep = NULL;
+
+               if (input_mail_tbl_data->file_path_html != NULL && input_mail_tbl_data->file_path_html[0] != '\0')
+                       text_body->subtype = strdup("html");
+               if (text_body->sparep)
+                       text_body->size.bytes = EM_SAFE_STRLEN(text_body->sparep);
+               else
+                       text_body->size.bytes = 0;
+       }
+
+       if (file_path)  {
+               EM_DEBUG_LOG("write rfc822  :  file_path[%s]", file_path);
+
+               if (part_for_html)
+                       html_body = &(part_for_html->body);
+
+               if (!emcore_write_rfc822(envelope, root_body ? root_body  :  text_body, html_body, input_mail_tbl_data->priority, input_mail_tbl_data->report_status, &fname, &error))  {
+                       EM_DEBUG_EXCEPTION("emcore_write_rfc822 failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+
+               *file_path = fname;
+       }
+
+       if (EM_SAFE_STRLEN(temp_file_path_plain) > 0)  {
+               if (!emstorage_delete_file(temp_file_path_plain, &error))  {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_file failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (EM_SAFE_STRLEN(temp_file_path_html) > 0) {
+               if (!emstorage_delete_file(temp_file_path_html, &error))  {
+                       EM_DEBUG_EXCEPTION("emstorage_delete_file failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       emstorage_free_account(&ref_account, 1, NULL);
+
+       if (envelope != NULL)
+               mail_free_envelope(&envelope);
+
+       if (text_body != NULL)
+               mail_free_body(&text_body);
+
+       if (root_body != NULL)
+               mail_free_body(&root_body);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+#ifdef __FEATURE_SUPPORT_REPORT_MAIL__
+static int emcore_get_report_mail_body(ENVELOPE *envelope, BODY **multipart_body, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("envelope[%p], mulitpart_body[%p], err_code[%p]", envelope, multipart_body, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       BODY *m_body = NULL;
+       BODY *p_body = NULL;
+       BODY *text_body = NULL;
+       PARAMETER *param = NULL;
+       emstorage_attachment_tbl_t temp_attachment_tbl;
+       FILE *fp = NULL;
+       char *fname = NULL;
+       char buf[512] = {0x00, };
+       int sz = 0;
+
+       if (!envelope || !multipart_body)  {
+               EM_DEBUG_EXCEPTION(" envelope[%p], mulitpart_body[%p]", envelope, multipart_body);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(text_body = mail_newbody()))  {
+               EM_DEBUG_EXCEPTION(" mail_newbody failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_temp_file_name(&fname, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_get_temp_file_name failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!(fp = fopen(fname, "wb+")))  {
+               EM_DEBUG_EXCEPTION(" fopen failed - %s", fname);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!envelope->from || !envelope->from->mailbox || !envelope->from->host)  {
+               if (!envelope->from)
+                       EM_DEBUG_EXCEPTION(" envelope->from[%p]", envelope->from);
+               else
+                       EM_DEBUG_LOG(" envelope->from->mailbox[%p], envelope->from->host[%p]", envelope->from->mailbox, envelope->from->host);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /*
+       if (envelope->from->personal)
+               SNPRINTF(buf, sizeof(buf), "%s <%s@%s>", envelope->from->personal, envelope->from->mailbox, envelope->from->host);
+       else
+       */
+               SNPRINTF(buf, sizeof(buf), "%s@%s", envelope->from->mailbox, envelope->from->host);
+
+       fprintf(fp, "Your message has been read by %s"CRLF_STRING, buf);
+       fprintf(fp, "Date :  %s", envelope->date);
+
+       fclose(fp); fp = NULL;
+
+       if (!emcore_get_file_size(fname, &sz, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_get_file_size failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       text_body->type = TYPETEXT;
+       text_body->encoding = ENC8BIT;
+       text_body->sparep = EM_SAFE_STRDUP(fname);
+       text_body->size.bytes = (unsigned long)sz;
+
+       if (!emcore_get_temp_file_name(&fname, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_get_temp_file_name failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!(fp = fopen(fname, "wb+")))  {
+               EM_DEBUG_EXCEPTION(" fopen failed - %s", fname);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;               /* EMAIL_ERROR_UNKNOWN; */
+               goto FINISH_OFF;
+       }
+
+       if (!envelope->references)  {
+               EM_DEBUG_EXCEPTION(" envelope->references[%p]", envelope->references);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       fprintf(fp, "Final-Recipient :  rfc822;%s@%s\r", envelope->from->mailbox, envelope->from->host);
+       fprintf(fp, "Original-Message-ID:  %s\r", envelope->references);
+       fprintf(fp, "Disposition :  manual-action/MDN-sent-manually; displayed");
+
+       fclose(fp); fp = NULL;
+
+       memset(&temp_attachment_tbl, 0x00, sizeof(emstorage_attachment_tbl_t));
+
+       temp_attachment_tbl.attachment_path = EM_SAFE_STRDUP(fname);
+
+       if (!emcore_get_file_size(fname, &temp_attachment_tbl.attachment_size, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_get_file_size failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!attach_attachment_to_body(&m_body, text_body, &temp_attachment_tbl, 1, &err))  {
+               EM_DEBUG_EXCEPTION(" attach_attachment_to_body failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       text_body->contents.text.data = NULL;
+
+       /*  change mail header */
+
+       /*  set content-type to multipart/report */
+       m_body->subtype = strdup("report");
+
+       /*  set report-type parameter in content-type */
+       param = em_malloc(sizeof(PARAMETER));
+       if (!param)  {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       param->attribute  = strdup("report-type");
+       param->value      = strdup("disposition-notification");
+       param->next       = m_body->parameter;
+
+       m_body->parameter = param;
+
+       /*  change body-header */
+
+       p_body = &m_body->nested.part->next->body;
+
+       /*  set content-type to message/disposition-notification */
+       p_body->type      = TYPEMESSAGE;
+       p_body->encoding  = ENC7BIT;
+
+       EM_SAFE_FREE(p_body->subtype);
+
+       p_body->subtype = strdup("disposition-notification");
+
+       /*  set parameter */
+       mail_free_body_parameter(&p_body->parameter);
+       mail_free_body_parameter(&p_body->disposition.parameter);
+
+       EM_SAFE_FREE(p_body->disposition.type);
+
+       p_body->disposition.type = strdup("inline");
+
+       ret = true;
+
+FINISH_OFF:
+       if ((ret == true) && (multipart_body != NULL))
+               *multipart_body = m_body;
+       else if (m_body != NULL)
+               mail_free_body(&m_body);
+
+       if (text_body != NULL)
+               mail_free_body(&text_body);
+
+       if (fp != NULL)
+               fclose(fp);
+
+       EM_SAFE_FREE(fname);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return ret;
+}
+#endif
+
+INTERNAL_FUNC int emcore_get_body_buff(char *file_path, char **buff)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       FILE *r_fp = NULL;
+       int read_size = 0;
+       int ret = false;
+       char *read_buff = NULL;
+
+
+       if (file_path)
+               r_fp = fopen(file_path, "r");
+
+       if (!r_fp) {
+               EM_DEBUG_EXCEPTION(" Filename %s failed to open", file_path);
+               goto FINISH_OFF;
+       }
+
+
+       struct stat stbuf;
+       stat(file_path, &stbuf);
+       EM_DEBUG_LOG(" File Size [ %d ] ", stbuf.st_size);
+       read_buff = calloc(1, (stbuf.st_size+ 1));
+       read_size = fread(read_buff, 1, stbuf.st_size, r_fp);
+       read_buff[stbuf.st_size] = '\0';
+
+       if (ferror(r_fp)) {
+               EM_DEBUG_EXCEPTION("file read failed - %s", file_path);
+               EM_SAFE_FREE(read_buff);
+               goto FINISH_OFF;
+       }
+       ret = true;
+       *buff = read_buff;
+
+FINISH_OFF:
+       if (r_fp)
+               fclose(r_fp);
+
+       return ret;
+}
+
+static int emcore_copy_attachment_from_original_mail(int input_original_mail_id, int input_target_mail_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_original_mail_id[%d] input_target_mail_id[%d]", input_original_mail_id, input_target_mail_id);
+       int err = EMAIL_ERROR_NONE;
+       int i = 0, j = 0;
+       int original_mail_attachment_count = 0;
+       int target_mail_attachment_count = 0;
+       int attachment_id = 0;
+       char output_file_name[MAX_PATH] = { 0, };
+       char output_file_path[MAX_PATH] = { 0, };
+       emstorage_attachment_tbl_t *original_mail_attachment_array = NULL;
+       emstorage_attachment_tbl_t *target_mail_attachment_array = NULL;
+       emstorage_attachment_tbl_t *target_attach = NULL;
+
+       if((err = emstorage_get_attachment_list(input_original_mail_id, false, &original_mail_attachment_array, &original_mail_attachment_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if((err = emstorage_get_attachment_list(input_target_mail_id, false, &target_mail_attachment_array, &target_mail_attachment_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < original_mail_attachment_count; i++) {
+               for(j = 0; j < target_mail_attachment_count; j++) {
+                       if(strcmp(original_mail_attachment_array[i].attachment_name, target_mail_attachment_array[j].attachment_name) == 0 ) {
+                               target_attach = target_mail_attachment_array + j;
+
+                               /* If attachment is inline content, fild path should not include attachment id */
+                               if(target_attach->attachment_inline_content_status == 1)
+                                       attachment_id = 0;
+                               else
+                                       attachment_id = target_attach->attachment_id;
+
+                               EM_DEBUG_LOG("attachment_inline_content_status [%d] attachment_id[%d]", target_attach->attachment_inline_content_status, attachment_id);
+
+                               if(!emcore_save_mail_file(target_attach->account_id, target_attach->mail_id, attachment_id, original_mail_attachment_array[i].attachment_path, original_mail_attachment_array[i].attachment_name, output_file_path, &err)) {
+                                       EM_DEBUG_EXCEPTION("emcore_save_mail_file failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+
+                               EM_SAFE_FREE(target_attach->attachment_path);
+                               target_attach->attachment_path = EM_SAFE_STRDUP(output_file_path);
+                               target_attach->attachment_save_status = 1;
+
+                               if(!emstorage_update_attachment(target_attach, false, &err)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_update_attachment failed [%d]", err);
+                                       goto FINISH_OFF;
+                               }
+                               memset(output_file_path, 0, MAX_PATH);
+                               memset(output_file_name, 0, MAX_PATH);
+                               break;
+                       }
+               }
+       }
+
+FINISH_OFF:
+       if(original_mail_attachment_array)
+               emstorage_free_attachment(&original_mail_attachment_array, original_mail_attachment_count, NULL);
+       if(target_mail_attachment_array)
+               emstorage_free_attachment(&target_mail_attachment_array, target_mail_attachment_count, NULL);
+
+
+       EM_DEBUG_FUNC_END("err[%d]", err);
+       return err;
+}
+
+/*  send a mail */
+INTERNAL_FUNC int emcore_send_mail_with_downloading_attachment_of_original_mail(int input_mail_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d]", input_mail_id);
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       int attachment_count = 0;
+       email_mail_data_t *mail_to_be_sent = NULL;
+       email_mail_data_t *original_mail = NULL;
+       email_attachment_data_t *attachment_array = NULL;
+
+       /* Get mail data */
+       if((err = emcore_get_mail_data(input_mail_id, &mail_to_be_sent)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_data failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(mail_to_be_sent->reference_mail_id <= 0) {
+               err = EMAIL_ERROR_INVALID_REFERENCE_MAIL;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_REFERENCE_MAIL");
+               goto FINISH_OFF;
+       }
+
+       /* Get original mail data */
+       if((err = emcore_get_mail_data(mail_to_be_sent->reference_mail_id, &original_mail)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_data failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Check necessity of download */
+       if((err = emcore_get_attachment_data_list(original_mail->mail_id, &attachment_array, &attachment_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_get_attachment_data_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* If need be, download attachments */
+       for(i = 0; i < attachment_count; i++) {
+               if(attachment_array[i].save_status != 1) {
+                       if(!emcore_download_attachment(original_mail->account_id, original_mail->mail_id, i + 1, &err)) {
+                               EM_DEBUG_EXCEPTION("emcore_download_attachment failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       /* Copy attachment to the mail to be sent */
+       if((err = emcore_copy_attachment_from_original_mail(original_mail->mail_id, mail_to_be_sent->mail_id)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_download_attachment failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Send the mail */
+       if(!emcore_send_mail(mail_to_be_sent->account_id, mail_to_be_sent->mailbox_id, mail_to_be_sent->mail_id, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_send_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+FINISH_OFF:
+
+       if(attachment_array)
+               emcore_free_attachment_data(&attachment_array, attachment_count, NULL);
+
+       if(mail_to_be_sent) {
+               emcore_free_mail_data(mail_to_be_sent);
+               EM_SAFE_FREE(mail_to_be_sent);
+       }
+
+       if(original_mail) {
+               emcore_free_mail_data(original_mail);
+               EM_SAFE_FREE(original_mail);
+       }
+
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-core/email-core-sound.c b/email-core/email-core-sound.c
new file mode 100755 (executable)
index 0000000..b57042a
--- /dev/null
@@ -0,0 +1,837 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <stdlib.h>
+#include <pthread.h>
+
+#include "email-debug-log.h"
+#include "email-storage.h"
+#include "email-core-utils.h"
+#include "email-core-mailbox.h"
+#include "email-core-sound.h"
+#include "email-utilities.h"
+
+#define TIMER 30000   // 30 seconds
+#define HAPTIC_TEST_ITERATION 1
+
+static MMHandleType email_mmhandle = 0;
+static alarm_id_t email_alarm_id = 0;
+static int setting_noti_status = 0;
+
+static char *filename;
+alarm_entry_t *alarm_info = NULL;
+
+static pthread_mutex_t sound_mutex = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t sound_condition = PTHREAD_COND_INITIALIZER;
+static pthread_mutex_t mmhandle_mutex = PTHREAD_MUTEX_INITIALIZER;
+static thread_t g_alert_thread;
+
+void  emcore_set_repetition_alarm(int repetition);
+int   emcore_sound_mp_player_stop();
+bool  emcore_sound_mp_player_destory();
+void *start_alert_thread(void *arg);
+
+bool emcore_set_mp_filepath(const char *key)
+{
+       filename = vconf_get_str(key);
+       if (filename == NULL)
+               return false;
+
+       /* initialize the ringtone path */
+       if (vconf_set_str(VCONF_VIP_NOTI_RINGTONE_PATH, filename) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_set_str failed");
+               return false;
+       }
+
+       return true;
+}
+
+int emcore_alert_sound_init()
+{
+       int ret = MM_ERROR_NONE;
+       if ((ret = mm_session_init(MM_SESSION_TYPE_NOTIFY)) != MM_ERROR_NONE) 
+               EM_DEBUG_EXCEPTION("mm_session_int failed");
+
+       return ret;
+}
+
+int emcore_alert_alarm_init()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = ALARMMGR_RESULT_SUCCESS;
+       
+       ret = alarmmgr_init("email-service-0");
+       if (ret != ALARMMGR_RESULT_SUCCESS) 
+               EM_DEBUG_EXCEPTION("alarmmgr_init failed : [%d]", ret);
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emcore_alert_sound_filepath_init()
+{
+       filename = (char  *)em_malloc(MAX_PATH);
+       if (filename == NULL) {
+               EM_DEBUG_EXCEPTION("Memory malloc error");      
+               return false;
+       }
+
+       if (!emcore_set_mp_filepath(VCONFKEY_SETAPPL_NOTI_EMAIL_RINGTONE_PATH_STR)) {
+               /* TODO : Add code to set default ringtone path */
+               EM_DEBUG_EXCEPTION("emcore_set_mp_filepath failed.");
+               return false;
+       }
+
+       return true;
+}
+
+void emcore_global_noti_key_changed_cb(keynode_t *key_node, void *data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = 0;
+
+       switch (vconf_keynode_get_type(key_node)) {
+       case VCONF_TYPE_INT:
+               ret = alarmmgr_remove_alarm(email_alarm_id);
+               if (ret != ALARMMGR_RESULT_SUCCESS) {
+                       EM_DEBUG_EXCEPTION("delete of alarm id failed");
+               }
+               emcore_set_repetition_alarm(vconf_keynode_get_int(key_node));
+               break;
+       case VCONF_TYPE_STRING:
+               filename = vconf_keynode_get_str(key_node);
+               break;
+       default:
+               EM_DEBUG_EXCEPTION("Invalid key type");
+               break;
+       }
+
+       EM_DEBUG_FUNC_END();
+}
+
+void emcore_email_noti_key_changed_cb(keynode_t *key_node, void *data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = 0;
+
+       switch (vconf_keynode_get_type(key_node)) {
+       case VCONF_TYPE_INT:
+               ret = alarmmgr_remove_alarm(email_alarm_id);
+               if (ret != ALARMMGR_RESULT_SUCCESS) {
+                       EM_DEBUG_EXCEPTION("delete of alarm id failed");
+               }
+               emcore_set_repetition_alarm(vconf_keynode_get_int(key_node));
+               break;
+       case VCONF_TYPE_STRING:
+               filename = vconf_keynode_get_str(key_node);
+               break;
+       default:
+               EM_DEBUG_EXCEPTION("Invalid key type");
+               break;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+bool emcore_update_noti_status()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ticker_noti = 0;
+
+       /* Get the priority noti ticker */
+       if (vconf_get_bool(VCONF_VIP_NOTI_NOTIFICATION_TICKER, &ticker_noti) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+               return false;
+       }
+
+       EM_DEBUG_LOG("ticker_noti of vip : [%d]", ticker_noti);
+
+       if (ticker_noti <= 0) {
+               /* Get the Global noti ticker */
+               if (vconf_get_bool(VCONFKEY_SETAPPL_STATE_TICKER_NOTI_EMAIL_BOOL, &ticker_noti) != 0) {
+                               EM_DEBUG_EXCEPTION("Not display the noti of email");
+                               return false;
+               }
+
+               EM_DEBUG_LOG("ticker_noti of global : [%d]", ticker_noti);
+
+               if (!ticker_noti) {
+                       EM_DEBUG_LOG("Not use the notification");
+                       setting_noti_status = SETTING_NOTI_STATUS_OFF;
+                       return true;
+               }
+
+               setting_noti_status = SETTING_NOTI_STATUS_GLOBAL;
+       } else {
+               setting_noti_status = SETTING_NOTI_STATUS_EMAIL;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+void emcore_noti_status_changed_cb(keynode_t *key_node, void *data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (!emcore_update_noti_status()) {
+               EM_DEBUG_EXCEPTION("emcore_update_noti_status failed");
+               return;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+bool emcore_noti_init(void *data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       struct appdata *ap = data;
+
+       if (!emcore_update_noti_status()) {
+               EM_DEBUG_EXCEPTION("emcore_update_noti_status failed");
+               return false;
+       }
+
+       /* Noti callback registration */
+       if (vconf_notify_key_changed(VCONFKEY_SETAPPL_NOTI_EMAIL_ALERT_REP_TYPE_INT, emcore_global_noti_key_changed_cb, ap) < 0) {
+               EM_DEBUG_EXCEPTION("Register failed : alert type");
+       }
+
+       if (vconf_notify_key_changed(VCONFKEY_SETAPPL_NOTI_EMAIL_RINGTONE_PATH_STR, emcore_global_noti_key_changed_cb, ap) < 0) {
+               EM_DEBUG_EXCEPTION("Register failed : Ringtone path");
+       }
+
+       if (vconf_notify_key_changed(VCONF_VIP_NOTI_REP_TYPE, emcore_email_noti_key_changed_cb, ap) < 0) {
+               EM_DEBUG_EXCEPTION("Register failed : alert type");
+       }
+
+       if (vconf_notify_key_changed(VCONF_VIP_NOTI_RINGTONE_PATH, emcore_email_noti_key_changed_cb, ap) < 0) {
+               EM_DEBUG_EXCEPTION("Register failed : Ringtone path");
+       }
+
+       if (vconf_notify_key_changed(VCONF_VIP_NOTI_NOTIFICATION_TICKER, emcore_noti_status_changed_cb, ap) < 0) {
+               EM_DEBUG_EXCEPTION("Register failed : Ringtone path");
+       }
+
+       if (vconf_notify_key_changed(VCONFKEY_SETAPPL_STATE_TICKER_NOTI_EMAIL_BOOL, emcore_noti_status_changed_cb, ap) < 0) {
+               EM_DEBUG_EXCEPTION("Register failed : Ringtone path");
+       }
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_alert_init()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = 0;
+       
+       if (!emcore_alert_sound_filepath_init()) {
+               EM_DEBUG_EXCEPTION("emcore_alert_sound_filepath_init failed");
+               return false;
+       }
+
+       if ((err = emcore_alert_sound_init()) != MM_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_alert_sound_init failed : [%d]", err);
+               return false;
+       }
+
+       if ((err = emcore_alert_alarm_init()) != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("emcore_alert_alarm_init failed : [%d]", err);
+               return false;           
+       }
+
+       if (!emcore_noti_init(NULL)) {
+               EM_DEBUG_EXCEPTION("emcore_noti_init failed");
+               return false;           
+       }
+
+       EM_DEBUG_FUNC_END();    
+       return true;
+}
+
+int emcore_mp_player_state_cb(int message, void *param, void *user_param)
+{
+       switch (message)
+       {
+               case MM_MESSAGE_ERROR:
+                       EM_DEBUG_LOG("Error is happened.");
+                       if (email_mmhandle) {
+                               emcore_sound_mp_player_destory();
+                       }
+                       break;
+               case MM_MESSAGE_BEGIN_OF_STREAM:
+                       EM_DEBUG_LOG("Play is started.");
+                       break;
+               case MM_MESSAGE_END_OF_STREAM:
+                       EM_DEBUG_LOG("End of stream.");
+                       ENTER_CRITICAL_SECTION(mmhandle_mutex);
+                       if (email_mmhandle)
+                       {                       
+                               emcore_sound_mp_player_stop();
+                               emcore_sound_mp_player_destory();
+                       }
+                       LEAVE_CRITICAL_SECTION(mmhandle_mutex);
+                       break;
+               default: 
+                       EM_DEBUG_LOG("Message = %d", message);
+                       break;
+       }
+       return 1;
+}
+
+bool emcore_sound_mp_player_create() 
+{      
+       EM_DEBUG_FUNC_BEGIN();
+       int err = 0;
+       
+       if (email_mmhandle) {
+               EM_DEBUG_LOG("already create the handle");
+               return false;
+       }
+
+       if ((err = mm_player_create(&email_mmhandle)) != MM_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("mm_player create fail [%d]", err);
+               return false;
+       }       
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+bool emcore_alarm_create() 
+{      
+       EM_DEBUG_FUNC_BEGIN();
+
+       alarm_info = alarmmgr_create_alarm();
+
+       if (alarm_info == NULL) {
+               EM_DEBUG_EXCEPTION("alarm create failed");
+               return false;
+       }               
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+bool emcore_alarm_destory()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret;
+       ret = alarmmgr_free_alarm(alarm_info);
+
+       if (ret != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("alarm free failed");
+               return false;
+       }               
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+bool emcore_alert_create()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       /* Create the alarm handle */
+       if (!emcore_alarm_create()) {
+               EM_DEBUG_EXCEPTION("emcore_alarm_create failed.");
+               return false;
+       }
+#if 0  
+       /* Set the music file in alert */
+       if (!emcore_set_mp_filepath(VCONFKEY_SETAPPL_NOTI_EMAIL_RINGTONE_PATH_STR)) {
+               /* TODO : Add code to set default ringtone path */
+               EM_DEBUG_EXCEPTION("emcore_set_mp_filepath failed.");
+               return false;
+       }
+#endif 
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+bool emcore_alert_destory()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = 0;
+
+       /* Destroy the music player handle */
+       if (!emcore_sound_mp_player_destory()) {
+               EM_DEBUG_EXCEPTION("emcore_sound_mp_player_destory fail");
+               return false;
+       }                       
+
+       /* Destroy the alarm handle */
+       ret = alarmmgr_free_alarm(alarm_info);
+       if (ret != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("alarmmgr_free_alarm fail");
+               return false;
+       }                       
+       
+       /* Set the music file in alert */
+       EM_SAFE_FREE(filename);
+       
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+gboolean mp_player_timeout_cb(void *data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       ENTER_CRITICAL_SECTION(mmhandle_mutex); 
+       if (email_mmhandle)
+       {                       
+               emcore_sound_mp_player_stop();
+               emcore_sound_mp_player_destory();
+       }
+       LEAVE_CRITICAL_SECTION(mmhandle_mutex);
+       
+       EM_DEBUG_FUNC_END();
+       return false;
+}
+
+bool emcore_vibration_start()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = false;
+       int error = FEEDBACK_ERROR_NONE;
+       int call_state = 0;
+
+       error = vconf_get_int(VCONFKEY_CALL_STATE, &call_state);
+       if (error == -1) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+               goto FINISH_OFF;
+       }
+
+       error = feedback_initialize();
+       if (error != FEEDBACK_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("feedback_initialize failed : [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       if (call_state > VCONFKEY_CALL_OFF && call_state < VCONFKEY_CALL_STATE_MAX) {   
+               error = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_EMAIL_ON_CALL);
+       } else {
+               error = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_EMAIL);
+       }
+
+       if (error != FEEDBACK_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("feedback_play failed : [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       error = feedback_deinitialize();
+       if (error != FEEDBACK_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("feedback_deinitialize failed : [%d]", error);
+       }
+       
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emcore_sound_mp_player_start(char *filepath)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = MM_ERROR_NONE;
+
+/*     
+       int volume = -1;
+
+
+       if ((err = vconf_get_int(VCONFKEY_SETAPPL_NOTI_SOUND_VOLUME_INT, &volume)) == -1)
+       {
+               EM_DEBUG_LOG("vconf_get_int failed \n");
+               return err;
+       }
+*/
+       mm_player_set_message_callback(email_mmhandle, emcore_mp_player_state_cb, (void  *)email_mmhandle);
+
+       EM_DEBUG_LOG("Before mm_player_set_attribute filepath = %s", filepath);
+       if ((err = mm_player_set_attribute(email_mmhandle, NULL, "sound_volume_type", MM_SOUND_VOLUME_TYPE_NOTIFICATION, "profile_uri", filepath, EM_SAFE_STRLEN(filepath), NULL)) != MM_ERROR_NONE)
+       {
+               EM_DEBUG_EXCEPTION("mm_player_set_attribute faile [ %d ] ", err);
+               return err;
+       }
+
+       EM_DEBUG_LOG("After mm_player_set_attribute");  
+
+       if ((err = mm_player_realize(email_mmhandle)) != MM_ERROR_NONE)
+       {
+               EM_DEBUG_EXCEPTION("mm_player_realize fail [%d]", err);
+               return err;
+       }
+
+       if ((err = mm_player_start(email_mmhandle)) != MM_ERROR_NONE)
+       {
+               EM_DEBUG_EXCEPTION("mm_player_start fail [%d]", err);
+               return err;
+       }
+
+       if ((err = g_timeout_add(TIMER, (GSourceFunc)mp_player_timeout_cb, NULL) <= 0))
+       {
+               EM_DEBUG_EXCEPTION("g_timeout_add - Failed to start timer");
+               return err;             
+       }
+       
+       EM_DEBUG_FUNC_END();
+       return err;
+}
+
+int emcore_sound_mp_player_stop()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = MM_ERROR_NONE;
+
+       if ((err = mm_player_stop(email_mmhandle)) != MM_ERROR_NONE)
+       {
+               EM_DEBUG_EXCEPTION("mm_player_stop fail [%d]", err);
+               return err;
+       }
+
+       if ((err = mm_player_unrealize(email_mmhandle)) != MM_ERROR_NONE)
+       {
+               EM_DEBUG_EXCEPTION("mm_player_unrealize [%d]", err);
+               return err;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return err;
+}
+
+bool emcore_sound_mp_player_destory()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = MM_ERROR_NONE;
+
+       if ((err = mm_player_destroy(email_mmhandle)) != MM_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("mm_player_destory [%d]", err);
+               return false;
+       }
+
+       email_mmhandle = 0;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}      
+
+int get_vconf_data(int key, int *return_value)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = -1, value = 0;
+       
+       switch (key)
+       {
+               case EMAIL_SOUND_STATUS:
+                       err = vconf_get_bool(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, &value);
+                       EM_DEBUG_LOG("EMAIL_SOUND_STATUS[%d]", value);
+                       break;
+               case EMAIL_VIBE_STATUS:
+                       err = vconf_get_bool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, &value);
+                       EM_DEBUG_LOG("EMAIL_VIBRATION_STATUS[%d]", value);
+                       break;
+               case EMAIL_ALERT_REP_TYPE:
+                       err = vconf_get_int(VCONFKEY_SETAPPL_NOTI_EMAIL_ALERT_REP_TYPE_INT, &value);
+                       EM_DEBUG_LOG("EMAIL_ALERT_REP_TYPE[%d]", value);
+                       break;
+               case EMAIL_ALERT_VOLUME:
+                       err = vconf_get_int(VCONFKEY_SETAPPL_NOTI_SOUND_VOLUME_INT, &value);
+                       EM_DEBUG_LOG("EMAIL_ALERT_VOLUME[%d]", value);
+                       break;
+               case EMAIL_ALERT_VIBE_STENGTH:
+                       err = vconf_get_int(VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT, &value);
+                       EM_DEBUG_LOG("EMAIL_ALERT_VIBE_STENGTH[%d]", value);
+                       break;
+               default: 
+               {
+                       EM_DEBUG_LOG("Uuknown request\n");
+                       return false;                   
+               }
+       }
+       
+       if (err == -1)
+       {
+               EM_DEBUG_LOG("Vconf_get_int failed\n");
+               return false;
+       }
+
+       *return_value = value;
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_get_alert_type()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int sound_status = 0, vibe_status = 0;
+       int err;
+       int alert_type = -1;
+
+       if (!(err = get_vconf_data(EMAIL_SOUND_STATUS, &sound_status))) {
+               EM_DEBUG_EXCEPTION("Don't get sound status");
+               return err;
+       }
+
+       if (!(err = get_vconf_data(EMAIL_VIBE_STATUS, &vibe_status)))
+       {
+               EM_DEBUG_EXCEPTION("Don't get vibration status");
+               return err;
+       }
+
+       if (sound_status && vibe_status)
+               alert_type = EMAIL_ALERT_TYPE_MELODY_AND_VIB;
+       else if (sound_status)
+               alert_type = EMAIL_ALERT_TYPE_MELODY;
+       else if (vibe_status)
+               alert_type = EMAIL_ALERT_TYPE_VIB;
+       else
+               alert_type = EMAIL_ALERT_TYPE_MUTE;
+
+       return alert_type;
+}
+
+
+INTERNAL_FUNC int emcore_start_thread_for_alerting_new_mails(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int thread_error;
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+       
+       if (g_alert_thread)
+       {
+               EM_DEBUG_EXCEPTION("Alert service is already running...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_UNKNOWN;
+               
+               return 1;
+       }
+       
+       THREAD_CREATE(g_alert_thread, start_alert_thread, NULL, thread_error);
+       if (thread_error != 0)
+       {
+               EM_DEBUG_EXCEPTION("Cannot create alert thread");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
+
+               return -1;
+       }
+               
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+       return 0;
+}
+
+int emcore_alarm_timeout_cb(int timer_id, void *user_parm)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       int total_unread_count = 0;
+       int total_mail_count = 0;
+       email_mailbox_t mailbox;
+
+       memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+
+       mailbox.account_id = ALL_ACCOUNT;
+       mailbox.mailbox_name = NULL;
+
+       if (!emcore_get_mail_count(&mailbox, &total_mail_count, &total_unread_count, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_count failed - %d\n", err);
+               return false;
+       }
+
+       EM_DEBUG_LOG(">>>> total_unread_count : [%d]\n", total_unread_count);
+       
+       if (total_unread_count) {
+               emcore_start_alert();
+       }
+
+       EM_DEBUG_FUNC_END();    
+       return true;
+}
+
+bool set_alarm(int repetition_time)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = 0;
+       alarm_date_t alarm_date;
+       time_t current_time;
+       struct tm current_tm;
+
+       time(&current_time);
+       localtime_r(&current_time, &current_tm);
+       
+       alarm_date.year = 0;
+       alarm_date.month = 0;
+       alarm_date.day = 0;
+
+       EM_DEBUG_LOG("Current time : [%d]-[%d]-[%d]", current_tm.tm_hour, current_tm.tm_min, current_tm.tm_sec);
+       
+       if (current_tm.tm_min + repetition_time < 60) {
+               alarm_date.hour = current_tm.tm_hour;
+               alarm_date.min = current_tm.tm_min + repetition_time;
+       } else {
+               if (current_tm.tm_hour < 12) {
+                       alarm_date.hour = current_tm.tm_hour + 1;
+               } else {
+                       alarm_date.hour = (current_tm.tm_hour + 1) % 12;
+               }
+
+               alarm_date.min = (current_tm.tm_min + repetition_time) % 60;
+       }
+
+       alarm_date.sec = current_tm.tm_sec;
+       
+       alarmmgr_set_time(alarm_info, alarm_date);
+       alarmmgr_set_repeat_mode(alarm_info, ALARM_REPEAT_MODE_ONCE, 0);
+       alarmmgr_set_type(alarm_info, ALARM_TYPE_VOLATILE);
+       alarmmgr_add_alarm_with_localtime(alarm_info, NULL, &email_alarm_id);
+
+       ret = alarmmgr_set_cb(emcore_alarm_timeout_cb, NULL);
+
+       if (ret != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("Failed : alarmmgr_set_cb() -> error[%d]", ret);
+               return false;
+       }
+
+       EM_DEBUG_LOG("Alarm time : [%d]-[%d]-[%d]-[%d]-[%d]-[%d]", alarm_date.year, alarm_date.month, alarm_date.day, alarm_date.hour, alarm_date.min, alarm_date.sec);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+void emcore_set_repetition_alarm(int repetition)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int repetition_time = 0;
+       
+       switch (repetition) {
+       case EMAIL_GCONF_VALUE_REPEAT_NONE:
+               repetition_time = 0;
+               break;
+       case EMAIL_GCONF_VALUE_REPEAT_2MINS:
+               repetition_time = 2;
+               break;
+       case EMAIL_GCONF_VALUE_REPEAT_5MINS:
+               repetition_time = 5;
+               break;
+       case EMAIL_GCONF_VALUE_REPEAT_10MINS:           
+               repetition_time = 10;
+               break;
+       default:
+               EM_DEBUG_EXCEPTION("Invalid repetition time");
+               return;
+       }
+
+       EM_DEBUG_LOG("repetition time is %d", repetition_time);
+
+       if (repetition_time > 0) {
+               set_alarm(repetition_time);
+       } 
+
+       EM_DEBUG_FUNC_END();
+}
+
+void *start_alert_thread(void *arg)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int err = 0;
+       int repetition = 0;
+
+       if (!emcore_alert_init())
+       {
+               EM_DEBUG_EXCEPTION("Error : emcore_alert_init failed");
+               return 0;
+       }
+
+       while (1) {
+               if (!emcore_alert_create()) {
+                       EM_DEBUG_EXCEPTION("Error : emcore_alert_create failed");
+                       return 0;
+               }
+
+               err = get_vconf_data(EMAIL_ALERT_REP_TYPE, &repetition);
+               emcore_set_repetition_alarm(repetition);
+
+               ENTER_CRITICAL_SECTION(sound_mutex);
+               SLEEP_CONDITION_VARIABLE(sound_condition , sound_mutex);
+
+               switch (emcore_get_alert_type())
+               {
+                       case EMAIL_ALERT_TYPE_MELODY:
+                               if (!emcore_sound_mp_player_create()) {
+                                       EM_DEBUG_LOG("emcore_sound_mp_player_create failed : [%d]", email_mmhandle);
+                                       break;
+                               }
+                               emcore_sound_mp_player_start(filename);
+                               break;
+                       case EMAIL_ALERT_TYPE_VIB:
+                               emcore_vibration_start();
+                               break;
+                       case EMAIL_ALERT_TYPE_MELODY_AND_VIB:
+                               emcore_vibration_start();
+                               if (!emcore_sound_mp_player_create()) {
+                                       EM_DEBUG_LOG("emcore_sound_mp_player_create failed : [%d]", email_mmhandle);
+                                       break;
+                               }
+                               emcore_sound_mp_player_start(filename);
+                               break;
+                       case EMAIL_ALERT_TYPE_MUTE:
+                               EM_DEBUG_LOG("Alert type is mute!!");
+                               break;
+                       default: 
+                               EM_DEBUG_EXCEPTION("alert type is strange");
+                               emcore_alert_destory();
+                               break;
+               }
+               LEAVE_CRITICAL_SECTION(sound_mutex);
+               EM_DEBUG_LOG("Start FINISH");
+               emcore_alarm_destory();
+       }
+
+       EM_DEBUG_FUNC_END();
+       return 0;
+}      
+
+INTERNAL_FUNC void emcore_start_alert()
+{
+       EM_DEBUG_FUNC_BEGIN("setting_noti_status : [%d]", setting_noti_status);
+
+       if (setting_noti_status == SETTING_NOTI_STATUS_OFF)
+               return;
+
+       ENTER_CRITICAL_SECTION(sound_mutex);
+       WAKE_CONDITION_VARIABLE(sound_condition);
+       LEAVE_CRITICAL_SECTION(sound_mutex);
+}
diff --git a/email-core/email-core-task-manager.c b/email-core/email-core-task-manager.c
new file mode 100755 (executable)
index 0000000..14cf361
--- /dev/null
@@ -0,0 +1,629 @@
+/*\r
+*  email-service\r
+*\r
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
+*\r
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
+*\r
+* Licensed under the Apache License, Version 2.0 (the "License");\r
+* you may not use this file except in compliance with the License.\r
+* You may obtain a copy of the License at\r
+*\r
+* http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*\r
+*/\r
+\r
+/*\r
+ * email-core-task-manager.c\r
+ *\r
+ *  Created on: 2012. 11. 1.\r
+ *      Author: kyuho.jo@samsung.com\r
+ */\r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <pthread.h>\r
+#include <dbus/dbus.h>\r
+\r
+#include "email-internal-types.h"\r
+#include "email-utilities.h"\r
+#include "email-core-tasks.h"\r
+#include "email-core-task-manager.h"\r
+#include "email-core-signal.h"\r
+#include "email-core-global.h"\r
+#include "email-core-utils.h"\r
+#include "email-debug-log.h"\r
+\r
+/* TODO : implement a function for removing a task from task pool */\r
+/* TODO : after fetching a task from DB, update status of the task. */\r
+\r
+\r
+#define REGISTER_TASK_BINDER(TASK_NAME) emcore_register_task_handler(TASK_NAME, task_handler_##TASK_NAME, email_encode_task_parameter_##TASK_NAME, email_decode_task_parameter_##TASK_NAME)\r
+\r
+/*- variables - begin --------------------------------------------------------*/\r
+static pthread_cond_t  _task_available_signal   = PTHREAD_COND_INITIALIZER;\r
+static pthread_mutex_t _task_available_lock     = PTHREAD_MUTEX_INITIALIZER;\r
+static pthread_mutex_t _task_manager_loop_lock  = PTHREAD_MUTEX_INITIALIZER;\r
+static pthread_mutex_t _active_task_pool_lock   = PTHREAD_MUTEX_INITIALIZER;\r
+\r
+static email_active_task_t _active_task_pool[MAX_ACTIVE_TASK];\r
+static thread_t            _thread_task_manager_loop;\r
+static int                 _task_manager_loop_availability = 1;\r
+/*- variables - end ----------------------------------------------------------*/\r
+static int emcore_insert_task_to_active_task_pool(int input_task_slot_index, int input_task_id, email_task_type_t input_task_type, thread_t input_thread_id);\r
+static int emcore_remove_task_from_active_task_pool(int input_task_id);\r
+static int emcore_find_available_slot_in_active_task_pool(int *result_index);\r
+static int emcore_update_task_status_on_task_table(int input_task_id, email_task_status_type_t task_status);\r
+static int emcore_get_task_handler_reference(email_task_type_t input_task_type, email_task_handler_t **output_task_handler);\r
+\r
+/*- task handlers helpers - begin --------------------------------------------*/\r
+static int emcore_initialize_task_handler(email_task_t *input_task)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task [%p]", input_task);\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       if(input_task == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       /* insert task to _active_task_pool */\r
+       emcore_insert_task_to_active_task_pool(input_task->active_task_id\r
+                       , input_task->task_id\r
+                       , input_task->task_type\r
+                       , THREAD_SELF());\r
+\r
+       /* send notification for 'task start */\r
+       if( (err = emcore_send_task_status_signal(input_task->task_type, input_task->task_id, EMAIL_TASK_STATUS_STARTED, EMAIL_ERROR_NONE, 0)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emcore_send_task_status_signal failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+FINISH_OFF:\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+static int emcore_finalize_task_handler(email_task_t *input_task, int input_error_code)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task [%p] input_error_code [%d]",input_task ,input_error_code);\r
+       int err = EMAIL_ERROR_NONE;\r
+       email_task_status_type_t task_status = EMAIL_TASK_STATUS_FINISHED;\r
+\r
+       if(input_task == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       if(input_error_code != EMAIL_ERROR_NONE) {\r
+               task_status = EMAIL_TASK_STATUS_FAILED;\r
+       }\r
+\r
+       /* remove task from task table */\r
+       if( (err = emcore_remove_task_from_task_table(input_task->task_id)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emcore_remove_task_from_active_task_pool failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       /* remove task id from active task id array */\r
+       if( (err = emcore_remove_task_from_active_task_pool(input_task->task_id)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emcore_remove_task_from_active_task_pool failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       /* send signal for 'task finish or failure */\r
+       if( (err = emcore_send_task_status_signal(input_task->task_type, input_task->task_id, task_status, input_error_code, 0)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emcore_send_task_status_signal failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       ENTER_CRITICAL_SECTION(_task_available_lock);\r
+       WAKE_CONDITION_VARIABLE(_task_available_signal);\r
+       LEAVE_CRITICAL_SECTION(_task_available_lock);\r
+\r
+FINISH_OFF:\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+void* emcore_default_task_handler(void *intput_param)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("intput_param [%p]", intput_param);\r
+       int err = EMAIL_ERROR_NONE;\r
+       email_task_t *task = intput_param;\r
+       email_task_handler_t *task_handler = NULL;\r
+       void *decoded_task_parameter = NULL;\r
+\r
+       if((err = emcore_initialize_task_handler(task)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emcore_initialize_task_handler failed. [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       /* create a thread to do this task */\r
+       if((err = emcore_get_task_handler_reference(task->task_type, &task_handler)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_LOG("emcore_get_task_handler_reference returns [%d]", err);\r
+       }\r
+       else {\r
+               /* Decode parameter */\r
+               emcore_decode_task_parameter(task->task_type, task->task_parameter, task->task_parameter_length, &decoded_task_parameter);\r
+               task_handler->task_handler_function(decoded_task_parameter);\r
+       }\r
+\r
+FINISH_OFF:\r
+       emcore_finalize_task_handler(task, err);\r
+\r
+       if(task) {\r
+               EM_SAFE_FREE(task->task_parameter);\r
+               EM_SAFE_FREE(task);\r
+       }\r
+\r
+       EM_SAFE_FREE(decoded_task_parameter);\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return NULL;\r
+}\r
+/*- task handlers helpers - end   --------------------------------------------*/\r
+\r
+int                   _task_handler_array_size;\r
+email_task_handler_t **_task_handler_array;\r
+\r
+static int emcore_register_task_handler(email_task_type_t input_task_type, void* (*input_task_handler)(void *), int (*input_task_parameter_encoder)(void*,char**,int*), int (*input_task_parameter_decoder)(char*,int,void**))\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_type [%d] input_task_handler [%p] input_task_parameter_encoder [%p] input_task_parameter_decoder [%p]", input_task_type, input_task_handler, input_task_parameter_encoder, input_task_parameter_decoder);\r
+       int err = EMAIL_ERROR_NONE;\r
+       email_task_handler_t *new_task_handler = NULL;\r
+\r
+       new_task_handler = malloc(sizeof(email_task_handler_t));\r
+\r
+       if (new_task_handler == NULL) {\r
+               err = EMAIL_ERROR_OUT_OF_MEMORY;\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       new_task_handler->task_type              = input_task_type;\r
+       new_task_handler->task_handler_function  = input_task_handler;\r
+       new_task_handler->task_parameter_encoder = input_task_parameter_encoder;\r
+       new_task_handler->task_parameter_decoder = input_task_parameter_decoder;\r
+\r
+       _task_handler_array_size++;\r
+\r
+       if (_task_handler_array) {\r
+               _task_handler_array = realloc(_task_handler_array, sizeof(email_task_handler_t*) * _task_handler_array_size);\r
+       }\r
+       else {\r
+               _task_handler_array = malloc(sizeof(email_task_handler_t*) * _task_handler_array_size);\r
+       }\r
+\r
+       if (_task_handler_array == NULL) {\r
+               err = EMAIL_ERROR_OUT_OF_MEMORY;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       _task_handler_array[_task_handler_array_size - 1] = new_task_handler;\r
+\r
+FINISH_OFF:\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+\r
+INTERNAL_FUNC int emcore_init_task_handler_array()\r
+{\r
+       EM_DEBUG_FUNC_BEGIN();\r
+\r
+       if (_task_handler_array == NULL) {\r
+               _task_handler_array      = NULL;\r
+               _task_handler_array_size = 0;\r
+\r
+               REGISTER_TASK_BINDER(EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT);\r
+               REGISTER_TASK_BINDER(EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX);\r
+               REGISTER_TASK_BINDER(EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL);\r
+       }\r
+\r
+       EM_DEBUG_FUNC_END();\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_free_task_handler_array()\r
+{\r
+       EM_DEBUG_FUNC_BEGIN();\r
+\r
+       int i = 0;\r
+\r
+       for(i = 0; i < _task_handler_array_size; i++) {\r
+               free(_task_handler_array[i]);\r
+       }\r
+\r
+       free(_task_handler_array);\r
+       _task_handler_array      = NULL;\r
+       _task_handler_array_size = 0;\r
+\r
+       EM_DEBUG_FUNC_END();\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+static int emcore_get_task_handler_reference(email_task_type_t input_task_type, email_task_handler_t **output_task_handler)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_type [%d] output_task_handler [%p]", input_task_type, output_task_handler);\r
+       int i = 0;\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       if (output_task_handler == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       *output_task_handler = NULL;\r
+       for (i = 0; i < _task_handler_array_size; i++) {\r
+               if (_task_handler_array[i]->task_type == input_task_type) {\r
+                       *output_task_handler = _task_handler_array[i];\r
+                       break;\r
+               }\r
+       }\r
+\r
+       if (*output_task_handler == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_TASK_BINDER_NOT_FOUND");\r
+               err = EMAIL_ERROR_TASK_BINDER_NOT_FOUND;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+FINISH_OFF:\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_encode_task_parameter(email_task_type_t input_task_type, void *input_task_parameter_struct, char **output_byte_stream, int *output_stream_size)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_type [%d] input_task_parameter_struct [%p] output_byte_stream [%p] output_stream_size [%p]", input_task_type, input_task_parameter_struct, output_byte_stream, output_stream_size);\r
+       int err = EMAIL_ERROR_NONE;\r
+       email_task_handler_t *task_handler = NULL;\r
+       int (*task_parameter_encoder)(void*, char**, int*);\r
+\r
+       if (input_task_parameter_struct == NULL || output_byte_stream == NULL || output_stream_size == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       if ((err = emcore_get_task_handler_reference(input_task_type, &task_handler)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emcore_get_task_handler_reference failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       task_parameter_encoder = task_handler->task_parameter_encoder;\r
+\r
+       if ((err = task_parameter_encoder(input_task_parameter_struct, output_byte_stream, output_stream_size)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("task_parameter_encoder failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+FINISH_OFF:\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_decode_task_parameter(email_task_type_t input_task_type, char *input_byte_stream, int input_stream_size, void **output_task_parameter_struct)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_type [%d] input_byte_stream [%p] input_stream_size [%d] output_task_parameter_struct [%p]", input_task_type, input_byte_stream, input_stream_size, output_task_parameter_struct);\r
+       int err = EMAIL_ERROR_NONE;\r
+       email_task_handler_t *task_handler = NULL;\r
+       int (*task_parameter_decoder)(char*, int, void**);\r
+\r
+       if (input_byte_stream == NULL || output_task_parameter_struct == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       if ((err = emcore_get_task_handler_reference(input_task_type, &task_handler)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emcore_get_task_handler_reference failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       task_parameter_decoder = task_handler->task_parameter_decoder;\r
+\r
+       if ((err = task_parameter_decoder(input_byte_stream, input_stream_size, output_task_parameter_struct)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("task_parameter_decoder failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+FINISH_OFF:\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+int emcore_fetch_task_from_task_pool(email_task_t **output_task)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("output_task [%p]", output_task);\r
+       int err = EMAIL_ERROR_NONE;\r
+       int output_task_count;\r
+\r
+       if((err = emstorage_query_task("WHERE task_status == 1", " ORDER BY date_time ASC, task_priority ASC LIMIT 0, 1", output_task, &output_task_count)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emstorage_query_task failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+FINISH_OFF:\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+\r
+/*-Task manager loop - begin -------------------------------------------------------------*/\r
+\r
+\r
+static int emcore_insert_task_to_active_task_pool(int input_task_slot_index, int input_task_id, email_task_type_t input_task_type, thread_t input_thread_id)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_slot_index [%d] input_task_id [%d] input_task_type [%d] input_thread_id [%d]", input_task_slot_index, input_task_id, input_task_type, input_thread_id);\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       ENTER_CRITICAL_SECTION(_active_task_pool_lock);\r
+       _active_task_pool[input_task_slot_index].task_id    = input_task_id;\r
+       _active_task_pool[input_task_slot_index].task_type  = input_task_type;\r
+       _active_task_pool[input_task_slot_index].thread_id  = input_thread_id;\r
+       LEAVE_CRITICAL_SECTION(_active_task_pool_lock);\r
+\r
+       EM_DEBUG_LOG("_active_task_pool[%d].task_id [%d]", input_task_slot_index, _active_task_pool[input_task_slot_index].task_id);\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+static int emcore_remove_task_from_active_task_pool(int input_task_id)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN(" input_task_id [%d]", input_task_id);\r
+       int err = EMAIL_ERROR_NONE;\r
+       int i = 0;\r
+\r
+       ENTER_CRITICAL_SECTION(_active_task_pool_lock);\r
+       for(i = 0; i < MAX_ACTIVE_TASK; i++) {\r
+               if(_active_task_pool[i].task_id == input_task_id) {\r
+                       _active_task_pool[i].task_id    = 0;\r
+                       _active_task_pool[i].task_type  = 0;\r
+                       _active_task_pool[i].thread_id  = 0;\r
+                       break;\r
+               }\r
+       }\r
+       LEAVE_CRITICAL_SECTION(_active_task_pool_lock);\r
+\r
+       if(i >= MAX_ACTIVE_TASK) {\r
+               EM_DEBUG_LOG("couldn't find proper task in active task pool [%d]", input_task_id);\r
+               err = EMAIL_ERROR_TASK_NOT_FOUND;\r
+       }\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_get_active_task_by_thread_id(thread_t input_thread_id, email_active_task_t **output_active_task)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN(" input_thread_id [%d] output_active_task [%p]", input_thread_id, output_active_task);\r
+       int err = EMAIL_ERROR_NONE;\r
+       int i = 0;\r
+\r
+       if (output_active_task == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       for(i = 0; i < MAX_ACTIVE_TASK; i++) {\r
+               if(_active_task_pool[i].thread_id == input_thread_id) {\r
+                       *output_active_task = _active_task_pool + i;\r
+                       break;\r
+               }\r
+       }\r
+\r
+       if(i >= MAX_ACTIVE_TASK) {\r
+               EM_DEBUG_LOG("couldn't find proper task in active task pool [%d]", input_thread_id);\r
+               err = EMAIL_ERROR_TASK_NOT_FOUND;\r
+       }\r
+\r
+FINISH_OFF:\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+\r
+static int emcore_find_available_slot_in_active_task_pool(int *result_index)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("result_index [%p]", result_index);\r
+       int i = 0;\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       if (result_index == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       ENTER_CRITICAL_SECTION(_active_task_pool_lock);\r
+       for(i = 0; i < MAX_ACTIVE_TASK; i++) {\r
+               if(_active_task_pool[i].task_id == 0) {\r
+                       break;\r
+               }\r
+       }\r
+\r
+       if(i >= MAX_ACTIVE_TASK) {\r
+               EM_DEBUG_EXCEPTION("There is no available task slot");\r
+               err = EMAIL_NO_AVAILABLE_TASK_SLOT;\r
+       }\r
+       else {\r
+               _active_task_pool[i].task_id = -1;\r
+               *result_index = i;\r
+       }\r
+       LEAVE_CRITICAL_SECTION(_active_task_pool_lock);\r
+\r
+FINISH_OFF :\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+void* thread_func_task_manager_loop(void *arg)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN();\r
+       int err = EMAIL_ERROR_NONE;\r
+       int thread_error;\r
+       int available_slot_index = 0;\r
+       email_task_t *new_task = NULL;\r
+\r
+       /* while loop */\r
+       while (_task_manager_loop_availability) {\r
+               /* fetch task from DB */\r
+               if( ((err = emcore_fetch_task_from_task_pool(&new_task)) == EMAIL_ERROR_NONE) &&\r
+                       ((err = emcore_find_available_slot_in_active_task_pool(&available_slot_index)) == EMAIL_ERROR_NONE)     ) {\r
+\r
+                       /* update task status as STARTED */\r
+                       if((err = emcore_update_task_status_on_task_table(new_task->task_id, EMAIL_TASK_STATUS_STARTED)) != EMAIL_ERROR_NONE) {\r
+                               EM_DEBUG_EXCEPTION("emcore_update_task_status_on_task_table failed [%d]", err);\r
+                       }\r
+                       new_task->active_task_id = available_slot_index;\r
+\r
+                       /* create a thread to do this task */\r
+                       THREAD_CREATE(new_task->thread_id, emcore_default_task_handler, new_task, thread_error);\r
+\r
+                       /* new_task and task_parameter will be free in task handler. */\r
+                       new_task     = NULL;\r
+\r
+               }\r
+               else {\r
+                       /* If there is no task or no available slot, sleep until someone wake you up. */\r
+                       /* Wake up case 1 : by emcore_add_task_to_task_table */\r
+                       /* Wake up case 2 : when some task terminated */\r
+                       ENTER_CRITICAL_SECTION(_task_available_lock);\r
+                       SLEEP_CONDITION_VARIABLE(_task_available_signal, _task_available_lock);\r
+                       LEAVE_CRITICAL_SECTION(_task_available_lock);\r
+                       EM_DEBUG_LOG("thread_func_task_manager_loop wake up!");\r
+               }\r
+       }\r
+\r
+       EM_DEBUG_FUNC_END();\r
+       return NULL;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_start_task_manager_loop()\r
+{\r
+    EM_DEBUG_FUNC_BEGIN();\r
+       int thread_error;\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       memset(&_active_task_pool, 0, sizeof(email_active_task_t) * MAX_ACTIVE_TASK);\r
+\r
+       if (_thread_task_manager_loop) {\r
+               EM_DEBUG_EXCEPTION("service thread is already running...");\r
+               err = EMAIL_ERROR_ALREADY_INITIALIZED;\r
+               goto FINISH_OFF;\r
+       }\r
+       emcore_init_task_handler_array();\r
+\r
+       _task_manager_loop_availability = 10;\r
+\r
+    /* create thread */\r
+       THREAD_CREATE(_thread_task_manager_loop, thread_func_task_manager_loop, NULL, thread_error);\r
+\r
+       if (thread_error != 0) {\r
+        EM_DEBUG_EXCEPTION("cannot create thread [%d]", thread_error);\r
+        err = EMAIL_ERROR_SYSTEM_FAILURE;\r
+        goto FINISH_OFF;\r
+    }\r
+\r
+FINISH_OFF :\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+    return err;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_stop_task_manager_loop()\r
+{\r
+    EM_DEBUG_FUNC_BEGIN();\r
+\r
+    int err = EMAIL_ERROR_NONE;\r
+\r
+    /* TODO : cancel tasks */\r
+\r
+    /* stop event_data loop */\r
+    _task_manager_loop_availability = 0;\r
+\r
+       ENTER_CRITICAL_SECTION(_task_manager_loop_lock);\r
+       WAKE_CONDITION_VARIABLE(_task_available_signal);\r
+       LEAVE_CRITICAL_SECTION(_task_manager_loop_lock);\r
+\r
+       /* wait for thread finished */\r
+       THREAD_JOIN(_thread_task_manager_loop);\r
+\r
+       _thread_task_manager_loop = 0;\r
+\r
+       DELETE_CRITICAL_SECTION(_task_manager_loop_lock);\r
+       DELETE_CONDITION_VARIABLE(_task_available_signal);\r
+\r
+       /* Free _active_task_pool */\r
+\r
+//FINISH_OFF :\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+    return err;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_add_task_to_task_table(email_task_type_t input_task_type, email_task_priority_t input_task_priority, char *input_task_parameter, int input_task_parameter_length, int *output_task_id)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_type [%d] input_task_priority [%d] input_task_parameter [%p] input_task_parameter_length [%d] output_task_id [%p]", input_task_type, input_task_priority, input_task_parameter, input_task_parameter_length, output_task_id);\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       if((err = emstorage_add_task(input_task_type, input_task_priority, input_task_parameter, input_task_parameter_length, false, output_task_id)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emstorage_add_task failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       ENTER_CRITICAL_SECTION(_task_available_lock);\r
+       WAKE_CONDITION_VARIABLE(_task_available_signal);\r
+       LEAVE_CRITICAL_SECTION(_task_available_lock);\r
+\r
+FINISH_OFF:\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+INTERNAL_FUNC int emcore_remove_task_from_task_table(int input_task_id)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_id [%d]", input_task_id);\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       if((err = emstorage_delete_task(input_task_id, true)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emstorage_delete_task failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+FINISH_OFF:\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+static int emcore_update_task_status_on_task_table(int input_task_id, email_task_status_type_t task_status)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_id [%d] task_status [%d]", input_task_id, task_status);\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       if((err = emstorage_update_task_status(input_task_id, task_status, true)) != EMAIL_ERROR_NONE) {\r
+               EM_DEBUG_EXCEPTION("emstorage_update_task_status failed [%d]", err);\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+FINISH_OFF:\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+/*-Task manager loop - end-------------------------------------------------------------*/\r
diff --git a/email-core/email-core-tasks.c b/email-core/email-core-tasks.c
new file mode 100755 (executable)
index 0000000..65faf1d
--- /dev/null
@@ -0,0 +1,326 @@
+/*\r
+*  email-service\r
+*\r
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
+*\r
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
+*\r
+* Licensed under the Apache License, Version 2.0 (the "License");\r
+* you may not use this file except in compliance with the License.\r
+* You may obtain a copy of the License at\r
+*\r
+* http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*\r
+*/\r
+/*\r
+ * email-tasks.c\r
+ *\r
+ *  Created on: 2012. 11. 5.\r
+ *      Author: kyuho.jo@samsung.com\r
+ */\r
+#include <stdlib.h>\r
+#include <stdio.h>\r
+#include <string.h>\r
+\r
+\r
+#include "email-debug-log.h"\r
+#include "email-utilities.h"\r
+#include "email-internal-types.h"\r
+#include "email-core-tasks.h"\r
+#include "email-core-task-manager.h"\r
+#include "email-core-mail.h"\r
+#include "email-core-mailbox-sync.h"\r
+#include "email-core-signal.h"\r
+#include "tpl.h"\r
+\r
+/*-------------------------------------------------------------------------------------------*/\r
+/* to handle EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT */\r
+#define task_parameter_format_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT "iiiB"\r
+\r
+INTERNAL_FUNC int email_encode_task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT(void *input_task_parameter_struct, char **output_byte_stream, int *output_stream_size)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_parameter_struct [%p] output_byte_stream [%p] output_stream_size [%p]", input_task_parameter_struct, output_byte_stream, output_stream_size);\r
+\r
+       int err = EMAIL_ERROR_NONE;\r
+       task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT *task_parameter = input_task_parameter_struct;\r
+       tpl_bin tb;\r
+       tpl_node *tn = NULL;\r
+       void  *result_data = NULL;\r
+       size_t result_data_length = 0;\r
+\r
+       if (task_parameter == NULL || output_byte_stream == NULL || output_stream_size == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       tn = tpl_map(task_parameter_format_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT\r
+                       , &task_parameter->source_mailbox_id\r
+                       , &task_parameter->target_mailbox_id\r
+                       , &task_parameter->mail_id_count\r
+                       , &tb);\r
+       tb.sz   = sizeof(int) * task_parameter->mail_id_count;\r
+       tb.addr = task_parameter->mail_id_array;\r
+       tpl_pack(tn, 0);\r
+       tpl_dump(tn, TPL_MEM, &result_data, &result_data_length);\r
+       tpl_free(tn);\r
+\r
+       *output_byte_stream = result_data;\r
+       *output_stream_size = result_data_length;\r
+\r
+FINISH_OFF:\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+INTERNAL_FUNC int email_decode_task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT(char *input_byte_stream, int input_stream_size, void **output_task_parameter_struct)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_byte_stream [%p] input_stream_size [%d] output_task_parameter_struct [%p]", input_byte_stream, input_stream_size, output_task_parameter_struct);\r
+       int err = EMAIL_ERROR_NONE;\r
+       tpl_bin tb;\r
+       tpl_node *tn = NULL;\r
+       task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT *task_parameter = NULL;\r
+\r
+       if (input_byte_stream == NULL || input_stream_size == 0 || output_task_parameter_struct == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       task_parameter = em_malloc(sizeof(task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT));\r
+\r
+       if(task_parameter == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");\r
+               err = EMAIL_ERROR_OUT_OF_MEMORY;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       tn = tpl_map(task_parameter_format_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT\r
+                               , &task_parameter->source_mailbox_id\r
+                               , &task_parameter->target_mailbox_id\r
+                               , &task_parameter->mail_id_count\r
+                               , &tb);\r
+       tpl_load(tn, TPL_MEM, input_byte_stream, input_stream_size);\r
+       tpl_unpack(tn, 0);\r
+       if(task_parameter->mail_id_count <= 0 || tb.addr == NULL) {\r
+               EM_DEBUG_LOG("No mail id list. mail_id_count[%d] addr[%p]", task_parameter->mail_id_count, tb.addr);\r
+       }\r
+       else {\r
+               task_parameter->mail_id_array = tb.addr;\r
+       }\r
+\r
+       *output_task_parameter_struct = task_parameter;\r
+\r
+FINISH_OFF:\r
+\r
+       if(tn)\r
+               tpl_free(tn);\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+INTERNAL_FUNC void* task_handler_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT(void *input_param)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_param [%p]", input_param);\r
+       int err = EMAIL_ERROR_NONE;\r
+       int err_for_signal = EMAIL_ERROR_NONE;\r
+       int i = 0;\r
+       int task_id = THREAD_SELF();\r
+       task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT *task_param = input_param;\r
+\r
+       for(i = 0; i < task_param->mail_id_count; i++) {\r
+               if((err = emcore_move_mail_to_another_account(task_param->mail_id_array[i], task_param->source_mailbox_id, task_param->target_mailbox_id, task_id)) != EMAIL_ERROR_NONE) {\r
+                       EM_DEBUG_EXCEPTION("emcore_move_mail_to_another_account failed [%d]", err);\r
+                       goto FINISH_OFF;\r
+               }\r
+\r
+               /* Send progress signal */\r
+               if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT, task_id, EMAIL_TASK_STATUS_IN_PROGRESS, i, task_param->mail_id_count)) != EMAIL_ERROR_NONE)\r
+                       EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);\r
+       }\r
+\r
+FINISH_OFF:\r
+       /* Free task parameter */\r
+       EM_SAFE_FREE(task_param->mail_id_array);\r
+       EM_SAFE_FREE(task_param);\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return NULL;\r
+}\r
+/*-------------------------------------------------------------------------------------------*/\r
+/* to handle EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX */\r
+#define task_parameter_format_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX "iiBi"\r
+\r
+INTERNAL_FUNC int email_encode_task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX(void *input_task_parameter_struct, char **output_byte_stream, int *output_stream_size)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_parameter_struct [%p] output_byte_stream [%p] output_stream_size [%p]", input_task_parameter_struct, output_byte_stream, output_stream_size);\r
+\r
+       int err = EMAIL_ERROR_NONE;\r
+       task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX *task_parameter = input_task_parameter_struct;\r
+       tpl_bin tb;\r
+       tpl_node *tn = NULL;\r
+       void  *result_data = NULL;\r
+       size_t result_data_length = 0;\r
+\r
+       if (task_parameter == NULL || output_byte_stream == NULL || output_stream_size == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       tn = tpl_map(task_parameter_format_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX\r
+                       , &task_parameter->account_id\r
+                       , &task_parameter->mailbox_id_count\r
+                       , &tb\r
+                       , &task_parameter->on_server);\r
+       tb.sz   = sizeof(int) * task_parameter->mailbox_id_count;\r
+       tb.addr = task_parameter->mailbox_id_array;\r
+       tpl_pack(tn, 0);\r
+       tpl_dump(tn, TPL_MEM, &result_data, &result_data_length);\r
+       tpl_free(tn);\r
+\r
+       *output_byte_stream = result_data;\r
+       *output_stream_size = result_data_length;\r
+\r
+FINISH_OFF:\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+INTERNAL_FUNC int email_decode_task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX(char *input_byte_stream, int input_stream_size, void **output_task_parameter_struct)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_byte_stream [%p] input_stream_size [%d] output_task_parameter_struct [%p]", input_byte_stream, input_stream_size, output_task_parameter_struct);\r
+       int err = EMAIL_ERROR_NONE;\r
+       tpl_bin tb;\r
+       tpl_node *tn = NULL;\r
+       task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX *task_parameter = NULL;\r
+\r
+       if (input_byte_stream == NULL || input_stream_size == 0 || output_task_parameter_struct == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       task_parameter = em_malloc(sizeof(task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX));\r
+\r
+       if(task_parameter == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");\r
+               err = EMAIL_ERROR_OUT_OF_MEMORY;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       tn = tpl_map(task_parameter_format_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX\r
+                               , &task_parameter->account_id\r
+                               , &task_parameter->mailbox_id_count\r
+                               , &tb\r
+                               , &task_parameter->on_server);\r
+       tpl_load(tn, TPL_MEM, input_byte_stream, input_stream_size);\r
+       tpl_unpack(tn, 0);\r
+       if(task_parameter->mailbox_id_count <= 0 || tb.addr == NULL) {\r
+               EM_DEBUG_LOG("No mail id list. mail_id_count[%d] addr[%p]", task_parameter->mailbox_id_count, tb.addr);\r
+       }\r
+       else {\r
+               task_parameter->mailbox_id_array = tb.addr;\r
+       }\r
+\r
+       *output_task_parameter_struct = task_parameter;\r
+\r
+FINISH_OFF:\r
+\r
+       if(tn)\r
+               tpl_free(tn);\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+INTERNAL_FUNC void* task_handler_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX(void *input_param)\r
+{\r
+       return NULL;\r
+}\r
+/*-------------------------------------------------------------------------------------------*/\r
+/* to handle EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL */\r
+#define task_parameter_format_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL "i"\r
+\r
+INTERNAL_FUNC int email_encode_task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL(void *input_task_parameter_struct, char **output_byte_stream, int *output_stream_size)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_task_parameter_struct [%p] output_byte_stream [%p] output_stream_size [%p]", input_task_parameter_struct, output_byte_stream, output_stream_size);\r
+\r
+       int err = EMAIL_ERROR_NONE;\r
+       task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL *task_parameter = input_task_parameter_struct;\r
+       tpl_node *tn = NULL;\r
+       void  *result_data = NULL;\r
+       size_t result_data_length = 0;\r
+\r
+       if (task_parameter == NULL || output_byte_stream == NULL || output_stream_size == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       tn = tpl_map(task_parameter_format_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL\r
+                       , &task_parameter->mail_id);\r
+       tpl_pack(tn, 0);\r
+       tpl_dump(tn, TPL_MEM, &result_data, &result_data_length);\r
+       tpl_free(tn);\r
+\r
+       *output_byte_stream = result_data;\r
+       *output_stream_size = result_data_length;\r
+\r
+FINISH_OFF:\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+INTERNAL_FUNC int email_decode_task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL(char *input_byte_stream, int input_stream_size, void **output_task_parameter_struct)\r
+{\r
+       EM_DEBUG_FUNC_BEGIN("input_byte_stream [%p] input_stream_size [%d] output_task_parameter_struct [%p]", input_byte_stream, input_stream_size, output_task_parameter_struct);\r
+       int err = EMAIL_ERROR_NONE;\r
+       tpl_node *tn = NULL;\r
+       task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL *task_parameter = NULL;\r
+\r
+       if (input_byte_stream == NULL || input_stream_size == 0 || output_task_parameter_struct == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");\r
+               err = EMAIL_ERROR_INVALID_PARAM;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       task_parameter = em_malloc(sizeof(task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL));\r
+\r
+       if(task_parameter == NULL) {\r
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");\r
+               err = EMAIL_ERROR_OUT_OF_MEMORY;\r
+               goto FINISH_OFF;\r
+       }\r
+\r
+       tn = tpl_map(task_parameter_format_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL\r
+                               , &task_parameter->mail_id);\r
+       tpl_load(tn, TPL_MEM, input_byte_stream, input_stream_size);\r
+       tpl_unpack(tn, 0);\r
+\r
+       *output_task_parameter_struct = task_parameter;\r
+\r
+FINISH_OFF:\r
+\r
+       if(tn)\r
+               tpl_free(tn);\r
+\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return EMAIL_ERROR_NONE;\r
+}\r
+\r
+INTERNAL_FUNC void* task_handler_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL(void *input_param)\r
+{\r
+       return NULL;\r
+}\r
+/*-------------------------------------------------------------------------------------------*/\r
diff --git a/email-core/email-core-timer.c b/email-core/email-core-timer.c
new file mode 100755 (executable)
index 0000000..04ceb95
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <stdlib.h>
+#include <string.h>
+#include <sys/time.h>
+#include <signal.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <time.h>
+#include <errno.h>
+#include <sys/signal.h>
+#include <sys/timeb.h>
+#include "email-core-timer.h"
+#include "email-debug-log.h"
+#include <dbus/dbus-glib.h> 
+
+
+typedef struct
+{
+       EMAIL_TIMER_CALLBACK user_callback_function;
+       void *callback_user_data;
+       int time_id;
+}em_timer_callback_data;
+
+
+INTERNAL_FUNC int emcore_timer_ex_callback(void *a_pData)
+{
+       EM_DEBUG_LOG("[emcore_timer_ex_callback] enter\n");
+       void *pUserData = NULL;
+
+
+       g_thread_init(NULL);
+       dbus_g_thread_init ();
+
+       em_timer_callback_data *pTimerData = (em_timer_callback_data *)a_pData;
+       if (pTimerData != NULL)
+               {
+               EMAIL_TIMER_CALLBACK pfn_UserCB = pTimerData->user_callback_function;
+                       pUserData = pTimerData->callback_user_data;
+               if (pUserData)
+                       EM_DEBUG_LOG("emcore_timer_ex_callback >>> data  :  %s", (char *)pTimerData->callback_user_data);
+                       EM_SAFE_FREE(pTimerData);
+                       pfn_UserCB(pUserData);
+               }
+               
+       g_thread_init(NULL);
+       dbus_g_thread_init ();
+
+       EM_DEBUG_LOG("[emcore_timer_ex_callback] leave\n");
+
+       if (pUserData)
+               return 0;
+       else
+                       return 1;
+}
+
+INTERNAL_FUNC int emcore_set_timer_ex(long a_nSetTimeValue, EMAIL_TIMER_CALLBACK a_pCallBack, void *a_pData)
+{
+       EM_DEBUG_LOG("emcore_set_timer_ex %d", a_nSetTimeValue);
+       em_timer_callback_data *pTimerData = NULL;
+       pTimerData = malloc(sizeof(em_timer_callback_data));
+       char *data = NULL;
+       if (!pTimerData)
+               return -1;
+       memset(pTimerData, 0x00, sizeof(em_timer_callback_data));
+       if (a_pData)
+               EM_DEBUG_LOG("emcore_set_timer_ex >>> data  :  %s", (char *)a_pData);
+
+       pTimerData->user_callback_function = a_pCallBack;
+       if (a_pData) {
+               data = (char *) a_pData;
+               pTimerData->callback_user_data = EM_SAFE_STRDUP(data);
+       }
+       pTimerData->time_id = g_timeout_add(a_nSetTimeValue, emcore_timer_ex_callback, pTimerData);
+       return pTimerData->time_id;
+}
+
+INTERNAL_FUNC void emcore_kill_timer_ex(int a_nTimerID)
+{
+       EM_DEBUG_LOG("[emcore_kill_timer_ex] a_nTimerID %d", a_nTimerID);
+       g_source_remove(a_nTimerID);
+}
+
diff --git a/email-core/email-core-utils.c b/email-core/email-core-utils.c
new file mode 100755 (executable)
index 0000000..570ccaa
--- /dev/null
@@ -0,0 +1,2325 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File: email-core-utils.c
+ * Desc: Mail Utils
+ *
+ * Auth:
+ *
+ * History:
+ *     2006.08.16 : created
+ *****************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <errno.h>
+#include <dlfcn.h>
+#include <glib.h>
+#include <glib-object.h>
+#include <sys/time.h>
+#include <unistd.h>
+#include <sys/vfs.h>
+#include <sys/stat.h>
+#include <vconf.h>
+#include <regex.h>
+#include <pthread.h>
+#include <notification.h>
+#include <badge.h>
+
+#include "email-types.h"
+#include "email-core-global.h"
+#include "email-core-utils.h"
+#include "email-debug-log.h"
+#include "email-core-mail.h"
+#include "email-core-event.h"
+#include "email-core-mailbox.h"
+#include "email-core-account.h"
+#include "email-core-mailbox-sync.h"
+#include "email-core-mime.h"
+#include "email-core-sound.h"
+#include "email-core-signal.h"
+#include "email-utilities.h"
+#include "email-convert.h"
+
+#define LED_TIMEOUT_SECS          12
+#define G_DISPLAY_LENGTH          256
+
+#define DIR_SEPERATOR_CH          '/'
+#define EMAIL_CH_QUOT             '"'
+#define EMAIL_CH_BRACKET_S        '<'
+#define EMAIL_CH_BRACKET_E        '>'
+#define EMAIL_CH_COMMA            ','
+#define EMAIL_CH_SEMICOLON        ';'
+#define EMAIL_CH_ROUND_BRACKET_S  '('
+#define EMAIL_CH_ROUND_BRACKET_E  ')'
+#define EMAIL_CH_SQUARE_BRACKET_S '['
+#define EMAIL_CH_SQUARE_BRACKET_E ']'
+#define EMAIL_CH_SPACE            ' '
+#define EMAIL_NOTI_ICON_PATH      EMAILPATH"/res/image/Q02_Notification_email.png"
+#define VCONF_KEY_UNREAD_MAIL_COUNT "db/badge/com.samsung.email"
+
+typedef struct  _em_transaction_info_type_t {
+       int mail_id;
+       int     handle;
+       struct _em_transaction_info_type_t *next;
+
+} em_transaction_info_type_t;
+
+em_transaction_info_type_t  *g_transaction_info_list;
+
+static email_session_t g_session_list[SESSION_MAX] = { {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0},};
+
+typedef struct emcore_account_list_t emcore_account_list_t;
+struct emcore_account_list_t {
+       email_account_t *account;
+       emcore_account_list_t *next;
+};
+
+INTERNAL_FUNC char *emcore_convert_mutf7_to_utf8(char *mailbox_name)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       return (char *)(utf8_from_mutf7((unsigned char *)mailbox_name));
+}
+
+/*  in smtp case, path argument must be ENCODED_PATH_SMTP */
+int emcore_get_long_encoded_path_with_account_info(email_account_t *account, char *path, int delimiter, char **long_enc_path, int *err_code)
+{
+       EM_PROFILE_BEGIN(emCorelongEncodedpath);
+       EM_DEBUG_FUNC_BEGIN("account[%p], path[%s], delimiter[%d], long_enc_path[%p], err_code[%p]", account, path, delimiter, long_enc_path, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char *p = NULL;
+
+       size_t long_enc_path_len = 0;
+
+       if (path == NULL || (path && strncmp(path, ENCODED_PATH_SMTP, EM_SAFE_STRLEN(ENCODED_PATH_SMTP)) != 0)) {               /*  imap or pop3 */
+               EM_DEBUG_LOG("account->incoming_server_address[%p]", account->incoming_server_address);
+               EM_DEBUG_LOG("account->incoming_server_address[%s]", account->incoming_server_address);
+
+               if (!account->incoming_server_address) {
+                       EM_DEBUG_EXCEPTION("account->incoming_server_address is null");
+                       error = EMAIL_ERROR_INVALID_ACCOUNT;
+                       goto FINISH_OFF;
+               }
+
+               long_enc_path_len = EM_SAFE_STRLEN(account->incoming_server_address) + EM_SAFE_STRLEN(path) + 64; /*prevent 34357*/
+
+               *long_enc_path = em_malloc(long_enc_path_len);
+               if (!*long_enc_path)  {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               p = *long_enc_path;
+
+               /*  ex:"{mai.test.com:143/imap} or {mai.test.com:143/imap/tls}my-mailbox" */
+
+               SNPRINTF(p, long_enc_path_len, "{%s:%d/%s/user=%d",
+                       account->incoming_server_address,
+                       account->incoming_server_port_number,
+                       account->incoming_server_type == EMAIL_SERVER_TYPE_POP3 ? "pop3" : "imap", account->account_id);
+
+               if (account->incoming_server_secure_connection & 0x01)  {
+                       strncat(p, "/ssl", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+                       /* strcat(p, "/tryssl"); */
+               }
+
+               /* Currently, receiving servers doesn't require tls.
+               if (account->incoming_server_secure_connection & 0x02)
+                       strncat(p, "/tls", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+               else
+                       strncat(p, "/notls", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+               */
+
+               if (account->incoming_server_requires_apop) {
+                       EM_DEBUG_LOG("emcore_get_long_encoded_path - incoming_server_requires_apop - %d", account->incoming_server_requires_apop);
+                       strncat(p, "/apop", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+                       EM_DEBUG_LOG("long_enc_path - %s", p);
+               }
+       }
+       else  {         /*  smtp */
+               long_enc_path_len = EM_SAFE_STRLEN(account->outgoing_server_address) + 64;
+
+               *long_enc_path = em_malloc(EM_SAFE_STRLEN(account->outgoing_server_address) + 64);
+               if (!*long_enc_path) {
+                       EM_DEBUG_EXCEPTION("\t malloc failed...\n");
+
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               p = *long_enc_path;
+
+               /*  ex:"mail.test.com:25/smtp" */
+
+               SNPRINTF(p, long_enc_path_len, "%s:%d/%s",
+                       account->outgoing_server_address,
+                       account->outgoing_server_port_number,
+                       "smtp");
+
+               if (account->outgoing_server_need_authentication) {
+                       SNPRINTF(p + EM_SAFE_STRLEN(p), long_enc_path_len-(EM_SAFE_STRLEN(p)), "/user=%d", account->account_id);
+               }
+
+               if (account->outgoing_server_secure_connection & 0x01) {
+                       strncat(p, "/ssl", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+                       /* strcat(p, "/tryssl"); */
+               }
+               if (account->outgoing_server_secure_connection & 0x02)
+                       strncat(p, "/tls", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+               else
+                       strncat(p, "/notls", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+       }
+
+       if (path == NULL || (path && strncmp(path, ENCODED_PATH_SMTP, EM_SAFE_STRLEN(ENCODED_PATH_SMTP)) != 0)) {
+               strncat(p, "}", long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+
+               if (path != NULL) {
+                       char *enc_name = NULL;
+
+                       if (!emcore_get_encoded_mailbox_name(path, &enc_name, &error))  {
+                               EM_DEBUG_EXCEPTION("emcore_get_encoded_mailbox_name failed - %d", error);
+                               *long_enc_path = NULL;
+                               goto FINISH_OFF;
+                       }
+
+                       if (enc_name)  {
+                               strncat(p, enc_name, long_enc_path_len-(EM_SAFE_STRLEN(p)+1));
+                               EM_SAFE_FREE(enc_name);
+                       }
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret != true)
+               EM_SAFE_FREE(p);
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_PROFILE_END(emCorelongEncodedpath);
+       return ret;
+}
+
+int emcore_get_long_encoded_path(int account_id, char *path, int delimiter, char **long_enc_path, int *err_code)
+{
+       EM_PROFILE_BEGIN(emCorelongEncodedpath);
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], delimiter[%d], long_enc_path[%p], err_code[%p]", account_id, delimiter, long_enc_path, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       email_account_t *ref_account = NULL;
+
+       ref_account = emcore_get_account_reference(account_id);
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               error = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (emcore_get_long_encoded_path_with_account_info(ref_account, path, delimiter, long_enc_path, &error) == false) {
+               EM_DEBUG_EXCEPTION("emcore_get_long_encoded_path_with_account_info failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_PROFILE_END(emCorelongEncodedpath);
+       return ret;
+}
+
+int emcore_get_encoded_mailbox_name(char *name, char **enc_name, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("name[%s], enc_name[%p], err_code[%p]", name, enc_name, err_code);
+
+       if (!name || !enc_name)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_FUNC_END();
+               return false;
+       }
+
+       /* encoding mailbox name (Charset->UTF8->UTF7) */
+
+       *enc_name = em_malloc(EM_SAFE_STRLEN(name)+1);
+       if (*enc_name == NULL) {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               EM_DEBUG_FUNC_END();
+               return false;
+       }
+
+       strcpy(*enc_name, name);
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_get_temp_file_name(char **filename, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filename[%p], err_code[%p]", filename, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (filename == NULL) {
+               EM_DEBUG_EXCEPTION("\t filename[%p]\n", filename);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       char tempname[512] = {0x00, };
+       struct timeval tv;
+
+
+       gettimeofday(&tv, NULL);
+       srand(tv.tv_usec);
+
+       /* Create Directory If deleted by user*/
+       emstorage_create_dir_if_delete();
+
+       SNPRINTF(tempname, sizeof(tempname), "%s%c%d", MAILTEMP, DIR_SEPERATOR_CH, rand());
+
+       char *p = EM_SAFE_STRDUP(tempname);
+       if (p == NULL) {
+               EM_DEBUG_EXCEPTION("\t strdup failed...\n");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       *filename = p;
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emcore_get_file_name(char *path, char **filename, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("path[%s], filename[%p], err_code[%p]", path, filename, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (!path || !filename) {
+               EM_DEBUG_EXCEPTION("path[%p], filename[%p]", path, filename);
+
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       int i = (int)EM_SAFE_STRLEN(path);
+
+       /*  get filename */
+       for (; i >= 0; i--)
+               if (path[i] == DIR_SEPERATOR_CH)
+                       break;
+
+       *filename = path + i + 1;
+
+       ret = true;
+
+FINISH_OFF:
+               if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emcore_get_file_size(char *path, int *size, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("path[%s], size[%p], err_code[%p]", path, size, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if ((path == NULL) || (size == NULL)) {
+               EM_DEBUG_EXCEPTION("\t path[%p], size[%p]\n", path, size);
+
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       struct stat st_buf;
+
+       if (stat(path, &st_buf) < 0)  {
+               EM_DEBUG_EXCEPTION("\t stat failed - %s\n", path);
+
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       *size = st_buf.st_size;
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+
+static int _emcore_check_host(char *host)
+{
+       if (!host)
+               return 0;
+       return strncmp(host, ".SYNTAX-ERROR.", strlen(".SYNTAX-ERROR."));
+}
+
+
+
+int emcore_get_address_count(char *addr_str, int *count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("addr_str[%s], count[%p], err_code[%p]", addr_str, count, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       ADDRESS *addr = NULL;
+       ADDRESS *p_addr = NULL;
+       int i = 0, j;
+       char *p = NULL;
+
+
+       if (!count)  {
+               EM_DEBUG_EXCEPTION("addr_str[%s], count[%p]", addr_str, count);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (addr_str != NULL)  {
+               em_skip_whitespace(addr_str, &p);
+               EM_DEBUG_LOG("em_skip_whitespace[p][%s]", p);
+
+
+               for (i = 0, j = EM_SAFE_STRLEN(p); i < j; i++)
+                       if (p[i] == ';') p[i] = ',';
+               rfc822_parse_adrlist(&addr, p, NULL);
+               EM_SAFE_FREE(p);
+
+
+               for (p_addr = addr, i = 0; p_addr; p_addr = p_addr->next, i++)  {
+                       if (p_addr->mailbox && p_addr->host) {
+                               if (!strncmp(p_addr->mailbox, "UNEXPECTED_DATA_AFTER_ADDRESS", strlen("UNEXPECTED_DATA_AFTER_ADDRESS"))
+                               || !strncmp(p_addr->mailbox, "INVALID_ADDRESS", strlen("INVALID_ADDRESS"))
+                               || !strncmp(p_addr->host, ".SYNTAX-ERROR.", strlen(".SYNTAX-ERROR."))) { /*prevent 34356*/
+                                       EM_DEBUG_LOG("Invalid address ");
+                                       continue;
+                               }
+                       }
+                       if ((!p_addr->mailbox) || (_emcore_check_host(p_addr->host) == 0)) {
+                               EM_DEBUG_EXCEPTION("\t invalid address : mailbox[%s], host[%s]\n", p_addr->mailbox, p_addr->host);
+
+                               error = EMAIL_ERROR_INVALID_ADDRESS;
+                               /* goto FINISH_OFF; */
+                       }
+               }
+       }
+
+       *count = i;
+       if (error != EMAIL_ERROR_INVALID_ADDRESS)
+       ret = true;
+
+FINISH_OFF:
+       if (addr)
+               mail_free_address(&addr);
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_set_network_error(int err_code)
+{
+       email_session_t *session = NULL;
+
+       EM_DEBUG_FUNC_BEGIN();
+
+       emcore_get_current_session(&session);
+
+       if (!session)
+               return false;
+
+       session->network = err_code;
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_get_empty_session(email_session_t **session)
+{
+       EM_DEBUG_FUNC_BEGIN("session[%p]", session);
+
+       /*  lock()... */
+
+       int i;
+
+       for (i = 0; i < SESSION_MAX; i++)  {
+               if (!g_session_list[i].status)  {
+                       memset(g_session_list+i, 0x00, sizeof(email_session_t));
+                       g_session_list[i].tid = GPOINTER_TO_INT(THREAD_SELF());
+                       g_session_list[i].status = true;
+                       break;
+               }
+       }
+
+       /*  unlock()... */
+
+       if (session != NULL)
+               *session = (i != SESSION_MAX) ? &g_session_list[i] : NULL;
+       EM_DEBUG_FUNC_END();
+       return (i != SESSION_MAX) ? true : false;
+}
+
+int emcore_clear_session(email_session_t *session)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (session)
+               memset(session, 0x00, sizeof(email_session_t));
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+int emcore_get_current_session(email_session_t **session)
+{
+       EM_DEBUG_FUNC_BEGIN("session[%p]", session);
+
+       int i;
+
+       for (i = 0; i < SESSION_MAX; i++)  {
+               if (g_session_list[i].tid == GPOINTER_TO_INT(THREAD_SELF())) {
+                       if (session)
+                               *session = g_session_list + i;
+
+                       break;
+               }
+       }
+
+       if (session)
+               *session = (i != SESSION_MAX) ? g_session_list + i : NULL;
+       EM_DEBUG_FUNC_END();
+       return (i != SESSION_MAX) ? true : false;
+}
+
+int emcore_get_mail_count_by_query(int account_id, int priority_sender, int *total_mail, int *unread_mail, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int i, count;
+       int type = EMAIL_PRIORITY_SENDER;
+       int unread_count = 0;
+       int total_count = 0;
+       char *conditional_clause_string = NULL;
+
+       int rule_count = 0;
+       int is_completed = 0;
+       emstorage_rule_tbl_t *rule = NULL;
+
+       int filter_count = 0;
+       email_list_filter_t *filter_list = NULL;
+
+       if (priority_sender) {
+               /* Get rule list */
+               if (!emstorage_get_rule(ALL_ACCOUNT, type, 0, &rule_count, &is_completed, &rule, true, &err) || !rule) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_rule failed");
+                       goto FINISH_OFF;
+               }
+
+               /* Make query for searching unread mail */
+               if (account_id != ALL_ACCOUNT) {
+                       filter_count = (rule_count * 2) + 3;
+               } else {
+                       filter_count = (rule_count * 2) + 1;                              // 1 is unseen field.
+               }
+
+               filter_list = em_malloc(sizeof(email_list_filter_t) * filter_count);
+               if (filter_list == NULL) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               for (i = 0, count = 0; i < filter_count - 1; i += 2, count++) {
+                       filter_list[i].list_filter_item_type                             = EMAIL_LIST_FILTER_ITEM_RULE;
+                       filter_list[i].list_filter_item.rule.rule_type                   = EMAIL_LIST_FILTER_RULE_INCLUDE;
+                       filter_list[i].list_filter_item.rule.target_attribute            = EMAIL_MAIL_ATTRIBUTE_FROM;
+                       filter_list[i].list_filter_item.rule.key_value.string_type_value = EM_SAFE_STRDUP(rule[count].value);
+
+                       filter_list[i+1].list_filter_item_type                           = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+                       if (i == (filter_count - 2)) {
+                               filter_list[i+1].list_filter_item.operator_type          = EMAIL_LIST_FILTER_OPERATOR_AND;
+                       } else {
+                               filter_list[i+1].list_filter_item.operator_type          = EMAIL_LIST_FILTER_OPERATOR_OR;
+                       }
+               }
+
+               filter_list[i].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+               filter_list[i].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+               filter_list[i].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_FLAGS_SEEN_FIELD;
+               filter_list[i].list_filter_item.rule.key_value.integer_type_value = 0;
+
+               if (account_id != ALL_ACCOUNT) {
+                       filter_list[i+1].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+                       filter_list[i+1].list_filter_item.operator_type                     = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+                       filter_list[i+2].list_filter_item_type                              = EMAIL_LIST_FILTER_ITEM_RULE;
+                       filter_list[i+2].list_filter_item.rule.rule_type                    = EMAIL_LIST_FILTER_RULE_EQUAL;
+                       filter_list[i+2].list_filter_item.rule.target_attribute             = EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID;
+                       filter_list[i+2].list_filter_item.rule.key_value.integer_type_value = account_id;
+               }
+
+               if ((err = emstorage_write_conditional_clause_for_getting_mail_list(filter_list, filter_count, NULL, 0, -1, -1, &conditional_clause_string)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emstorage_write_conditional_clause_for_getting_mail_list failed[%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("conditional_clause_string[%s]", conditional_clause_string);
+
+               /* Search the mail of priority sender in DB */
+               if ((err = emstorage_query_mail_count(conditional_clause_string, true, &total_count, &unread_count)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emstorage_query_mail_count failed:[%d]", err);
+                       goto FINISH_OFF;
+               }
+       } else {
+               if (!emstorage_get_mail_count(account_id, NULL, &total_count, &unread_count, true, &err))  {
+                       EM_DEBUG_EXCEPTION(" emstorage_get_mail_count failed - %d", err);
+
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (rule)
+               emstorage_free_rule(&rule, rule_count, NULL);
+
+       if (filter_list)
+               emstorage_free_list_filter(&filter_list, filter_count);
+
+       EM_SAFE_FREE(conditional_clause_string);
+
+       if (total_mail)
+               *total_mail = total_count;
+
+       if (unread_mail)
+               *unread_mail = unread_count;
+
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+int emcore_display_unread_in_badge()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int total_unread_count = 0;
+       int total_mail_count = 0;
+       int badge_ticker = 0;
+       int priority_sender = 0;
+
+
+       /* Get the Global noti ticker */
+       if (vconf_get_bool(VCONFKEY_TICKER_NOTI_BADGE_EMAIL, &badge_ticker) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+               err = EMAIL_ERROR_GCONF_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Get the priority noti ticker */
+       if (!badge_ticker) {
+               if (vconf_get_bool(VCONF_VIP_NOTI_BADGE_TICKER, &badge_ticker) != 0) {
+                       EM_DEBUG_EXCEPTION("vconf_get_bool failed");
+                       err = EMAIL_ERROR_GCONF_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if (!badge_ticker) {
+                       EM_DEBUG_LOG("Not display the badge");
+                       ret = true;
+                       goto FINISH_OFF;
+               }
+
+               priority_sender = 1;
+       }
+
+       /* Get unread mail count */
+       if (!emcore_get_mail_count_by_query(ALL_ACCOUNT, priority_sender, &total_mail_count, &total_unread_count, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_count_by_query failed");
+               goto FINISH_OFF;
+       }
+
+       /* temporarily disable : set unread count to badge */
+       if (vconf_set_int(VCONF_KEY_UNREAD_MAIL_COUNT, total_unread_count) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_set_int failed");
+               err = EMAIL_ERROR_GCONF_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /* Use badge API */
+       badge_error_e badge_err = BADGE_ERROR_NONE;
+       bool exist;
+
+       if((badge_err = badge_is_existing("com.samsung.email", &exist)) != BADGE_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("badge_is_existing failed [%d]", badge_err);
+               err = EMAIL_ERROR_BADGE_API_FAILED;
+               goto FINISH_OFF;
+       }
+       if (!exist) {
+               /* create badge */
+               if((badge_err = badge_create("com.samsung.email", "/usr/bin/email-service")) != BADGE_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("badge_create failed [%d]", badge_err);
+                       err = EMAIL_ERROR_BADGE_API_FAILED;
+                       goto FINISH_OFF;
+               }
+       }
+
+       if((badge_err = badge_set_count("com.samsung.email", total_unread_count)) != BADGE_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("badge_set_count failed [%d]", badge_err);
+               err = EMAIL_ERROR_BADGE_API_FAILED;
+               goto FINISH_OFF;
+       }
+
+       if (total_unread_count <= 0)
+               goto FINISH_OFF;
+
+       ret = true;
+
+FINISH_OFF:
+
+       return ret;
+}
+
+static int emcore_layout_multi_noti(notification_h noti, int unread_mail, char *email_address, char *account_name)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+       char modified_string[10];
+
+       noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_MULTIPLE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_layout NOTI_EVENT_SINGLE failed [%d]", noti_err);
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(modified_string, sizeof(modified_string), "%d", unread_mail);
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Email", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_TITLE failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, modified_string, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_EVENT_COUNT failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "new emails", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_CONTENT failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, email_address, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_INFO_1 failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, account_name, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_INFO_2 failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, EMAIL_NOTI_ICON_PATH);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_image TYPE_ICON failed");
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("noti_err : [%d]", noti_err);
+       return noti_err;
+}
+
+static int emcore_layout_single_noti(notification_h noti, char *account_name, char *display_sender, time_t time, char *subject)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_SINGLE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_layout NOTI_EVENT_SINGLE failed [%d]", noti_err);
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Email", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_TITLE failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, account_name, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_CONTENT failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, display_sender, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_INFO_1 failed");
+               goto FINISH_OFF;
+       }
+
+       /*
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_SUB_1, time, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_INFO_SUB_1 failed");
+               goto FINISH_OFF;
+       }
+       */
+
+       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, subject, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_text TEXT_TYPE_INFO_2 failed");
+               goto FINISH_OFF;
+       }
+
+       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, EMAIL_NOTI_ICON_PATH);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("notification_set_image TYPE_ICON failed");
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("noti_err : [%d]", noti_err);
+       return noti_err;
+}
+
+static int emcore_add_notification(int account_id, int mail_id, email_action_t action)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END("ret [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_show_user_message(int id, email_action_t action, int error)
+{
+       EM_DEBUG_FUNC_BEGIN("id[%d], action[%d], error[%d]", id, action, error);
+
+       int ret = false;
+
+       if (action == EMAIL_ACTION_SEND_MAIL && error != EMAIL_ERROR_CANCELLED) {
+       /*  In case email is cancelled using cancel button in Outbox there is no need to show Cancel/Retry Pop up */
+               emstorage_mail_tbl_t *mail_table_data = NULL;
+
+               if (error == 0) /*  error 0 means 'this is not error' */
+                       return true;
+
+               if (id <= 0) {
+                       EM_DEBUG_LOG("Invalid mail_id");
+                       return false;
+               }
+
+               if (!emstorage_get_mail_by_id(id, &mail_table_data, true, NULL)) {
+                       EM_DEBUG_LOG("Mail not found");
+                       return false;
+               }
+
+               if (emcore_add_notification(mail_table_data->account_id, id, action) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_notification_set error");
+
+                       if (!emstorage_free_mail(&mail_table_data, 1, NULL))
+                               EM_DEBUG_EXCEPTION("emstorage_free_mail Failed");
+
+                       return false;
+               }
+
+               if (!emstorage_free_mail(&mail_table_data, 1, NULL))
+                       EM_DEBUG_EXCEPTION("emstorage_free_mail Failed");
+
+               ret = true;
+       }
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+/* storage space handling - 210709 */
+int emcore_get_storage_status(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int storage_status = 0, nError = 0;
+
+       g_type_init();
+
+#ifdef STORAGE_STATUS
+       nError = vconf_get_int(PS_KEY_SYSTEM_STORAGE_MOVI_STATUS,
+                                                       &storage_status);
+#endif /*  STORAGE_STATUS */
+
+       if (nError == -1) {
+               EM_DEBUG_EXCEPTION("vconf_get_int Failed");
+               return false;
+       }
+       EM_DEBUG_FUNC_END();
+       return storage_status;
+}
+
+int emcore_is_storage_full(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       struct statfs buf = {0};
+
+       if (statfs(DATA_PATH, &buf) == -1) {
+               EM_DEBUG_EXCEPTION("statfs(\"%s\") failed - %d", DATA_PATH, errno);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       else  {
+               long i_free = (buf.f_bfree * buf.f_bsize) / (1024 * 1024);
+               EM_DEBUG_LOG("f_bfree[%d] f_bsize[%d]", buf.f_bfree, buf.f_bsize);
+               EM_DEBUG_LOG("Free space of storage is[%ld] MB.", i_free);
+               if (i_free < EMAIL_LIMITATION_FREE_SPACE)
+                       err = EMAIL_ERROR_MAIL_MEMORY_FULL;
+       }
+
+       if (err == EMAIL_ERROR_MAIL_MEMORY_FULL)
+               ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("ret[%d]", ret);
+       return ret;
+}
+
+int emcore_calc_mail_size(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, int *output_size)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count[%d], output_size[%p]", input_mail_data, input_attachment_data_list, input_attachment_count, output_size);
+
+       struct stat            st_buf;
+       int                    mail_size = 0; /*  size of the plain text body and attachments */
+       int                    err       = EMAIL_ERROR_NONE;
+       int                    i         = 0;
+
+       if (!input_mail_data || (input_attachment_count && !input_attachment_data_list) || (!input_attachment_count &&input_attachment_data_list) || !output_size)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (input_mail_data->file_path_plain != NULL) {
+               if (stat(input_mail_data->file_path_plain, &st_buf) < 0)  {
+                       EM_DEBUG_EXCEPTION("input_mail_data->file_path_plain : stat(\"%s\") failed...", input_mail_data->file_path_plain);
+                       err = EMAIL_ERROR_INVALID_MAIL;
+                       goto FINISH_OFF;
+               }
+
+               mail_size += st_buf.st_size;
+
+       }
+
+       if (input_mail_data->file_path_html != NULL) {
+               if (stat(input_mail_data->file_path_html, &st_buf) < 0) {
+                       EM_DEBUG_EXCEPTION("input_mail_data->file_path_html : stat(\"%s\") failed...", input_mail_data->file_path_html);
+                       err = EMAIL_ERROR_INVALID_MAIL;
+                       goto FINISH_OFF;
+               }
+
+               mail_size += st_buf.st_size;
+       }
+
+       for(i = 0; i < input_attachment_count; i++)  {
+               if (stat(input_attachment_data_list[i].attachment_path, &st_buf) < 0)  {
+                       EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", input_attachment_data_list[i].attachment_path);
+                       err = EMAIL_ERROR_INVALID_MAIL;
+                       goto FINISH_OFF;
+               }
+               mail_size += st_buf.st_size;
+       }
+
+       *output_size = mail_size;
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("mail_size [%d]", mail_size);
+       return err;
+}
+
+
+/* parse the Full mailbox Path and Get the Alias Name of the Mailbox */
+char *emcore_get_alias_of_mailbox(const char *mailbox_path)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_IF_NULL_RETURN_VALUE(mailbox_path, NULL);
+
+       guint index = 0;
+       gchar **token_list = NULL;
+       gchar *mailbox = NULL, *name = NULL;
+       char *converted_name;
+
+
+       mailbox = g_strdup(mailbox_path);
+       token_list = g_strsplit_set(mailbox, "/", -1);
+
+       if (mailbox)
+               g_free(mailbox);
+
+       while (token_list[index] != NULL)
+               index++;
+
+       name = g_strdup(token_list[index - 1]);
+       if(!name) /* prevent 27459 */
+               return NULL;
+
+       g_strfreev(token_list);
+
+       converted_name = emcore_convert_mutf7_to_utf8(name);
+
+       if (name)
+               g_free(name);
+
+       EM_DEBUG_FUNC_END();
+       return converted_name;
+}
+
+
+static int emcore_get_first_address(const char *full_address, char **alias, char **address)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (full_address == NULL || alias == NULL || address == NULL){
+               EM_DEBUG_EXCEPTION("Invalid Param  :  full_address[%p], alias[%p], address[%p]", full_address, alias, address);
+               return false;
+       }
+
+       char *s = NULL;
+       char *alias_start = NULL;
+       char *alias_end = NULL;
+       char *alias_cursor = NULL;
+       char *address_start = NULL;
+       char *address_end = NULL;
+       char *first_address = NULL;
+
+       if (full_address){
+               s = (char *)strchr((char *)full_address, ';');
+               if (s == NULL)
+                       first_address = strdup(full_address);   /*  only one  address */
+               else
+                       first_address = strndup(full_address, s - full_address);        /*  over two addresses */
+
+               /*  get alias */
+               *alias = NULL;
+               if ((alias_start = (char *)strchr((char *)first_address, '\"'))){
+                       alias_start++;
+                       alias_cursor = alias_start;
+                       while ((alias_cursor = (char *)strchr((char *)(alias_cursor), '\"'))){
+                               alias_end = alias_cursor;
+                               alias_cursor++;
+                               if (*alias_cursor == 0)
+                                       break;
+                       }
+                       if (alias_end)  {       /*  there is "alias" */
+                               *alias = strndup(alias_start, alias_end - alias_start);
+                               EM_DEBUG_LOG("alias [%s]", *alias);
+                       }
+               }
+
+               /*  get address */
+               *address = NULL;
+               if (alias_end == NULL)
+                       s = first_address;
+               else
+                       s = alias_end+1;
+               if ((address_start = (char *)strchr((char  *)s, '<'))){
+                       address_start++;
+                       if ((address_end = (char *)strchr((char  *)address_start, '>')))
+                               *address = strndup(address_start, address_end - address_start); /*  (alias) <(addr)>  ... */
+                       else
+                               *address = strdup(s);
+               }
+               else
+              *address = strdup(s);    /*  (addr) ; ...                 :  no alias */
+       }
+
+       EM_SAFE_FREE(first_address);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+void emcore_fill_address_information_of_mail_tbl(emstorage_mail_tbl_t *mail_data)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_data [%p]", mail_data);
+
+       char *first_alias   = NULL;
+       char *first_address = NULL;
+       char *recipient     = NULL;
+
+       /*  sender alias & address */
+       if (emcore_get_first_address(mail_data->full_address_from, &first_alias, &first_address) == true) {
+               if (first_alias == NULL) {
+                       mail_data->alias_sender = EM_SAFE_STRDUP(first_address);
+               }
+               else {
+                       mail_data->alias_sender = first_alias;
+                       first_alias = NULL;
+               }
+               mail_data->email_address_sender = first_address;
+               first_address = NULL;
+       }
+
+       /*  recipient alias & address */
+       if (mail_data->full_address_to != NULL)
+               recipient = mail_data->full_address_to;
+       else if (mail_data->full_address_cc != NULL)
+               recipient = mail_data->full_address_cc;
+       else if (mail_data->full_address_bcc != NULL)
+               recipient = mail_data->full_address_bcc;
+
+       if (emcore_get_first_address(recipient, &first_alias, &first_address) == true) {
+               if (first_alias == NULL)
+                       mail_data->alias_recipient = EM_SAFE_STRDUP(first_address);
+               else
+                       mail_data->alias_recipient = first_alias;
+
+               mail_data->email_address_recipient = first_address;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+
+int emcore_get_preview_text_from_file(const char *input_plain_path, const char *input_html_path, int input_preview_buffer_length, char **output_preview_buffer)
+{
+       EM_DEBUG_FUNC_BEGIN("input_plain_path[%p], input_html_path[%p], input_preview_buffer_length [%d], output_preview_buffer[%p]", input_plain_path, input_html_path, input_preview_buffer_length, output_preview_buffer);
+
+       int          err = EMAIL_ERROR_NONE;
+       unsigned int byte_read = 0;
+       unsigned int byte_written = 0;
+       int          local_preview_buffer_length = 0;
+       char        *local_preview_text = NULL;
+       char        *encoding_type = NULL;
+       char        *utf8_encoded_string = NULL;
+       FILE        *fp_html = NULL;
+       FILE        *fp_plain = NULL;
+       GError      *glib_error = NULL;
+       struct stat  st_buf;
+
+       if (!output_preview_buffer) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       local_preview_buffer_length = input_preview_buffer_length * 2;
+
+       if ( input_html_path ) { /*prevent 26249*/
+               /*      get preview text from html file */
+               if( (err = em_get_encoding_type_from_file_path(input_html_path, &encoding_type)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%s]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (stat(input_html_path, &st_buf) < 0)  {
+                       EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", input_html_path);
+                       err = EMAIL_ERROR_INVALID_MAIL;
+                       goto FINISH_OFF;
+               }
+
+               if (!(fp_html = fopen(input_html_path, "r")))   {
+                       EM_DEBUG_EXCEPTION("fopen failed [%s]", input_html_path);
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if (S_ISREG(st_buf.st_mode) && st_buf.st_size == 0) {
+                       EM_DEBUG_LOG("input_html_file is empty size");
+                       err = EMAIL_ERROR_EMPTY_FILE;
+                       goto FINISH_OFF;
+               }
+
+               if (!(local_preview_text = (char*)em_malloc(sizeof(char) * (st_buf.st_size + 1)))) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               byte_read = fread(local_preview_text, sizeof(char), st_buf.st_size, fp_html);
+
+               if(byte_read <= 0) { /*prevent 26249*/
+                       EM_SAFE_FREE(local_preview_text);
+                       if (ferror(fp_html)) {
+                               EM_DEBUG_EXCEPTION("fread failed [%s]", input_html_path);
+                               err = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+               else {
+                       if ( (err = emcore_strip_HTML(local_preview_text)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emcore_strip failed");
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       if ( !local_preview_text && input_plain_path) { /*prevent 26249*/
+               /*  get preview text from plain text file */
+               if( (err = em_get_encoding_type_from_file_path(input_plain_path, &encoding_type)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("em_get_encoding_type_from_file_path failed [%s]", err);
+                       goto FINISH_OFF;
+               }
+
+               memset(&st_buf, 0, sizeof(struct stat));
+               if (stat(input_plain_path, &st_buf) < 0)  {
+                       EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", input_plain_path);
+                       err = EMAIL_ERROR_INVALID_MAIL;
+                       goto FINISH_OFF;
+               }
+
+               if (!(fp_plain = fopen(input_plain_path, "r")))  {
+                       EM_DEBUG_EXCEPTION("fopen failed [%s]", input_plain_path);
+                       err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if (S_ISREG(st_buf.st_mode) && st_buf.st_size == 0) {
+                       EM_DEBUG_LOG("input_text_file is empty size");
+                       err = EMAIL_ERROR_EMPTY_FILE;
+                       goto FINISH_OFF;
+               }
+
+               if (!(local_preview_text = (char*)em_malloc(sizeof(char) * local_preview_buffer_length))) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       goto FINISH_OFF;
+               }
+
+               byte_read = fread(local_preview_text, sizeof(char), local_preview_buffer_length - 1, fp_plain);
+
+               if(byte_read <=0) { /*prevent 26249*/
+                       EM_SAFE_FREE(local_preview_text);
+                       err = EMAIL_ERROR_NULL_VALUE;
+                       if (ferror(fp_plain)) {
+                               EM_DEBUG_EXCEPTION("fread failed [%s]", input_plain_path);
+                               err = EMAIL_ERROR_SYSTEM_FAILURE;
+                       }
+                       goto FINISH_OFF;
+               }
+               reg_replace(local_preview_text, CR_STRING, " ");
+               reg_replace(local_preview_text, LF_STRING, " ");
+               reg_replace(local_preview_text, TAB_STRING, " ");
+       }
+
+       if(local_preview_text) {
+               em_trim_left(local_preview_text);
+               EM_DEBUG_LOG("local_preview_text : [%s]", local_preview_text);
+               if(encoding_type && strcasecmp(encoding_type, "UTF-8") != 0) {
+                       EM_DEBUG_LOG("encoding_type [%s]", encoding_type);
+                       utf8_encoded_string = (char*)g_convert (local_preview_text, -1, "UTF-8", encoding_type, &byte_read, &byte_written, &glib_error);
+
+                       if(utf8_encoded_string == NULL) {
+                               EM_DEBUG_EXCEPTION("g_convert failed : byte_read[%d], EM_SAFE_STRLEN : [%d]", byte_read, EM_SAFE_STRLEN(local_preview_text));
+                               EM_DEBUG_LOG("Error is G_CONVERT_ERROR_ILLEGAL_SEQUENCE");
+
+                               if (!g_error_matches (glib_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE)) {
+                                       EM_DEBUG_EXCEPTION("g_convert failed");
+                                       goto FINISH_OFF;
+                               }
+
+                               EM_DEBUG_LOG("Extract the preview text, again");
+
+                               utf8_encoded_string = (char *)g_convert(local_preview_text, byte_read, "UTF-8", encoding_type, &byte_read, &byte_written, &glib_error);
+                               if (utf8_encoded_string == NULL) {
+                                       EM_DEBUG_EXCEPTION("g_convert failed : byte_read[%d]", byte_read);
+                                       goto FINISH_OFF;
+                               }
+
+                       }
+                       EM_SAFE_FREE(local_preview_text);
+                       local_preview_text = utf8_encoded_string;
+               }
+       }
+
+FINISH_OFF:
+
+       if (local_preview_text != NULL)
+               *output_preview_buffer = EM_SAFE_STRDUP(local_preview_text);
+
+       EM_SAFE_FREE(local_preview_text);
+       EM_SAFE_FREE(encoding_type);
+
+       if (fp_html != NULL)
+               fclose(fp_html);
+
+       if (fp_plain != NULL)
+               fclose(fp_plain);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emcore_add_transaction_info(int mail_id, int handle , int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], handle[%d]", mail_id, handle);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE ;
+       em_transaction_info_type_t  *pTransinfo = NULL ;
+       em_transaction_info_type_t      *pTemp = NULL;
+
+       EM_DEBUG_LOG("g_transaction_info_list[%p]", g_transaction_info_list);
+       pTransinfo = g_transaction_info_list ;
+
+       if (!(pTemp = em_malloc(sizeof(em_transaction_info_type_t))))  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       pTemp->mail_id = mail_id ;
+       pTemp->handle = handle;
+
+       if (!pTransinfo) {
+               pTransinfo = pTemp ;
+               g_transaction_info_list = pTransinfo ;
+       }
+       else {
+               while (pTransinfo->next)
+                       pTransinfo = pTransinfo->next;
+               pTransinfo->next = pTemp;
+       }
+       ret = true ;
+
+FINISH_OFF:
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("g_transaction_info_list[%p]", g_transaction_info_list);
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_get_handle_by_mailId_from_transaction_info(int mail_id, int *pHandle)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], handle[%p]", mail_id, pHandle);
+
+       int ret = false;
+       em_transaction_info_type_t  *pTransinfo = NULL ;
+
+       if (g_transaction_info_list == NULL) {
+               EM_DEBUG_EXCEPTION("g_transaction_info_list NULL");
+               return false;
+       }
+       pTransinfo = g_transaction_info_list;
+
+       do {
+               EM_DEBUG_LOG("pTransinfo->mail_id[%d]", pTransinfo->mail_id);
+               if (pTransinfo->mail_id == mail_id) {
+                       *pHandle = pTransinfo->handle;
+                       ret = true;
+                       EM_DEBUG_LOG("*pHandle[%d]", *pHandle);
+                       break;
+               }
+               else
+                       pTransinfo = pTransinfo->next ;
+       }while (pTransinfo);
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_delete_transaction_info_by_mailId(int mail_id )
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d]", mail_id);
+
+       em_transaction_info_type_t  *pTransinfo ;
+       em_transaction_info_type_t *pTemp = NULL;
+
+       if (g_transaction_info_list == NULL) {
+               EM_DEBUG_EXCEPTION("g_transaction_info_list NULL");
+               return false;
+       }
+       pTransinfo = g_transaction_info_list;
+
+       EM_DEBUG_LOG("pTransinfo[%p]", pTransinfo);
+
+       do {
+               EM_DEBUG_LOG("pTransinfo->mail_id[%d]", pTransinfo->mail_id);
+               if (pTransinfo->mail_id == mail_id) {
+                       pTemp = pTransinfo->next ;
+                       if (!pTemp) {
+                               EM_SAFE_FREE(pTransinfo) ;
+                               g_transaction_info_list = NULL;
+                       }
+                       else {
+                               pTransinfo->mail_id = pTransinfo->next->mail_id;
+                               pTransinfo->handle = pTransinfo->next->handle ;
+                               pTransinfo->next = pTransinfo->next->next;
+
+                               EM_SAFE_FREE(pTemp);
+                       }
+                       break;
+               }
+               else {
+                       pTransinfo = pTransinfo->next ;
+               }
+
+       }while (pTransinfo);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+
+#include <regex.h>
+
+int reg_replace (char *input_source_text, char *input_old_pattern_string, char *input_new_string)
+{
+       EM_DEBUG_FUNC_BEGIN("input_source_text [%p], input_old_pattern_string [%p], input_new_string [%p]", input_source_text, input_old_pattern_string, input_new_string);
+       int         error_code = EMAIL_ERROR_NONE;
+       char       *pos = NULL;
+       int         so, n, nmatch, source_text_length, n_count = 1;
+       regmatch_t *pmatch = NULL;
+       regex_t     reg_pattern;
+
+       if(!input_source_text || !input_old_pattern_string || !input_new_string) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       source_text_length = EM_SAFE_STRLEN(input_source_text);
+
+       regcomp(&reg_pattern, input_old_pattern_string, REG_ICASE);
+
+       nmatch = reg_pattern.re_nsub + 1;
+
+       EM_DEBUG_LOG("nmatch [%d]", nmatch);
+
+       if(nmatch < 1) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_DATA");
+               error_code = EMAIL_ERROR_INVALID_DATA;
+               goto FINISH_OFF;
+       }
+
+       pmatch = (regmatch_t*)em_malloc(sizeof(regmatch_t) * nmatch);
+
+       if(pmatch == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               error_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for (pos = input_new_string; *pos ; pos++) {
+               if (*pos == '\\' && *(pos + 1) > '0' && *(pos + 1) <= '9') {
+
+                       so = pmatch[*(pos + 1) - 48].rm_so;
+                       n  = pmatch[*(pos + 1) - 48].rm_eo - so;
+
+                       EM_DEBUG_LOG("so [%d], n [%d]", so, n);
+
+                       if (so < 0 || EM_SAFE_STRLEN (input_new_string) + n - 1 > source_text_length)
+                               break;
+
+                       memmove (pos + n, pos + 2, EM_SAFE_STRLEN (pos) - 1);
+                       memmove (pos, input_source_text + so, n);
+                       pos = pos + n - 2;
+               }
+       }
+
+       for (pos = input_source_text; !regexec (&reg_pattern, pos, 1, pmatch, 0);) {
+               n = pmatch[0].rm_eo - pmatch[0].rm_so;
+               pos += pmatch[0].rm_so;
+
+               memmove (pos + EM_SAFE_STRLEN (input_new_string), pos + n, EM_SAFE_STRLEN (pos) - n + 1);
+               memmove (pos, input_new_string, EM_SAFE_STRLEN (input_new_string));
+               pos += EM_SAFE_STRLEN (input_new_string);
+               n_count++;
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(pmatch);
+       regfree (&reg_pattern);
+
+       EM_DEBUG_FUNC_END("error_code [%d]", error_code);
+       return error_code;
+}
+
+
+int emcore_strip_HTML(char *source_string)
+{
+       EM_DEBUG_FUNC_BEGIN("source_string [%p]", source_string);
+
+       int result = EMAIL_ERROR_NONE;
+
+       reg_replace(source_string, CR_STRING, " ");
+       reg_replace(source_string, LF_STRING, " ");
+       reg_replace(source_string, "<head[^>]*>", "<head>"); /*  "<()*head([^>])*>", "<head>" */
+       reg_replace(source_string, "<*/head>", "</head>");  /*  "(<()*(/)()*head()*>)", "</head>" */
+       reg_replace(source_string, "<head>.*</head>", ""); /*  "(<head>).*(</head>)", "" */
+       reg_replace(source_string, "<style[^>]*>.*</style>", "");
+
+       reg_replace(source_string, "<*/p>", " ");
+       reg_replace(source_string, "<br>", " ");
+
+       /*   "<[^>]*>", " */
+       reg_replace(source_string, "<[^>]*>", "");
+
+
+       /*   "&bull;", " *  */
+       /* reg_replace(source_string, "&bull;", " * "); */
+
+       /*   "&lsaquo;", "< */
+       /* reg_replace(source_string, "&lsaquo;", "<"); */
+
+       /*   "&rsaquo;", "> */
+       /* reg_replace(source_string, "&rsaquo;", ">"); */
+
+       /*   "&trade;", "(tm) */
+       /* reg_replace(source_string, "&trade;", "(tm)"); */
+
+       /*   "&frasl;", "/ */
+       /* reg_replace(source_string, "&frasl;", "/"); */
+
+       /*  "&lt;", "< */
+       reg_replace(source_string, "&lt;", "<");
+
+       /*  "&gt;", "> */
+       reg_replace(source_string, "&gt;", ">");
+
+       /*  "&copy;", "(c) */
+       /* reg_replace(source_string, "&copy;", "(c)"); */
+
+       /* "&quot;", "\' */
+       reg_replace(source_string, "&quot;", "\'");
+
+       /*  "&nbsp;", " */
+       reg_replace(source_string, "&nbsp;", " ");
+
+       reg_replace(source_string, "  ", " ");
+
+       EM_DEBUG_FUNC_END();
+
+       return result;
+}
+
+/*  emcore_send_noti_for_new_mail is not used currently because DBUS could not send very long message.*/
+/*  But I think it can be used to notify incomming new mail for replacing NOTI_MAIL_ADD with some modification(uid should be replaced with mail_id).  */
+/*  This notification is including addtional information comparing NOTI_MAIL_ADD. */
+/*  By this change, email application will be able to add email item without additional DB query.  */
+/*  It might improve performance of sync email.  */
+/*  kyuho.jo 2010-09-07 */
+
+INTERNAL_FUNC int emcore_send_noti_for_new_mail(int account_id, char *mailbox_name, char *subject, char *from, char *uid, char *datetime)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_name(%s) subject(%s), from(%s), uid(%s), datetime(%s)", mailbox_name, subject, from, uid, datetime);
+       int error_code = EMAIL_ERROR_NONE;
+       int param_length = 0;
+       char *param_string = NULL;
+
+       if (mailbox_name == NULL || subject == NULL || from == NULL || uid == NULL || datetime == NULL) {
+               error_code = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("Invalid parameter, mailbox_name(%p), subject(%p), from(%p), uid(%p), datetime(%p)", mailbox_name, subject, from, uid, datetime);
+               goto FINISH_OFF;
+       }
+
+       param_length = strlen(mailbox_name) + strlen(subject) + strlen(from) + strlen(uid) + strlen(datetime) + 5; /*prevent 34358*/
+
+       param_string = em_malloc(param_length);
+       if (param_string == NULL) {
+               error_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               EM_DEBUG_EXCEPTION("Memory allocation for 'param_string' is failed");
+               goto FINISH_OFF;
+       }
+
+       memset(param_string, 0x00, param_length);
+
+       SNPRINTF(param_string, param_length, "%s%c%s%c%s%c%s%c%s", mailbox_name, 0x01, subject, 0x01, from, 0x01, uid, 0x01, datetime);
+
+       if (emcore_notify_network_event(NOTI_DOWNLOAD_NEW_MAIL, account_id, param_string, 0, 0) == 0) { /*  failed */
+               error_code = EMAIL_ERROR_UNKNOWN;
+               EM_DEBUG_EXCEPTION("emcore_notify_network_event is failed");
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(param_string);
+       EM_DEBUG_FUNC_END();
+       return error_code;
+}
+
+#define MAX_TITLE_LENGTH 1024
+int emcore_update_notification_for_unread_mail(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("acccount_id[%d]", account_id);
+       int ret = false;
+       int i, account_count = 0;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *p_account_tbl = NULL;
+
+       if (!emstorage_get_account_list(&account_count, &p_account_tbl, true, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < account_count ; i++) {
+               if (emcore_add_notification(p_account_tbl[i].account_id, 0, EMAIL_ACTION_NUM) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_add_notification failed");
+                       continue;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (p_account_tbl)
+               emstorage_free_account(&p_account_tbl, account_count, NULL);
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_finalize_sync(int account_id, int *error)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], error [%p]", account_id, error);
+       int err = EMAIL_ERROR_NONE, ret = true, result_sync_status = SYNC_STATUS_FINISHED;
+
+       if ((err = emcore_update_sync_status_of_account(account_id, SET_TYPE_MINUS, SYNC_STATUS_SYNCING)) != EMAIL_ERROR_NONE)
+               EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+
+       if (!emstorage_get_sync_status_of_account(ALL_ACCOUNT, &result_sync_status, &err))
+               EM_DEBUG_EXCEPTION("emstorage_get_sync_status_of_account failed [%d]", err);
+
+       if (result_sync_status == SYNC_STATUS_HAVE_NEW_MAILS) {
+               if (!emcore_update_notification_for_unread_mail(ALL_ACCOUNT))
+                       EM_DEBUG_EXCEPTION("emcore_update_notification_for_unread_mail failed");
+
+               if (!emcore_display_unread_in_badge())
+                       EM_DEBUG_EXCEPTION("emcore_display_unread_in_badge failed");
+
+               emcore_start_alert();
+
+               if ((err = emcore_update_sync_status_of_account(account_id, SET_TYPE_MINUS, SYNC_STATUS_HAVE_NEW_MAILS)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_EXCEPTION("emcore_update_sync_status_of_account failed [%d]", err);
+       }
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_clear_all_notifications()
+{
+       int account_count = 0, i;
+       emstorage_account_tbl_t *account_list;
+       int error_code = EMAIL_ERROR_NONE;
+
+       if(!emstorage_get_account_list(&account_count, &account_list, true, false, &error_code)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed");
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < account_count; i++) {
+               emcore_delete_notification_by_account(account_list[i].account_id);
+       }
+
+FINISH_OFF:
+       if(account_count) {
+               emstorage_free_account(&account_list, account_count, NULL);
+       }
+
+       EM_DEBUG_FUNC_END("return[%d]", error_code);
+       return error_code;
+}
+
+#define EAS_EXECUTABLE_PATH "/usr/bin/eas-engine"
+
+INTERNAL_FUNC int emcore_delete_notification_by_account(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d]", account_id);
+       int error_code = EMAIL_ERROR_NONE;
+       int private_id = 0;
+       char vconf_private_id[MAX_PATH] = {0, };
+
+       SNPRINTF(vconf_private_id, sizeof(vconf_private_id), "%s/%d", VCONF_KEY_NOTI_PRIVATE_ID, account_id);
+       if (vconf_get_int(vconf_private_id, &private_id) != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+       }
+       EM_DEBUG_FUNC_END();
+       return error_code;
+}
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+
+/**
+ * @fn emcore_convert_to_uid_range_set(email_id_set_t* id_set, int id_set_count, email_uid_range_set **uid_range_set, int range_len, int *err_code)
+ * Prepare a linked list of uid ranges with each node having a uid_range and lowest and highest uid in it.
+ *
+ *@author                                      h.gahlaut@samsung.com
+ * @param[in] id_set                   Specifies the array of mail_id and corresponding server_mail_id sorted by server_mail_ids in ascending order
+ * @param[in] id_set_count             Specifies the no. of cells in id_set array i.e. no. of sets of mail_ids and server_mail_ids
+ * @param[in] range_len                Specifies the maximum length of string of range allowed.
+ * @param[out] uid_range_set   Returns the uid_ranges formed in the form of a linked list with head stored in uid_range_set pointer
+ * @param[out] err_code                Returns the error code.
+ * @remarks                                    An example of a uid_range formed is 2:6,8,10,14:15,89,
+ *                                                     While using it the caller should remove the ending, (comma)
+ * @return This function returns true on success or false on failure.
+ */
+
+INTERNAL_FUNC int emcore_convert_to_uid_range_set(email_id_set_t *id_set, int id_set_count, email_uid_range_set **uid_range_set, int range_len, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (NULL == id_set || id_set_count  <= 0 || NULL == uid_range_set) {
+               EM_DEBUG_EXCEPTION(" Invalid Parameter id_set[%p] id_set_count[%d] uid_range_set[%p]", id_set, id_set_count, uid_range_set);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       int i = 0;
+       unsigned long current_uid = 0;
+       unsigned long first_uid = 0;
+       unsigned long last_uid = 0;
+       const int max_subset_string_size = MAX_SUBSET_STRING_SIZE;
+       char subset_string[MAX_SUBSET_STRING_SIZE] = {0,};
+       email_uid_range_set *current_node = NULL;       /* current_node denotes the current node under processing in the linked list of uid_range_set that is to be formed*/
+
+       if (range_len < (max_subset_string_size + 1))           /* 1 for ending NULL character */ {
+               EM_DEBUG_EXCEPTION(" Invalid Parameter range_len[%d]", range_len);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("id set count[%d] range_len[%d]", id_set_count, range_len);
+
+       do {
+               first_uid = last_uid = current_uid = id_set[i].server_mail_id;
+               /* Start subset string by putting first server mail id in it from id_set*/
+               memset(subset_string, 0x00, max_subset_string_size);
+               SNPRINTF(subset_string, max_subset_string_size, "%lu", first_uid);
+               ++i;
+
+               /* Check if only one server mail id was left in id_set */
+               if (i >= id_set_count) {
+                       /* No more server mail id left in id_set */
+                       if (false == emcore_append_subset_string_to_uid_range(subset_string, &current_node, uid_range_set, range_len, first_uid, last_uid)) {
+                               EM_DEBUG_EXCEPTION("emcore_append_subset_string_to_uid_range failed");
+                               goto FINISH_OFF;
+                       }
+                       break;
+               }
+               else {
+                       /* More server mail id are present in id_set. Find out if first:last_uid is to be formed or only first_uid will be subset string */
+                       do {
+                               current_uid = id_set[i].server_mail_id;
+                               if (current_uid == (last_uid + 1)) {
+                                       last_uid = current_uid;
+                                       ++i;
+                               }
+                               else {
+                                       memset(subset_string, 0x00, max_subset_string_size);
+                                       if (first_uid != last_uid)      /* Form subset string by first_uid:last_uid */
+                                               SNPRINTF(subset_string, max_subset_string_size, "%lu:%lu", first_uid, last_uid);
+                                       else    /* Form subset string by first_uid */
+                                               SNPRINTF(subset_string, max_subset_string_size, "%lu", first_uid);
+
+                                       if (false == emcore_append_subset_string_to_uid_range(subset_string, &current_node, uid_range_set, range_len, first_uid, last_uid)) {
+                                               EM_DEBUG_EXCEPTION("emcore_append_subset_string_to_uid_range failed");
+                                               goto FINISH_OFF;
+                                       }
+                                       /* To Start formation of new subset string break out of inner loop */
+                                       break;
+                               }
+
+                       } while (i < id_set_count);
+
+                       /* Flow comes here in two cases :
+                       1. id_set ended and has continuous numbers at end of id_set so form subset string by first_uid:last_uid . in this  case last_uid == current_uid
+                       2. due to break statement */
+
+                       if (last_uid == current_uid) {
+                               /* Case 1 */
+
+                               memset(subset_string, 0x00, max_subset_string_size);
+                               SNPRINTF(subset_string, max_subset_string_size, "%lu:%lu", first_uid, last_uid);
+
+                               if (false == emcore_append_subset_string_to_uid_range(subset_string, &current_node, uid_range_set, range_len, first_uid, last_uid)) {
+                                       EM_DEBUG_EXCEPTION("emcore_append_subset_string_to_uid_range failed");
+                                       goto FINISH_OFF;
+                               }
+                       }
+                       else {
+                               /* Case 2: Do Nothing */
+                       }
+
+               }
+       } while (i < id_set_count);
+
+       ret = true;
+
+FINISH_OFF:
+       if (NULL != err_code)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+
+}
+
+/**
+ * @fn emcore_append_subset_string_to_uid_range(char *subset_string, email_uid_range_set **uid_range_set, int range_len, unsigned long luid, unsigned long huid)
+ * Appends the subset_string to uid range if the uid range has not exceeded maximum length(range_len), otherwise creates a new node in linked list of uid range set
+ * and stores the subset_string in its uid_range. Also sets the lowest and highest uids for the corresponsing uid_range
+ *
+ * @author                                     h.gahlaut@samsung.com
+ * @param[in] subset_string    Specifies the subset string to be appended. A subset string can be like X:Y or X where X and Y are uids.
+ * @param[in] range_len                Specifies the maximum length of range string allowed.
+ * @param[in] luid                     Specifies the lowest uid in subset string
+ * @param[in] huid                     Specifies the highest uid in subset string
+ * @param[out] uid_range_set   Returns the uid_ranges formed in the form of a linked list with head stored in uid_range_set pointer
+ * @param[out] err_code                Returns the error code.
+ * @remarks
+ * @return This function returns true on success or false on failure.
+ */
+
+int emcore_append_subset_string_to_uid_range(char *subset_string, email_uid_range_set **current_node_adr, email_uid_range_set **uid_range_set, int range_len, unsigned long luid, unsigned long huid)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       email_uid_range_set *current_node = NULL;
+
+       if (NULL == (*uid_range_set)) {
+               /*This happens only once when list  creation starts. Head Node is allocated */
+               current_node = (email_uid_range_set *)em_malloc(sizeof(email_uid_range_set));
+               if (NULL == current_node) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       return false;
+               }
+
+               current_node->uid_range = (char *)em_malloc(range_len);
+
+               if (NULL == current_node->uid_range) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       EM_SAFE_FREE(current_node);
+                       return false;
+               }
+
+               SNPRINTF(current_node->uid_range, range_len, "%s,", subset_string);
+
+               current_node->lowest_uid = luid;
+               current_node->highest_uid = huid;
+               (*uid_range_set) = current_node;
+
+               (*current_node_adr) = current_node;
+
+       }
+       else {
+               /* Apart from first call to this function flow will always come here */
+               current_node = (*current_node_adr);
+               int len_sub_string = EM_SAFE_STRLEN(subset_string);
+               int space_left_in_buffer = range_len - EM_SAFE_STRLEN(current_node->uid_range);
+
+               if ((len_sub_string + 1 + 1) <= space_left_in_buffer)   /* 1 for comma + 1 for ending null character */ {
+                       SNPRINTF(current_node->uid_range + EM_SAFE_STRLEN(current_node->uid_range), space_left_in_buffer, "%s,", subset_string);
+                       current_node->highest_uid = huid;
+               }
+               else {
+                       /* No more space left in uid_range string.If continued on it, it will exceeded max size of range_len */
+                       /* Allocate new node in Uid Range set */
+                       email_uid_range_set *new_node = NULL;
+
+                       new_node = (email_uid_range_set *)em_malloc(sizeof(email_uid_range_set));
+
+                       if (NULL == new_node) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               return false;
+                       }
+
+                       /* Allocate uid_range of new node */
+
+                       new_node->uid_range =  (char *)em_malloc(range_len);
+
+                       if (NULL == new_node->uid_range) {
+                               EM_DEBUG_EXCEPTION("em_malloc failed");
+                               EM_SAFE_FREE(new_node);
+                               return false;
+                       }
+
+                       SNPRINTF(new_node->uid_range, range_len, "%s, ", subset_string);
+
+                       new_node->lowest_uid = luid;
+                       new_node->highest_uid = huid;
+
+                       current_node->next = new_node;
+
+                       (*current_node_adr) = new_node;
+               }
+       }
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+/**
+ * void emcore_free_uid_range_set(email_uid_range_set **uid_range_head)
+ * Frees the linked list of uid ranges
+ *
+ * @author                                     h.gahlaut@samsung.com
+ * @param[in] uid_range_head   Head pointer of linked list of uid ranges
+ * @remarks
+ * @return This function does not return anything.
+ */
+
+INTERNAL_FUNC
+void emcore_free_uid_range_set(email_uid_range_set **uid_range_set)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       email_uid_range_set *current_node = NULL;
+       email_uid_range_set *uid_range_head = NULL;
+
+       current_node = uid_range_head = (*uid_range_set);       /* Make the current node and head ptr point to starting of  uid_range_set */
+
+       while (current_node) {
+               uid_range_head = current_node->next;            /* Move the head ptr to next node*/
+
+               EM_SAFE_FREE(current_node->uid_range);
+               EM_SAFE_FREE(current_node);                             /* Free the current node */
+
+               current_node = uid_range_head;                  /* Make the current node point to head ptr */
+       }
+
+       (*uid_range_set) = NULL;
+       EM_DEBUG_FUNC_END();
+}
+
+
+/**
+ * @fn emcore_form_comma_separated_strings(int numbers[], int num_count, int max_string_len, char *** strings, int *string_count, int *err_code)
+ * Forms comma separated strings of a give max_string_len from an array of numbers
+ *
+ * @author                                     h.gahlaut@samsung.com
+ * @param[in] numbers                  Specifies the array of numbers to be converted into comma separated strings.
+ * @param[in] num_count                Specifies the count of numbers in numbers array.
+ * @param[in] max_string_len   Specifies the maximum length of comma separated strings that are to be formed.
+ * @param[out] strings                 Returns the base address of a double dimension array which stores the strings.
+ * @param[out] string_count            Returns the number of strings formed.
+ * @param[out] err_code                Returns the error code.
+ * @remarks                                    If Input to the function is five numbers like 2755 2754 2748 2749 2750 and a given max_string_len is 20.
+ *                                                     Then this function will form two comma separated strings as follows -
+ *                                                     "2755, 2754, 2748"
+ *                                                     "2749, 2750"
+ * @return This function returns true on success or false on failure.
+ */
+
+INTERNAL_FUNC int emcore_form_comma_separated_strings(int numbers[], int num_count, int max_string_len, char *** strings, int *string_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+
+       char **string_list = NULL;
+       int num_of_strings = 0;
+       int i = 0;
+       int j =0;
+       char num[MAX_INTEGER_LENGTH + 1] = {0, };
+       int num_len = 0;
+       int space_in_buffer = 0;
+       int len_of_string_formed = 0;
+
+       if (NULL == numbers || num_count <= 0 || \
+               max_string_len < (MAX_INTEGER_LENGTH + 2)|| NULL == strings || NULL == string_count)                    /*  32767, is the highest integer possible in string.This requires 7 bytes of storage in character type array (1 byte for ending NULL and 1 byte for ending comma) so max_string_len should not be less than worst case possible.  */ {
+               EM_DEBUG_EXCEPTION("Invalid Parameter numbers[%p] num_count [%d] max_string_len [%d] strings [%p] string_count[%p]", \
+                       numbers, num_count, max_string_len, strings, string_count);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("num_count [%d] max_string_len [%d]", num_count, max_string_len);
+
+       string_list = em_malloc(sizeof(char *));
+
+       if (NULL == string_list) {
+               EM_DEBUG_EXCEPTION("em_malloc failed ");
+               goto FINISH_OFF;
+       }
+
+       string_list[num_of_strings] = em_malloc(max_string_len);
+
+       if (NULL == string_list[num_of_strings]) {
+               EM_DEBUG_EXCEPTION("em_malloc failed ");
+               goto FINISH_OFF;
+       }
+
+       ++num_of_strings;
+       space_in_buffer = max_string_len;
+
+       for (j = 0; j < num_count;++j) {
+               memset(num, 0x00, MAX_INTEGER_LENGTH + 1);
+               SNPRINTF(num, MAX_INTEGER_LENGTH + 1, "%d", numbers[j]);
+
+               num_len = EM_SAFE_STRLEN(num);
+
+               len_of_string_formed = EM_SAFE_STRLEN(string_list[num_of_strings - 1]);
+
+               space_in_buffer = max_string_len - len_of_string_formed ;
+
+               if (space_in_buffer >= (num_len+1+1))                   /*  1 for comma and 1 for ending NULL */ {
+                       SNPRINTF(string_list[num_of_strings - 1] + len_of_string_formed, max_string_len, "%d,", numbers[j]);
+               }
+               else {  /*  Removing comma at end of string  */
+                       string_list[num_of_strings - 1][len_of_string_formed-1] = '\0';
+                       char **temp = NULL;
+                       temp = (char **)realloc(string_list, sizeof(char *) * (num_of_strings + 1));    /*  Allocate new buffer to store a pointer to a new string */
+
+                       if (NULL == temp) {
+                               EM_DEBUG_EXCEPTION("realloc failed");
+                               goto FINISH_OFF;
+                       }
+
+                       memset(temp + num_of_strings, 0X00, sizeof(char *));
+
+                       string_list = temp;
+                       temp = NULL;
+                       string_list[num_of_strings] = em_malloc(max_string_len);/*  Allocate new buffer to store the string */
+
+                       if (NULL == string_list[num_of_strings]) {
+                               EM_DEBUG_EXCEPTION(" em_malloc failed ");
+                               goto FINISH_OFF;
+                       }
+                       ++num_of_strings;
+                       SNPRINTF(string_list[num_of_strings - 1] , max_string_len, "%d,", numbers[j]);/*  Start making new string */
+               }
+       }
+
+       /*  Removing comma at end of string  */
+       len_of_string_formed = EM_SAFE_STRLEN(string_list[num_of_strings - 1]);
+       string_list[num_of_strings - 1][len_of_string_formed-1] = '\0';
+       ret = true;
+
+FINISH_OFF:
+
+       if (false == ret)
+               emcore_free_comma_separated_strings(&string_list, &num_of_strings);
+
+       if (true == ret) {
+               for (i = 0; i < num_of_strings;++i)
+                       EM_DEBUG_LOG("%s", string_list[i]);
+               *strings = string_list;
+               *string_count = num_of_strings;
+       }
+
+
+       if (NULL != err_code)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+/**
+ * @fn emcore_free_comma_separated_strings(char *** string_list, int *string_count)
+ * Frees the double dimensional array of strings.
+ *
+ * @author                                     h.gahlaut@samsung.com
+ * @param[in] uid_range_head   Address of base address of double dimensional array of strings.
+ * @param[in] string_count             Address of variable holding the count of strings.
+ * @remarks
+ * @return This function does not return anything.
+ */
+INTERNAL_FUNC void emcore_free_comma_separated_strings(char *** string_list, int *string_count)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int i = 0;
+       char **str_list = NULL;
+       int count = 0;
+
+       if (NULL != string_list) {
+               str_list = *string_list;
+
+               if (0 != *string_count) {
+                       count = *string_count;
+                       for (i = 0; i < count; ++i)
+                               EM_SAFE_FREE(str_list[i]);
+               }
+
+               EM_SAFE_FREE(str_list);
+               *string_list = NULL;    /*  This makes the pointer to be freed as NULL in calling function and saves it from being a dangling pointer for sometime in calling function */
+               *string_count = 0;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+
+#endif
+
+
+
+
+int emcore_make_attachment_file_name_with_extension(char *source_file_name, char *sub_type, char *result_file_name, int result_file_name_buffer_length, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("source_file_name[%s], sub_type[%s], result_file_name_buffer_length[%d] ", source_file_name, sub_type, result_file_name_buffer_length);
+       int ret = false, err = EMAIL_ERROR_NONE;
+       char *extcheck = NULL;
+       char attachment_file_name[MAX_PATH + 1] = { 0, };
+
+       if (!source_file_name || !result_file_name) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err  = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       strncpy(attachment_file_name, source_file_name, MAX_PATH);
+       extcheck = strchr(attachment_file_name, '.');
+
+       if (extcheck)
+               EM_DEBUG_LOG("Extension Exist in the Attachment [%s] ", extcheck);
+       else  { /* No extension attached, So add the Extension based on the subtype */
+               if (sub_type) {
+                       strcat(attachment_file_name, ".");
+                       strcat(attachment_file_name, sub_type);
+                       EM_DEBUG_LOG("attachment_file_name with extension[%s] ", attachment_file_name);
+               }
+               else
+                       EM_DEBUG_LOG("UnKnown Extesnsion");
+
+       }
+       memset(result_file_name, 0 , result_file_name_buffer_length);
+       EM_SAFE_STRNCPY(result_file_name, attachment_file_name, result_file_name_buffer_length - 1);
+       EM_DEBUG_LOG("*result_file_name[%s]", result_file_name);
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+INTERNAL_FUNC int emcore_add_activity(emstorage_activity_tbl_t *new_activity, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       EM_DEBUG_LOG("\t new_activity[%p], err_code[%p]", new_activity, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!new_activity) {
+               EM_DEBUG_LOG("\t new_activity[%p]\n", new_activity);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       if (!emstorage_add_activity(new_activity, false, &err)) {
+               EM_DEBUG_LOG("\t emstorage_add_activity falied - %d\n", err);
+
+               goto FINISH_OFF;
+       }
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_delete_activity(emstorage_activity_tbl_t *activity, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       EM_DEBUG_LOG("\t new_activity[%p], err_code[%p]", activity, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       if (!activity) {
+               EM_DEBUG_LOG("\t new_activity[%p]\n", activity);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       if (!emstorage_delete_local_activity(activity, true, &err)) {
+               EM_DEBUG_LOG("\t emstorage_delete_local_activity falied - %d\n", err);
+
+               goto FINISH_OFF;
+       }
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+INTERNAL_FUNC int emcore_get_next_activity_id(int *activity_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (NULL == activity_id)
+       {
+               EM_DEBUG_EXCEPTION("\t activity_id[%p]", activity_id);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (false == emstorage_get_next_activity_id(activity_id, &err)) {
+               EM_DEBUG_LOG("\t emstorage_get_next_activity_id failed - %d\n", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+       FINISH_OFF:
+       if (NULL != err_code) {
+               *err_code = err;
+       }
+
+       return ret;
+
+}
+
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+
+
+INTERNAL_FUNC void emcore_free_rule(email_rule_t* rule)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!rule)
+               return;
+
+       EM_SAFE_FREE(rule->value);
+
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC int emcore_search_string_from_file(char *file_path, char *search_string, int *result)
+{
+       EM_DEBUG_FUNC_BEGIN("file_path : [%s], search_string : [%s]", file_path, search_string);
+       int error = EMAIL_ERROR_NONE;
+       int file_size = 0;
+       int p_result = false;
+       FILE *fp = NULL;
+       char *buf = NULL;
+       char *stripped = NULL;
+
+       if (!search_string || !file_path || !result) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               return error;
+       }
+
+       fp = fopen(file_path, "r");
+       if (fp == NULL) {
+               EM_DEBUG_EXCEPTION("fopen failed");
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_file_size(file_path, &file_size, &error)) {
+               EM_DEBUG_EXCEPTION("emcore_get_file_size failed");
+               goto FINISH_OFF;
+       }
+
+       buf = em_malloc(file_size);
+       if (buf == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (fread(buf, sizeof(char), file_size, fp) != file_size) {
+               EM_DEBUG_EXCEPTION("Get the data from file : failed");
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       /*prevent 35586*/
+       stripped = em_replace_all_string(buf, CRLF_STRING, "");
+       if (strstr(stripped, search_string))
+               p_result = true;
+
+FINISH_OFF:
+       if(!p_result)
+               EM_DEBUG_LOG("Search string[%s] not found",search_string);
+
+       *result = p_result;
+
+       if (fp)
+               fclose(fp);
+
+       EM_SAFE_FREE(buf);
+       EM_SAFE_FREE(stripped);  /*prevent 35586*/
+
+       EM_DEBUG_FUNC_END("error:[%d]", error);
+       return error;
+}
+/* EOF */
diff --git a/email-core/email-device/email-device.c b/email-core/email-device/email-device.c
new file mode 100755 (executable)
index 0000000..9af7104
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <sys/types.h>
+
+#include "email-device.h"
+#include "email-debug-log.h"
+
+
+
+INTERNAL_FUNC int emdevice_set_sleep_on_off(int on, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN("on[%d], err_code[%p]", on, error_code);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+INTERNAL_FUNC int emdevice_set_dimming_on_off(int on, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN("on[%d], err_code[%p]", on, error_code);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
diff --git a/email-core/email-device/include/email-device.h b/email-core/email-device/include/email-device.h
new file mode 100755 (executable)
index 0000000..b4d056a
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-device.h
+ * Desc :  email-core Device Library Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2012.02.20  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_DEVICE_H__
+#define __EMAIL_DEVICE_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include "email-internal-types.h"
+
+INTERNAL_FUNC int emdevice_set_sleep_on_off(int on, int *error_code);
+INTERNAL_FUNC int emdevice_set_dimming_on_off(int on, int *error_code);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* __EMAIL_DEVICE_H__ */
diff --git a/email-core/email-network/email-network.c b/email-core/email-network/email-network.c
new file mode 100755 (executable)
index 0000000..5bb3783
--- /dev/null
@@ -0,0 +1,490 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File: email-network.c
+ * Desc: Data network interface
+ *
+ * Auth:
+ *
+ * History:
+ *     2006.11.17 : created
+ *****************************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <signal.h>
+#include <netdb.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <email-storage.h> 
+#include <vconf.h>
+#include "glib.h"
+
+#include "lnx_inc.h"
+#include "utf8aux.h"
+#include "c-client.h"
+#include "email-debug-log.h"
+#include "email-types.h"
+#include "email-core-utils.h" 
+#include "email-core-mailbox.h"
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+#include "email-core-event.h"
+#endif
+
+/* _get_network_status - Get the data network status from vconf */
+static int _get_network_status(int *network_status)
+{
+       EM_DEBUG_FUNC_BEGIN("network_status [%p]", network_status);
+
+       int value = 0;
+
+       if(!network_status) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if (vconf_get_int(VCONFKEY_NETWORK_STATUS, &value)) {
+               EM_DEBUG_EXCEPTION("Failed vconf_get_int [VCONFKEY_NETWORK_STATUS]");
+               return EMAIL_ERROR_SYSTEM_FAILURE;
+       }
+
+       *network_status = value;
+
+       EM_DEBUG_FUNC_END("network_status [%d]", value);
+       return EMAIL_ERROR_NONE;
+}
+
+/* Check code for SIM status */
+static int  _get_sim_status(int *sim_status)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int value;
+
+       if(!sim_status) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if (vconf_get_int(VCONFKEY_TELEPHONY_SIM_SLOT, &value)  != 0) {
+               EM_DEBUG_EXCEPTION("Failed vconf_get_int [VCONFKEY_TELEPHONY_SIM_SLOT]");
+               return EMAIL_ERROR_SYSTEM_FAILURE;
+       }
+
+       *sim_status = value;
+
+       EM_DEBUG_FUNC_END("status[%d]", value);
+       return EMAIL_ERROR_NONE;
+}
+
+static int _get_wifi_status(int *wifi_status)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int value;
+
+       if(!wifi_status) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if (vconf_get_int(VCONFKEY_WIFI_STATE, &value)  != 0) {
+               EM_DEBUG_EXCEPTION("vconf_get_int failed");
+               return EMAIL_ERROR_SYSTEM_FAILURE;
+       }
+
+       *wifi_status = value;
+
+       EM_DEBUG_FUNC_END("status[%d]", *wifi_status);
+       return EMAIL_ERROR_NONE;
+}
+
+
+INTERNAL_FUNC int emnetwork_check_network_status(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int network_status = 0;
+       int sim_status     = VCONFKEY_TELEPHONY_SIM_UNKNOWN;
+       int wifi_status    = 0;
+       int err            = EMAIL_ERROR_NONE;
+       int ret            = false;
+
+       if ( (err = _get_network_status(&network_status)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_get_network_status failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(network_status == 0) {
+               EM_DEBUG_LOG("VCONFKEY_NETWORK_STATUS is 0");
+
+               if ( (err = _get_wifi_status(&wifi_status)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("_get_wifi_status failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (wifi_status == 0) {
+                       EM_DEBUG_LOG("Furthermore, WIFI is off");
+
+                       if ( (err = _get_sim_status(&sim_status)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("_get_sim_status failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if (sim_status != VCONFKEY_TELEPHONY_SIM_INSERTED) {
+                               EM_DEBUG_EXCEPTION("EMAIL_ERROR_NO_SIM_INSERTED");
+                               err = EMAIL_ERROR_NO_SIM_INSERTED;
+                               goto FINISH_OFF;
+                       }
+
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_NETWORK_NOT_AVAILABLE");
+                       err = EMAIL_ERROR_NETWORK_NOT_AVAILABLE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       EM_DEBUG_LOG("Data Network Mode is ON");
+       ret = true;
+
+FINISH_OFF: 
+
+       emcore_set_network_error(err);
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+
+       return ret;
+}
+
+INTERNAL_FUNC long emnetwork_callback_ssl_cert_query(char *reason, char *host, char *cert)
+{
+       EM_DEBUG_FUNC_BEGIN("reason[%s], host[%s], cert[%s]", reason, host, cert);
+       int ret = 1;
+
+       /*  FIXME : add user interface for Accept or Reject */
+       /*  1:Accept - ignore this certificate error */
+       /*  0:Reject - stop ssl connection */
+       ret = 1;
+
+       EM_DEBUG_FUNC_END("ret[%s]", ret ? "ignore error" : "stop connection");
+       return ret;
+}
+
+/* ------ socket read/write handle ---------------------------------------- */
+int _g_canceled = 0;
+/*  TCPSTREAM = SENDSTREAM->netstream->stream; socket-id = TCPSTREAM->tcpsi, tcpso; */
+/*  sockid_in  = ((TCPSTREAM*)send_stream->netstream->stream)->tcpsi; */
+/*  sockid_out = ((TCPSTREAM*)send_stream->netstream->stream)->tcpso; */
+
+INTERNAL_FUNC long tcp_getbuffer_lnx(TCPSTREAM *stream, unsigned long size, char *s)
+{
+       struct timeval tmout;
+       fd_set readfds;
+       int nleave, nread, sret, sockid, maxfd;
+       char *p = s;
+       int max_timeout = 0;
+       sockid = stream->tcpsi;
+       maxfd = sockid + 1;
+/* EM_DEBUG_LOG("start sockid %d", sockid);    */
+       if (sockid < 0) return 0;
+
+       if (stream->ictr > 0) {
+               int copy_sz;
+               if (stream->ictr >= size) {
+                       memcpy(p, stream->iptr, size);
+                       copy_sz = size;
+               }
+               else {
+                       memcpy(p, stream->iptr, stream->ictr);
+                       copy_sz = stream->ictr;
+               }
+               p += copy_sz;
+               nleave = size - copy_sz;
+               stream->iptr += copy_sz;
+               stream->ictr -= copy_sz;
+
+               if (nleave <= 0) {
+                       *p = '\0';
+                       /* EM_DEBUG_LOG("end"); */
+                       return 1;
+               }
+       }
+       else {
+               nleave = size;
+       }
+
+       while (nleave > 0) {
+#ifdef TEST_CANCEL_JOB
+               if (!emcore_check_thread_status()) {
+                       EM_DEBUG_EXCEPTION("thread canceled");
+                       tcp_abort(stream);
+                       goto JOB_CANCEL;
+               }
+#endif
+               /* if (_g_canceled){ */
+               /*      EM_DEBUG_LOG1("thread canceled\n"); */
+               /*      tcp_abort(stream); */
+               /*      return 0; */
+               /* } */
+
+               tmout.tv_usec = 0;
+               tmout.tv_sec = 1;
+               FD_ZERO(&readfds);
+               FD_SET(sockid, &readfds);
+
+               sret = select(maxfd, &readfds, NULL, NULL, &tmout);
+               if (sret < 0) {
+                       EM_DEBUG_EXCEPTION("select error[%d]\n", errno);
+                       tcp_abort(stream);
+                       return 0;
+               }
+               else if (!sret) {
+                       if (max_timeout >= 5) {
+                               EM_DEBUG_EXCEPTION("max select timeout %d", max_timeout);
+                               emcore_set_network_error(EMAIL_ERROR_NO_RESPONSE);
+                               return 0;
+                       }
+                       EM_DEBUG_EXCEPTION("%d select timeout", max_timeout);
+                       ++max_timeout;
+                       continue;
+               }
+
+               nread = read(sockid, p, nleave);
+               if (nread < 0) {
+                       EM_DEBUG_EXCEPTION("socket read error");
+/*                     if (errno == EINTR) continue; */
+                       tcp_abort(stream);
+                       return 0;
+               }
+
+               if (!nread) {
+                       EM_DEBUG_EXCEPTION("socket read no data");
+                       tcp_abort(stream);
+                       return 0;
+               }
+
+               p += nread;
+               nleave -= nread;
+       }
+
+       *p = '\0';
+
+       if (_g_canceled) {
+               EM_DEBUG_EXCEPTION("thread canceled");
+               tcp_abort(stream);
+               return 0;
+       }
+
+       return 1;
+/*     EM_DEBUG_LOG("end"); */
+#ifdef TEST_CANCEL_JOB
+JOB_CANCEL:
+       return 0;
+#endif
+}
+
+long tcp_getdata_lnx(TCPSTREAM *stream)
+{
+       struct timeval tmout;
+       fd_set readfds;
+       int nread, sret, sockid, maxfd;
+       int max_timeout = 0;
+       
+       sockid = stream->tcpsi;
+       maxfd = sockid + 1;
+       
+       /* EM_DEBUG_LOG("start sockid %d", sockid);     */
+       if (sockid < 0) return false;
+       
+       while (stream->ictr < 1)  {
+#ifdef TEST_CANCEL_JOB
+               if (!emcore_check_thread_status())  {
+                       EM_DEBUG_EXCEPTION("thread canceled...");
+                       tcp_abort(stream);
+                       goto JOB_CANCEL;
+               }
+#endif
+               
+               /* if (_g_canceled){ */
+               /*      EM_DEBUG_LOG1("thread canceled\n"); */
+               /*      tcp_abort(stream); */
+               /*      return 0; */
+               /* } */
+               
+               tmout.tv_usec = 0;/* 1000*10; */
+               tmout.tv_sec = 1;
+               
+               FD_ZERO(&readfds);
+               FD_SET(sockid, &readfds);
+               
+               sret = select(maxfd, &readfds, NULL, NULL, &tmout);
+               
+               if (sret < 0) {
+                       EM_DEBUG_LOG("select error[%d]", errno);
+                       
+                       tcp_abort(stream);
+                       return false;
+               }
+               else if (!sret) {
+                       if (max_timeout >= 50) {
+                               EM_DEBUG_EXCEPTION("max select timeout %d", max_timeout);
+                               
+                               emcore_set_network_error(EMAIL_ERROR_NO_RESPONSE);
+                               return false;
+                       }
+                       
+                       EM_DEBUG_EXCEPTION("%d select timeout", max_timeout);
+                       
+                       ++max_timeout;
+                       continue;
+               }
+               
+               if ((nread = read(sockid, stream->ibuf, BUFLEN)) < 0) {
+                       EM_DEBUG_EXCEPTION("socket read failed...");
+                       
+                       emcore_set_network_error(EMAIL_ERROR_SOCKET_FAILURE);
+                       
+                       /* if (errno == EINTR) contine; */
+                       tcp_abort(stream);
+                       return false;
+               }
+               
+               if (!nread) {
+                       EM_DEBUG_EXCEPTION("socket read no data...");
+                       
+                       emcore_set_network_error(EMAIL_ERROR_INVALID_RESPONSE);
+                       
+                       tcp_abort(stream);
+                       return false;
+               }
+               
+               stream->ictr = nread;
+               stream->iptr = stream->ibuf;
+       }
+       
+       if (_g_canceled) {
+               EM_DEBUG_EXCEPTION("\t thread canceled...\n");
+               
+               tcp_abort(stream);
+               return false;
+       }
+       
+       /* EM_DEBUG_LOG("end"); */
+       return true;
+       
+#ifdef TEST_CANCEL_JOB
+JOB_CANCEL:
+       return false;
+#endif
+}
+
+INTERNAL_FUNC long tcp_sout_lnx(TCPSTREAM *stream, char *string, unsigned long size)
+{
+       struct timeval tmout;
+       fd_set writefds;
+       int sret, nwrite, maxfd, sockid;
+       int max_timeout = 0;
+       
+       sockid = stream->tcpso;
+       maxfd = sockid + 1;
+/* EM_DEBUG_LOG("start sockid %d", sockid); */
+       if (sockid < 0) return 0;
+
+       while (size > 0) {
+#ifdef TEST_CANCEL_JOB
+               if (!emcore_check_thread_status()) {
+                       EM_DEBUG_EXCEPTION("thread canceled");
+                       tcp_abort(stream);
+                       goto JOB_CANCEL;
+               }
+#endif
+               /* if (_g_canceled){ */
+               /*      EM_DEBUG_LOG1("thread canceled"); */
+               /*      tcp_abort(stream); */
+               /*      return 0; */
+               /* } */
+
+               tmout.tv_usec = 0;
+               tmout.tv_sec = 1;
+               FD_ZERO(&writefds);
+               FD_SET(sockid, &writefds);
+
+               sret = select(maxfd, NULL, &writefds, NULL, &tmout);
+               if (sret < 0) {
+                       EM_DEBUG_LOG("select error[%d]", errno);
+                       tcp_abort(stream);
+                       return 0;
+               }
+               else if (!sret) {
+                       if (max_timeout >= 50) {
+                               EM_DEBUG_EXCEPTION("max select timeout %d", max_timeout);
+                               emcore_set_network_error(EMAIL_ERROR_NO_RESPONSE);
+                               return 0;
+                       }
+                       EM_DEBUG_EXCEPTION("%d select timeout", max_timeout);
+                       ++max_timeout;
+                       continue;
+               }
+
+               if ((nwrite = write(sockid, string, size)) < 0) { /*prevent 22857*/
+                       EM_DEBUG_EXCEPTION("socket write error");
+/*                     if (errno == EINTR) continue; */
+                       tcp_abort(stream);
+                       return 0;
+               }
+
+               if (!nwrite) {
+                       EM_DEBUG_EXCEPTION("socket write no data");
+                       tcp_abort(stream);
+                       return 0;
+               }
+
+               string += nwrite;
+               size -= nwrite;
+       }
+
+       if (_g_canceled) {
+               EM_DEBUG_EXCEPTION("thread canceled");
+               tcp_abort(stream);
+               return 0;
+       }
+/* EM_DEBUG_LOG("end"); */
+       return 1;
+
+#ifdef TEST_CANCEL_JOB
+JOB_CANCEL:
+       return 0;
+#endif
+}
+
+INTERNAL_FUNC long tcp_soutr_lnx(TCPSTREAM *stream, char *string)
+{
+       return tcp_sout_lnx(stream, string, EM_SAFE_STRLEN(string));
+}
+
diff --git a/email-core/email-network/include/email-network.h b/email-core/email-network/include/email-network.h
new file mode 100755 (executable)
index 0000000..db56240
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+/******************************************************************************
+ * File :  email-network.h
+ * Desc :  
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2011.12.16  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_NETWORK_H__
+#define __EMAIL_NETWORK_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include "email-internal-types.h"
+
+INTERNAL_FUNC long emnetwork_callback_ssl_cert_query(char *reason, char *host, char *cert);
+INTERNAL_FUNC int  emnetwork_check_network_status(int *err_code);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-core/email-storage/email-storage.c b/email-core/email-storage/email-storage.c
new file mode 100755 (executable)
index 0000000..10e84ef
--- /dev/null
@@ -0,0 +1,15505 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File: email-storage.c
+ * Desc: email-service Storage Library on Sqlite3
+ *
+ * Auth:
+ *
+ * History:
+ *     2007.03.02 : created
+ *****************************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <glib.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <errno.h>
+#include <dirent.h>
+#include <vconf.h>
+#include <sys/mman.h>
+#include <ss_manager.h>
+#include <fcntl.h>
+#include <db-util.h>
+
+#define __USE_UNIX98
+#define __USE_GNU
+#include <pthread.h>
+
+#include "email-internal-types.h"
+#include "email-convert.h"
+#include "email-core-utils.h"
+#include "email-utilities.h"
+#include "email-storage.h"
+#include "email-debug-log.h"
+#include "email-types.h"
+#include "email-convert.h"
+#include "email-core-signal.h"
+
+#define DB_STMT sqlite3_stmt *
+
+#define SETTING_MEMORY_TEMP_FILE_PATH "/tmp/email_tmp_file"
+
+#define CONTENT_DATA                  "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset="
+#define CONTENT_TYPE_DATA             "<meta http-equiv=\"Content-Type\" content=\"text/html; charset="
+
+#define FLAG_SEEN       0x01
+#define FLAG_DELETED    0x02
+#define FLAG_FLAGGED    0x04
+#define FLAG_ANSWERED   0x08
+#define FLAG_OLD        0x10
+#define FLAG_DRAFT      0x20
+
+#undef close
+
+#define ISSUE_ORGANIZATION_LEN_IN_MAIL_CERTIFICATE_TBL 256
+#define EMAIL_ADDRESS_LEN_IN_MAIL_CERTIFICATE_TBL      128
+#define SUBJECT_STRING_LEN_IN_MAIL_CERTIFICATE_TBL     1027
+#define FILE_NAME_LEN_IN_MAIL_CERTIFICATE_TBL          256
+
+#define ACCOUNT_NAME_LEN_IN_MAIL_ACCOUNT_TBL            50
+#define RECEIVING_SERVER_ADDR_LEN_IN_MAIL_ACCOUNT_TBL   50
+#define EMAIL_ADDR_LEN_IN_MAIL_ACCOUNT_TBL              128
+#define USER_NAME_LEN_IN_MAIL_ACCOUNT_TBL               50
+#define PASSWORD_LEN_IN_MAIL_ACCOUNT_TBL                50
+#define SENDING_SERVER_ADDR_LEN_IN_MAIL_ACCOUNT_TBL     50
+#define SENDING_USER_LEN_IN_MAIL_ACCOUNT_TBL            50
+#define SENDING_PASSWORD_LEN_IN_MAIL_ACCOUNT_TBL        50
+#define DISPLAY_NAME_LEN_IN_MAIL_ACCOUNT_TBL            30
+#define REPLY_TO_ADDR_LEN_IN_MAIL_ACCOUNT_TBL           128
+#define RETURN_ADDR_LEN_IN_MAIL_ACCOUNT_TBL             128
+#define LOGO_ICON_PATH_LEN_IN_MAIL_ACCOUNT_TBL          256
+#define DISPLAY_NAME_FROM_LEN_IN_MAIL_ACCOUNT_TBL       256
+#define SIGNATURE_LEN_IN_MAIL_ACCOUNT_TBL               256
+#define MAILBOX_NAME_LEN_IN_MAIL_BOX_TBL                128
+#define ALIAS_LEN_IN_MAIL_BOX_TBL                       128
+#define LOCAL_MBOX_LEN_IN_MAIL_READ_MAIL_UID_TBL        128
+#define MAILBOX_NAME_LEN_IN_MAIL_READ_MAIL_UID_TBL      128
+#define S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL             128
+#define DATA2_LEN_IN_MAIL_READ_MAIL_UID_TBL             256
+#define VALUE_LEN_IN_MAIL_RULE_TBL                      256
+#define DEST_MAILBOX_LEN_IN_MAIL_RULE_TBL               128
+#define MAILBOX_NAME_LEN_IN_MAIL_ATTACHMENT_TBL         128
+#define ATTACHMENT_PATH_LEN_IN_MAIL_ATTACHMENT_TBL      256
+#define ATTACHMENT_NAME_LEN_IN_MAIL_ATTACHMENT_TBL      256
+#define CONTENT_ID_LEN_IN_MAIL_ATTACHMENT_TBL           256
+#define ATTACHMENT_MIME_TYPE_LEN_IN_MAIL_ATTACHMENT_TBL 128
+#define MAILBOX_LEN_IN_MAIL_TBL                         128
+#define SERVER_MAILBOX_LEN_IN_MAIL_TBL                  128
+#define SERVER_MAIL_ID_LEN_IN_MAIL_TBL                  128
+#define FROM_LEN_IN_MAIL_TBL                            256
+#define SENDER_LEN_IN_MAIL_TBL                          256
+#define REPLY_TO_LEN_IN_MAIL_TBL                        256
+#define TO_LEN_IN_MAIL_TBL                              3999
+#define CC_LEN_IN_MAIL_TBL                              3999
+#define BCC_LEN_IN_MAIL_TBL                             3999
+#define RETURN_PATH_LEN_IN_MAIL_TBL                     3999
+#define SUBJECT_LEN_IN_MAIL_TBL                         1027
+#define THREAD_TOPIC_LEN_IN_MAIL_TBL                    256
+#define TEXT_1_LEN_IN_MAIL_TBL                          256
+#define TEXT_2_LEN_IN_MAIL_TBL                          256
+#define MIME_ENTITY_LEN_IN_MAIL_TBL                     256
+#define DATETIME_LEN_IN_MAIL_TBL                        128
+#define MESSAGE_ID_LEN_IN_MAIL_TBL                      256
+#define FROM_CONTACT_NAME_LEN_IN_MAIL_TBL               3999
+#define FROM_EMAIL_ADDRESS_LEN_IN_MAIL_TBL              3999
+#define TO_CONTACT_NAME_LEN_IN_MAIL_TBL                 3999
+#define TO_EMAIL_ADDRESS_LEN_IN_MAIL_TBL                3999
+#define MAILBOX_LEN_IN_MAIL_MEETING_TBL                 128
+#define LOCATION_LEN_IN_MAIL_MEETING_TBL                1024
+#define GLOBAL_OBJECT_ID_LEN_IN_MAIL_MEETING_TBL        512
+#define STANDARD_NAME_LEN_IN_MAIL_MEETING_TBL           32
+#define DAYLIGHT_NAME_LEN_IN_MAIL_MEETING_TBL           32
+#define PREVIEWBODY_LEN_IN_MAIL_TBL                     512
+#define CERTIFICATE_PATH_LEN_IN_MAIL_ACCOUNT_TBL        256
+
+/*  this define is used for query to change data (delete, insert, update) */
+#define EMSTORAGE_START_WRITE_TRANSACTION(transaction_flag, error_code) \
+       if (transaction_flag)\
+       {\
+               _timedlock_shm_mutex(&mapped_for_db_lock, 2);\
+               if (emstorage_begin_transaction(NULL, NULL, &error_code) == false) \
+               {\
+                       EM_DEBUG_EXCEPTION("emstorage_begin_transaction() error[%d]", error_code);\
+                       goto FINISH_OFF;\
+               }\
+       }
+
+/*  this define is used for query to change data (delete, insert, update) */
+#define EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction_flag, result_code, error_code) \
+       if (transaction_flag)\
+       {\
+               if (result_code == true)\
+               {\
+                       if (emstorage_commit_transaction(NULL, NULL, NULL) == false)\
+                       {\
+                               error_code = EMAIL_ERROR_DB_FAILURE;\
+                               result_code = false;\
+                       }\
+               }\
+               else\
+               {\
+                       if (emstorage_rollback_transaction(NULL, NULL, NULL) == false)\
+                               error_code = EMAIL_ERROR_DB_FAILURE;\
+               }\
+               _unlockshm_mutex(&mapped_for_db_lock);\
+       }
+
+/*  this define is used for query to read (select) */
+#define EMSTORAGE_START_READ_TRANSACTION(transaction_flag) \
+       if (transaction_flag)\
+       {\
+               /*_timedlock_shm_mutex(&mapped_for_db_lock, 2);*/\
+       }
+
+/*  this define is used for query to read (select) */
+#define EMSTORAGE_FINISH_READ_TRANSACTION(transaction_flag) \
+       if (transaction_flag)\
+       {\
+               /*_unlockshm_mutex(&mapped_for_db_lock);*/\
+       }
+
+/*  for safety DB operation */
+static pthread_mutex_t _transactionBeginLock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t _transactionEndLock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t _db_handle_lock = PTHREAD_MUTEX_INITIALIZER;
+
+static int _get_attribute_type_by_mail_field_name(char *input_mail_field_name, email_mail_attribute_type *output_mail_attribute_type);
+
+#define        _MULTIPLE_DB_HANDLE
+
+#ifdef _MULTIPLE_DB_HANDLE
+
+#define _DISCONNECT_DB                 /* db_util_close(_db_handle); */
+
+typedef struct
+{
+       pthread_t       thread_id;
+       sqlite3 *db_handle;
+} db_handle_t;
+
+#define MAX_DB_CLIENT 100
+
+/* static int _db_handle_count = 0; */
+db_handle_t _db_handle_list[MAX_DB_CLIENT] = {{0, 0}, };
+
+sqlite3 *emstorage_get_db_handle()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int i;
+       pthread_t current_thread_id = THREAD_SELF();
+       sqlite3 *result_db_handle = NULL;
+
+       ENTER_CRITICAL_SECTION(_db_handle_lock);
+       for (i = 0; i < MAX_DB_CLIENT; i++) {
+               if (pthread_equal(current_thread_id, _db_handle_list[i].thread_id)) {
+                       EM_DEBUG_LOG("found db handle at [%d]", i);
+                       result_db_handle = _db_handle_list[i].db_handle;
+                       break;
+               }
+       }
+       LEAVE_CRITICAL_SECTION(_db_handle_lock);
+
+       if (!result_db_handle)
+               EM_DEBUG_EXCEPTION("Can't find proper handle for [%d]", current_thread_id);
+
+       EM_DEBUG_FUNC_END();
+       return result_db_handle;
+}
+
+int emstorage_set_db_handle(sqlite3 *db_handle)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int i, error_code = EMAIL_ERROR_MAX_EXCEEDED;
+       pthread_t current_thread_id = THREAD_SELF();
+
+       ENTER_CRITICAL_SECTION(_db_handle_lock);
+       for (i = 0; i < MAX_DB_CLIENT; i++)     {
+               if (_db_handle_list[i].thread_id == 0) {
+                       _db_handle_list[i].thread_id = current_thread_id;
+                       _db_handle_list[i].db_handle = db_handle;
+                       EM_DEBUG_LOG("current_thread_id [%d], index [%d]", current_thread_id, i);
+                       error_code =  EMAIL_ERROR_NONE;
+                       break;
+               }
+       }
+       LEAVE_CRITICAL_SECTION(_db_handle_lock);
+
+       if (error_code == EMAIL_ERROR_MAX_EXCEEDED)
+               EM_DEBUG_EXCEPTION("Exceeded the limitation of db client. Can't find empty slot in _db_handle_list.");
+
+       EM_DEBUG_FUNC_END("error_code [%d]", error_code);
+       return error_code;
+}
+
+int emstorage_remove_db_handle()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int i, error_code = EMAIL_ERROR_MAX_EXCEEDED;
+       ENTER_CRITICAL_SECTION(_db_handle_lock);
+       for (i = 0; i < MAX_DB_CLIENT; i++)
+       {
+               if (_db_handle_list[i].thread_id == THREAD_SELF())
+               {
+                       _db_handle_list[i].thread_id = 0;
+                       _db_handle_list[i].db_handle = NULL;
+                       EM_DEBUG_LOG("index [%d]", i);
+                       error_code = EMAIL_ERROR_NONE;
+                       break;
+               }
+       }
+       LEAVE_CRITICAL_SECTION(_db_handle_lock);
+
+       if (error_code == EMAIL_ERROR_MAX_EXCEEDED)
+               EM_DEBUG_EXCEPTION("Can't find proper thread_id");
+
+       EM_DEBUG_FUNC_END("error_code [%d]", error_code);
+       return error_code;
+}
+
+
+int emstorage_reset_db_handle_list()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int i;
+
+       ENTER_CRITICAL_SECTION(_db_handle_lock);
+       for (i = 0; i < MAX_DB_CLIENT; i++)
+       {
+               _db_handle_list[i].thread_id = 0;
+               _db_handle_list[i].db_handle = NULL;
+       }
+       LEAVE_CRITICAL_SECTION(_db_handle_lock)
+
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+sqlite3 *emstorage_get_db_connection()
+{
+       sqlite3 *tmp_db_handle = emstorage_get_db_handle();
+       if (NULL == tmp_db_handle)
+               tmp_db_handle = emstorage_db_open(NULL);
+       return tmp_db_handle;
+}
+
+
+#else  /*  _MULTIPLE_DB_HANDLE */
+#define _DISCONNECT_DB                 /* db_util_close(_db_handle); */
+
+sqlite3 *_db_handle = NULL;
+
+sqlite3 *emstorage_get_db_connection()
+{
+       if (NULL == _db_handle)
+               emstorage_db_open(NULL);
+       return _db_handle;
+}
+#endif /*  _MULTIPLE_DB_HANDLE */
+
+/* ------------------------------------------------------------------------------ */
+/*  Mutex using shared memory */
+typedef struct
+{
+       pthread_mutex_t mutex;
+       int data;
+} mmapped_t;
+
+mmapped_t       *mapped_for_db_lock = NULL;
+int              shm_fd_for_db_lock = 0;
+
+#ifdef __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__
+mmapped_t       *mapped_for_generating_mail_id = NULL;
+int              shm_fd_for_generating_mail_id = 0;
+#endif /* __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__ */
+
+#ifdef __FEATURE_USE_SHARED_MUTEX_FOR_PROTECTED_FUNC_CALL__
+#define EMSTORAGE_PROTECTED_FUNC_CALL(function_call, return_value) \
+       {  _timedlock_shm_mutex(&mapped_for_db_lock, 2); return_value = function_call; _unlockshm_mutex(&mapped_for_db_lock); }
+#else /*  __FEATURE_USE_SHARED_MUTEX_FOR_PROTECTED_FUNC_CALL__ */
+#define EMSTORAGE_PROTECTED_FUNC_CALL(function_call, return_value) \
+       {  return_value = function_call; }
+#endif /*  __FEATURE_USE_SHARED_MUTEX_FOR_PROTECTED_FUNC_CALL__ */
+
+INTERNAL_FUNC int emstorage_shm_file_init(const char *shm_file_name)
+{
+       EM_DEBUG_FUNC_BEGIN("shm_file_name [%p]", shm_file_name);
+
+       if(!shm_file_name) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int fd = shm_open(shm_file_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); /*  note: permission is not working */
+
+       if (fd > 0) {
+               fchmod(fd, 0666);
+               EM_DEBUG_LOG("** Create SHM FILE **");
+               if (ftruncate(fd, sizeof(mmapped_t)) != 0) {
+                       EM_DEBUG_EXCEPTION("ftruncate failed: %s", strerror(errno));
+                       return EMAIL_ERROR_SYSTEM_FAILURE;
+               }
+
+               mmapped_t *m = (mmapped_t *)mmap(NULL, sizeof(mmapped_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+               if (m == MAP_FAILED) {
+                       EM_DEBUG_EXCEPTION("mmap failed: %s", strerror(errno));
+                       return EMAIL_ERROR_SYSTEM_FAILURE;
+               }
+
+               m->data = 0;
+
+               pthread_mutexattr_t mattr;
+               pthread_mutexattr_init(&mattr);
+               pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
+               pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST_NP);
+               pthread_mutex_init(&(m->mutex), &mattr);
+               pthread_mutexattr_destroy(&mattr);
+       }
+       else {
+               EM_DEBUG_EXCEPTION("shm_open failed: %s", strerror(errno));
+               return EMAIL_ERROR_SYSTEM_FAILURE;
+       }
+       close(fd);
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+int emstorage_shm_file_destroy(const char *shm_file_name)
+{
+       EM_DEBUG_FUNC_BEGIN("shm_file_name [%p]", shm_file_name);
+       if(!shm_file_name) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if (shm_unlink(shm_file_name) != 0)
+               EM_DEBUG_EXCEPTION("shm_unlink failed: %s", strerror(errno));
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+static int _initialize_shm_mutex(const char *shm_file_name, int *param_shm_fd, mmapped_t **param_mapped)
+{
+       EM_DEBUG_FUNC_BEGIN("shm_file_name [%p] param_shm_fd [%p], param_mapped [%p]", shm_file_name, param_shm_fd, param_mapped);
+
+       if(!shm_file_name || !param_shm_fd || !param_mapped) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if (!(*param_mapped)) {
+               EM_DEBUG_LOG("** mapping begin **");
+
+               if (!(*param_shm_fd)) { /*  open shm_file_name at first. Otherwise, the num of files in /proc/pid/fd will be increasing  */
+                       *param_shm_fd = shm_open(shm_file_name, O_RDWR, 0);
+                       if ((*param_shm_fd) == -1) {
+                               EM_DEBUG_EXCEPTION("FAIL: shm_open(): %s", strerror(errno));
+                               return EMAIL_ERROR_SYSTEM_FAILURE;
+                       }
+               }
+               mmapped_t *tmp = (mmapped_t *)mmap(NULL, sizeof(mmapped_t), PROT_READ|PROT_WRITE, MAP_SHARED, (*param_shm_fd), 0);
+
+               if (tmp == MAP_FAILED) {
+                       EM_DEBUG_EXCEPTION("mmap failed: %s", strerror(errno));
+                       return EMAIL_ERROR_SYSTEM_FAILURE;
+               }
+               *param_mapped = tmp;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+static int _timedlock_shm_mutex(mmapped_t **param_mapped, int sec)
+{
+       EM_DEBUG_FUNC_BEGIN("param_mapped [%p], sec [%d]", param_mapped, sec);
+
+       if(!param_mapped) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       struct timespec abs_time;
+       clock_gettime(CLOCK_REALTIME, &abs_time);
+       abs_time.tv_sec += sec;
+
+       int err = pthread_mutex_timedlock(&((*param_mapped)->mutex), &abs_time);
+
+       if (err == EOWNERDEAD) {
+               err = pthread_mutex_consistent(&((*param_mapped)->mutex));
+               EM_DEBUG_EXCEPTION("Previous owner is dead with lock. Fix mutex : %s", EM_STRERROR(err));
+       }
+       else if (err != 0) {
+               EM_DEBUG_EXCEPTION("ERROR : %s", EM_STRERROR(err));
+               return err;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+void _unlockshm_mutex(mmapped_t **param_mapped)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       pthread_mutex_unlock(&((*param_mapped)->mutex));
+       EM_DEBUG_FUNC_END();
+}
+/* ------------------------------------------------------------------------------ */
+
+
+static int _open_counter = 0;
+static int g_transaction = false;
+
+static int _get_password_file_name(int account_id, char *recv_password_file_name, char *send_password_file_name);
+static int _read_password_from_secure_storage(char *file_name, char **password);
+
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+static int _get_cert_password_file_name(int index, char *cert_password_file_name);
+#endif
+
+typedef struct {
+       const char *object_name;
+       unsigned int data_flag;
+} email_db_object_t;
+
+static const email_db_object_t _g_db_tables[] =
+{
+       { "mail_read_mail_uid_tbl", 1},
+       { "mail_tbl", 1},
+       { "mail_attachment_tbl", 1},
+       { NULL,  0},
+};
+
+static const email_db_object_t _g_db_indexes[] =
+{
+       { "mail_read_mail_uid_idx1", 1},
+       { "mail_idx1", 1},
+       { "mail_attachment_idx1", 1},
+       { NULL,  1},
+};
+
+enum
+{
+       CREATE_TABLE_MAIL_ACCOUNT_TBL,
+       CREATE_TABLE_MAIL_BOX_TBL,
+       CREATE_TABLE_MAIL_READ_MAIL_UID_TBL,
+       CREATE_TABLE_MAIL_RULE_TBL,
+       CREATE_TABLE_MAIL_TBL,
+       CREATE_TABLE_MAIL_ATTACHMENT_TBL,
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+       CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL,
+#endif
+       CREATE_TABLE_MAIL_MEETING_TBL,
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL,
+#endif
+       CREATE_TABLE_MAIL_CERTIFICATE_TBL,
+       CREATE_TABLE_MAIL_TASK_TBL,
+       CREATE_TABLE_MAX,
+};
+
+enum
+{
+       DATA1_IDX_IN_MAIL_ACTIVITY_TBL = 0,
+       TRANSTYPE_IDX_IN_MAIL_ACTIVITY_TBL,
+       FLAG_IDX_IN_MAIL_ACTIVITY_TBL,
+};
+
+enum
+{
+       CERTFICATE_BIND_TYPE_IDX_IN_MAIL_CERTIFICATE_TBL = 0,
+       ISSUE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL,
+       ISSUE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL,
+       ISSUE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL,
+       EXPIRE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL,
+       EXPIRE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL,
+       EXPIRE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL,
+       ISSUE_ORGANIZATION_IDX_IN_MAIL_CERTIFICATE_TBL,
+       EMAIL_ADDRESS_IDX_IN_MAIL_CERTIFICATE_TBL,
+       SUBJECT_STRING_IDX_IN_MAIL_CERTIFICATE_TBL,
+       FILE_PATH_IDX_IN_MAIL_CERTIFICATE_TBL,
+};
+
+enum
+{
+       TO_RECIPIENT = 0,
+       CC_RECIPIENT,
+       BCC_RECIPIENT,
+};
+enum
+{
+       ACCOUNT_ID_IDX_IN_MAIL_BOX_TBL = 0,
+       LOCAL_YN_IDX_IN_MAIL_BOX_TBL,
+       MAILBOX_NAME_IDX_IN_MAIL_BOX_TBL,
+       MAILBOX_TYPE_IDX_IN_MAIL_BOX_TBL,
+       ALIAS_IDX_IN_MAIL_BOX_TBL,
+       SYNC_WITH_SERVER_YN_IDX_IN_MAIL_BOX_TBL,
+       MODIFIABLE_YN_IDX_IN_MAIL_BOX_TBL,
+       TOTAL_MAIL_COUNT_ON_SERVER_IDX_IN_MAIL_BOX_TBL,
+       ARCHIVE_IDX_IN_MAIL_BOX_TBL,
+       MAIL_SLOT_SIZE_IDX_IN_MAIL_BOX_TBL,
+};
+
+enum
+{
+       ACCOUNT_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL = 0,
+       LOCAL_MAILBOX_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       S_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       DATA1_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       DATA2_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       FLAG_IDX_IN_MAIL_READ_MAIL_UID_TBL,
+       IDX_NUM_IDX_IN_MAIL_READ_MAIL_UID_TBL,          /* unused */
+};
+
+enum
+{
+       ACCOUNT_ID_IDX_IN_MAIL_RULE_TBL = 0,
+       RULE_ID_IDX_IN_MAIL_RULE_TBL,
+       TYPE_IDX_IN_MAIL_RULE_TBL,
+       VALUE_IDX_IN_MAIL_RULE_TBL,
+       ACTION_TYPE_IDX_IN_MAIL_RULE_TBL,
+       TARGET_MAILBOX_ID_IDX_IN_MAIL_RULE_TBL,
+       FLAG1_IDX_IN_MAIL_RULE_TBL,
+       FLAG2_IDX_IN_MAIL_RULE_TBL,
+};
+
+enum
+{
+       MAIL_ID_IDX_IN_MAIL_TBL = 0,
+       ACCOUNT_ID_IDX_IN_MAIL_TBL,
+       MAILBOX_ID_IDX_IN_MAIL_TBL,
+       MAILBOX_NAME_IDX_IN_MAIL_TBL,
+       MAILBOX_TYPE_IDX_IN_MAIL_TBL,
+       SUBJECT_IDX_IN_MAIL_TBL,
+       DATETIME_IDX_IN_MAIL_TBL,
+       SERVER_MAIL_STATUS_IDX_IN_MAIL_TBL,
+       SERVER_MAILBOX_NAME_IDX_IN_MAIL_TBL,
+       SERVER_MAIL_ID_IDX_IN_MAIL_TBL,
+       MESSAGE_ID_IDX_IN_MAIL_TBL,
+       REFERENCE_ID_IDX_IN_MAIL_TBL,
+       FULL_ADDRESS_FROM_IDX_IN_MAIL_TBL,
+       FULL_ADDRESS_REPLY_IDX_IN_MAIL_TBL,
+       FULL_ADDRESS_TO_IDX_IN_MAIL_TBL,
+       FULL_ADDRESS_CC_IDX_IN_MAIL_TBL,
+       FULL_ADDRESS_BCC_IDX_IN_MAIL_TBL,
+       FULL_ADDRESS_RETURN_IDX_IN_MAIL_TBL,
+       EMAIL_ADDRESS_SENDER_IDX_IN_MAIL_TBL,
+       EMAIL_ADDRESS_RECIPIENT_IDX_IN_MAIL_TBL,
+       ALIAS_SENDER_IDX_IN_MAIL_TBL,
+       ALIAS_RECIPIENT_IDX_IN_MAIL_TBL,
+       BODY_DOWNLOAD_STATUS_IDX_IN_MAIL_TBL,
+       FILE_PATH_PLAIN_IDX_IN_MAIL_TBL,
+       FILE_PATH_HTML_IDX_IN_MAIL_TBL,
+       FILE_PATH_MIME_ENTITY_IDX_IN_MAIL_TBL,
+       MAIL_SIZE_IDX_IN_MAIL_TBL,
+       FLAGS_SEEN_FIELD_IDX_IN_MAIL_TBL,
+       FLAGS_DELETED_FIELD_IDX_IN_MAIL_TBL,
+       FLAGS_FLAGGED_FIELD_IDX_IN_MAIL_TBL,
+       FLAGS_ANSWERED_FIELD_IDX_IN_MAIL_TBL,
+       FLAGS_RECENT_FIELD_IDX_IN_MAIL_TBL,
+       FLAGS_DRAFT_FIELD_IDX_IN_MAIL_TBL,
+       FLAGS_FORWARDED_FIELD_IDX_IN_MAIL_TBL,
+       DRM_STATUS_IDX_IN_MAIL_TBL,
+       PRIORITY_IDX_IN_MAIL_TBL,
+       SAVE_STATUS_IDX_IN_MAIL_TBL,
+       LOCK_STATUS_IDX_IN_MAIL_TBL,
+       REPORT_STATUS_IDX_IN_MAIL_TBL,
+       ATTACHMENT_COUNT_IDX_IN_MAIL_TBL,
+       INLINE_CONTENT_COUNT_IDX_IN_MAIL_TBL,
+       THREAD_ID_IDX_IN_MAIL_TBL,
+       THREAD_ITEM_COUNT_IDX_IN_MAIL_TBL,
+       PREVIEW_TEXT_IDX_IN_MAIL_TBL,
+       MEETING_REQUEST_STATUS_IDX_IN_MAIL_TBL,
+       MESSAGE_CLASS_IDX_IN_MAIL_TBL,
+       DIGEST_TYPE_IDX_IN_MAIL_TBL,
+       SMIME_TYPE_IDX_IN_MAIL_TBL,
+       FIELD_COUNT_OF_MAIL_TBL,  /* End of mail_tbl */
+};
+
+enum
+{
+       ATTACHMENT_ID_IDX_IN_MAIL_ATTACHMENT_TBL = 0,
+       ATTACHMENT_NAME_IDX_IN_MAIL_ATTACHMENT_TBL,
+       ATTACHMENT_PATH_IDX_IN_MAIL_ATTACHMENT_TBL,
+       ATTACHMENT_SIZE_IDX_IN_MAIL_ATTACHMENT_TBL,
+       MAIL_ID_IDX_IN_MAIL_ATTACHMENT_TBL,
+       ACCOUNT_ID_IDX_IN_MAIL_ATTACHMENT_TBL,
+       MAILBOX_ID_IDX_IN_MAIL_ATTACHMENT_TBL,
+       ATTACHMENT_SAVE_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL,
+       ATTACHMENT_DRM_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL,
+       ATTACHMENT_DRM_METHOD_IDX_IN_MAIL_ATTACHMENT_TBL,
+       ATTACHMENT_INLINE_CONTENT_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL,
+       ATTACHMENT_MIME_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL,
+#ifdef __ATTACHMENT_OPTI__
+       ENCODING_IDX_IN_MAIL_ATTACHMENT_TBL,
+       SECTION_IDX_IN_MAIL_ATTACHMENT_TBL,
+#endif
+};
+
+enum {
+       IDX_IDX_IN_MAIL_CONTACT_SYNC_TBL = 0,
+#ifndef USE_SIMPLE_CONTACT_SYNC_ATTRIBUTES
+       MAIL_ID_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+       ACCOUNT_ID_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+       ADDRESS_TYPE_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+       ADDRESS_IDX_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+#endif
+       ADDRESS_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+       CONTACT_ID_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+       STORAGE_TYPE_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+       CONTACT_NAME_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+#ifndef USE_SIMPLE_CONTACT_SYNC_ATTRIBUTES
+       DISPLAY_NAME_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+       FLAG1_IDX_IN_MAIL_CONTACT_SYNC_TBL,
+#endif
+};
+
+/* sowmya.kr 03032010, changes for get list of mails for given addr list */
+typedef struct _em_mail_id_list {
+       int mail_id;
+       struct _em_mail_id_list *next;
+} em_mail_id_list;
+
+static char *g_test_query[] = {
+               /*  1. select mail_account_tbl */
+               "SELECT"
+               " account_name, "
+               " incoming_server_type, "
+               " incoming_server_address, "
+               " user_email_address, "
+               " incoming_server_user_name, "
+               " incoming_server_password, "
+               " retrieval_mode, "
+               " incoming_server_port_number, "
+               " incoming_server_secure_connection, "
+               " outgoing_server_type, "
+               " outgoing_server_address, "
+               " outgoing_server_port_number, "
+               " outgoing_server_need_authentication, "
+               " outgoing_server_secure_connection, "
+               " outgoing_server_user_name, "
+               " outgoing_server_password, "
+               " display_name, "
+               " reply_to_addr, "
+               " return_addr, "
+               " account_id, "
+               " keep_mails_on_pop_server_after_download, "
+               " flag1, "
+               " flag2, "
+               " pop_before_smtp, "
+               " incoming_server_requires_apop"
+               ", logo_icon_path, "
+               " is_preset_account, "
+               " check_interval, "
+               " priority, "
+               " keep_local_copy, "
+               " req_delivery_receipt, "
+               " req_read_receipt, "
+               " download_limit, "
+               " block_address, "
+               " block_subject, "
+               " display_name_from, "
+               " reply_with_body, "
+               " forward_with_files, "
+               " add_myname_card, "
+               " add_signature, "
+               " signature"
+               ", add_my_address_to_bcc"
+               ", account_svc_id "
+               ", index_color "
+               ", sync_status "
+               ", sync_disabled "
+               ", smime_type"
+               ", certificate_path"
+               ", cipher_type"
+               ", digest_type"
+               " FROM mail_account_tbl",
+               /*  2. select mail_box_tbl */
+               "SELECT "
+               "   mailbox_id, "
+               "   account_id, "
+               "   local_yn,  "
+               "   mailbox_name,  "
+               "   mailbox_type,   "
+               "   alias,  "
+               "   deleted_flag,  "
+               "   modifiable_yn,  "
+               "   total_mail_count_on_server,  "
+               "   has_archived_mails, "
+               "   mail_slot_size, "
+               "   no_select, "
+               "   last_sync_time "
+               " FROM mail_box_tbl ",
+               /*  3. select mail_read_mail_uid_tbl */
+               "SELECT  "
+               "   account_id,  "
+               "   mailbox_id,  "
+               "   local_uid,  "
+               "   mailbox_name,  "
+               "   s_uid,  "
+               "   data1 ,  "
+               "   data2,  "
+               "   flag,  "
+               "   idx_num "
+               " FROM mail_read_mail_uid_tbl ",
+               /*  4. select mail_rule_tbl */
+               "SELECT "
+               "   account_id, "
+               "   rule_id, "
+               "       type, "
+               "       value, "
+               "       action_type, "
+               "       target_mailbox_id,      "
+               "       flag1, "
+               "       flag2 "
+               " FROM mail_rule_tbl    ",
+               /*  5. select mail_tbl */
+               "SELECT"
+               "       mail_id, "
+               "       account_id, "
+               "       mailbox_id, "
+               "       mailbox_name, "
+               "   mailbox_type, "
+               "   subject, "
+               "       date_time, "
+               "       server_mail_status, "
+               "       server_mailbox_name, "
+               "       server_mail_id, "
+               "   message_id, "
+               "       reference_mail_id, "
+               "   full_address_from, "
+               "   full_address_reply, "
+               "   full_address_to, "
+               "   full_address_cc, "
+               "   full_address_bcc, "
+               "   full_address_return, "
+               "   email_address_sender, "
+               "   email_address_recipient, "
+               "   alias_sender, "
+               "   alias_recipient, "
+               "       body_download_status, "
+               "       file_path_plain, "
+               "       file_path_html, "
+               "   file_path_mime_entity, "
+               "       mail_size, "
+               "   flags_seen_field     ,"
+               "   flags_deleted_field  ,"
+               "   flags_flagged_field  ,"
+               "   flags_answered_field ,"
+               "   flags_recent_field   ,"
+               "   flags_draft_field    ,"
+               "   flags_forwarded_field,"
+               "       DRM_status, "
+               "       priority, "
+               "       save_status, "
+               "       lock_status, "
+               "       report_status, "
+               "   attachment_count, "
+               "       inline_content_count, "
+               "       thread_id, "
+               "       thread_item_count, "
+               "   preview_text, "
+               "       meeting_request_status, "
+               "   message_class, "
+               "   digest_type, "
+               "   smime_type "
+               " FROM mail_tbl",
+               /*  6. select mail_attachment_tbl */
+               "SELECT "
+               "       attachment_id, "
+               "       attachment_name, "
+               "       attachment_path, "
+               "       attachment_size, "
+               "       mail_id,  "
+               "       account_id, "
+               "       mailbox_id, "
+               "       attachment_save_status,  "
+               "       attachment_drm_type,  "
+               "       attachment_drm_method,  "
+               "       attachment_inline_content_status,  "
+               "       attachment_mime_type  "
+               " FROM mail_attachment_tbl ",
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+               "SELECT  "
+               "   account_id, "
+               "   mail_id, "
+               "   server_mail_id, "
+               "   activity_id, "
+               "   activity_type, "
+               "   mailbox_id, "
+               "   mailbox_name "
+               " FROM mail_partial_body_activity_tbl ",
+#endif
+
+               "SELECT  "
+               "   mail_id, "
+               "   account_id, "
+               "   mailbox_id, "
+               "   meeting_response, "
+               "   start_time, "
+               "   end_time, "
+               "   location, "
+               "   global_object_id, "
+               "   offset, "
+               "   standard_name, "
+               "   standard_time_start_date, "
+               "   standard_bias, "
+               "   daylight_name, "
+               "   daylight_time_start_date, "
+               "   daylight_bias "
+               " FROM mail_meeting_tbl ",
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+               "SELECT "
+               "       activity_id, "
+               "   account_id, "
+               "   mail_id, "
+               "   activity_type, "
+               "   server_mailid, "
+               "   src_mbox , "
+               "       dest_mbox "
+               " FROM mail_local_activity_tbl  ",
+#endif
+               "SELECT "
+               "       task_id, "
+               "   task_type, "
+               "   task_status, "
+               "   task_priority, "
+               "   task_parameter_length, "
+               "   task_parameter , "
+               "       date_time "
+               " FROM mail_task_tbl    ",
+               NULL,
+};
+
+
+static int _get_table_field_data_char(char  **table, char *buf, int index)
+{
+       if ((table == NULL) || (buf == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION("table[%p], buf[%p], index[%d]", table, buf, index);
+               return false;
+       }
+
+       if (table[index] != NULL) {
+               *buf = (char)atoi(table[index]);
+               return true;
+       }
+
+       /*  EM_DEBUG_LOG("Empty field. Set as zero"); */
+
+       *buf = 0;
+       return false;
+}
+
+static int _get_table_field_data_int(char  **table, int *buf, int index)
+{
+       if ((table == NULL) || (buf == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION("table[%p], buf[%p], index[%d]", table, buf, index);
+               return false;
+       }
+
+       if (table[index] != NULL) {
+               *buf = atoi(table[index]);
+               return true;
+       }
+
+       /*  EM_DEBUG_LOG("Empty field. Set as zero"); */
+
+       *buf = 0;
+       return false;
+}
+
+static int _get_table_field_data_time_t(char  **table, time_t *buf, int index)
+{
+       if ((table == NULL) || (buf == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION("table[%p], buf[%p], index[%d]", table, buf, index);
+               return false;
+       }
+
+       if (table[index] != NULL) {
+               *buf = (time_t)atol(table[index]);
+               return true;
+       }
+
+       /*  EM_DEBUG_LOG("Empty field. Set as zero"); */
+
+       *buf = 0;
+       return false;
+}
+
+static int _get_table_field_data_string(char **table, char **buf, int ucs2, int index)
+{
+       int ret = false;
+
+       if ((table == NULL) || (buf == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION("table[%p], buf[%p], index[%d]", table, buf, index);
+               return false;
+       }
+
+       char *pTemp = table[index];
+       int sLen = 0;
+       if (pTemp == NULL)
+               *buf = NULL;
+       else {
+               sLen = EM_SAFE_STRLEN(pTemp);
+               if(sLen) {
+                       *buf = (char *) em_malloc(sLen + 1);
+                       if (*buf == NULL) {
+                               EM_DEBUG_EXCEPTION("malloc is failed");
+                               goto FINISH_OFF;
+                       }
+                       strncpy(*buf, pTemp, sLen);
+               }
+               else
+                       *buf = NULL;
+       }
+#ifdef _PRINT_STORAGE_LOG_
+       if (*buf)
+               EM_DEBUG_LOG("_get_table_field_data_string - buf[%s], index[%d]", *buf, index);
+       else
+               EM_DEBUG_LOG("_get_table_field_data_string - No string got ");
+#endif
+       ret = true;
+FINISH_OFF:
+
+       return ret;
+}
+
+static int _get_table_field_data_string_without_allocation(char **table, char *buf, int buffer_size, int ucs2, int index)
+{
+       if ((table == NULL) || (buf == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION(" table[%p], buf[%p], index[%d]", table, buf, index);
+                       return false;
+       }
+
+       char *pTemp = table[index];
+
+       if (pTemp == NULL)
+               buf = NULL;
+       else {
+               memset(buf, 0, buffer_size);
+               strncpy(buf, pTemp, buffer_size - 1);
+       }
+#ifdef _PRINT_STORAGE_LOG_
+       if (buf)
+               EM_DEBUG_LOG("_get_table_field_data_string - buf[%s], index[%d]", buf, index);
+       else
+               EM_DEBUG_LOG("_get_table_field_data_string - No string got ");
+#endif
+
+       return true;
+}
+
+/*
+static int _get_table_field_data_blob(char **table, void **buffer, int buffer_size, int index)
+{
+       if ((table == NULL) || (buffer == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION(" table[%p], buffer[%p], buffer_size [%d], index[%d]", table, buffer, buffer_size, index);
+               return false;
+       }
+
+       char *temp_buffer = table[index];
+
+       if (temp_buffer == NULL)
+               buffer = NULL;
+       else {
+               *buffer = malloc(buffer_size);
+               if(*buffer == NULL) {
+                       EM_DEBUG_EXCEPTION("allocation failed.");
+                       return false;
+               }
+               memset(*buffer, 0, buffer_size);
+               memcpy(*buffer, temp_buffer, buffer_size);
+       }
+#ifdef _PRINT_STORAGE_LOG_
+       if (buf)
+               EM_DEBUG_LOG("_get_table_field_data_string - buffer[%s], index[%d]", buffer, index);
+       else
+               EM_DEBUG_LOG("_get_table_field_data_string - No string got ");
+#endif
+
+       return true;
+}
+*/
+
+static int _get_stmt_field_data_char(DB_STMT hStmt, char *buf, int index)
+{
+       if ((hStmt == NULL) || (buf == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION("buf[%p], index[%d]", buf, index);
+               return false;
+       }
+
+       if (sqlite3_column_text(hStmt, index) != NULL) {
+               *buf = (char)sqlite3_column_int(hStmt, index);
+#ifdef _PRINT_STORAGE_LOG_
+                       EM_DEBUG_LOG("_get_stmt_field_data_int [%d]", *buf);
+#endif
+               return true;
+       }
+
+       EM_DEBUG_LOG("sqlite3_column_int fail. index [%d]", index);
+
+       return false;
+}
+
+static int _get_stmt_field_data_int(DB_STMT hStmt, int *buf, int index)
+{
+       if ((hStmt == NULL) || (buf == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION("buf[%p], index[%d]", buf, index);
+               return false;
+       }
+
+       if (sqlite3_column_text(hStmt, index) != NULL) {
+               *buf = sqlite3_column_int(hStmt, index);
+#ifdef _PRINT_STORAGE_LOG_
+                       EM_DEBUG_LOG("_get_stmt_field_data_int [%d]", *buf);
+#endif
+               return true;
+       }
+
+       EM_DEBUG_LOG("sqlite3_column_int fail. index [%d]", index);
+
+       return false;
+}
+
+static int _get_stmt_field_data_time_t(DB_STMT hStmt, time_t *buf, int index)
+{
+       if ((hStmt == NULL) || (buf == NULL) || (index < 0))  {
+               EM_DEBUG_EXCEPTION("buf[%p], index[%d]", buf, index);
+               return false;
+       }
+
+       if (sqlite3_column_text(hStmt, index) != NULL) {
+               *buf = (time_t)sqlite3_column_int(hStmt, index);
+#ifdef _PRINT_STORAGE_LOG_
+               EM_DEBUG_LOG("_get_stmt_field_data_time_t [%d]", *buf);
+#endif
+               return true;
+       }
+
+       EM_DEBUG_LOG("_get_stmt_field_data_time_t fail. index [%d]", index);
+       return false;
+}
+
+static int _get_stmt_field_data_string(DB_STMT hStmt, char **buf, int ucs2, int index)
+{
+       if (!hStmt || !buf || (index < 0))  { /*prevent 39619*/
+               EM_DEBUG_EXCEPTION("hStmt[%d], buf[%p], index[%d]", hStmt, buf, index);
+               return false;
+       }
+
+       int sLen = 0;
+       sLen = sqlite3_column_bytes(hStmt, index);
+
+#ifdef _PRINT_STORAGE_LOG_
+               EM_DEBUG_LOG("_get_stmt_field_data_string sqlite3_column_bytes sLen[%d]", sLen);
+#endif
+
+       if (sLen > 0) {
+               *buf = (char *) em_malloc(sLen + 1);
+               strncpy(*buf, (char *)sqlite3_column_text(hStmt, index), sLen);
+       }
+       else
+               *buf = NULL;
+
+#ifdef _PRINT_STORAGE_LOG_
+       if (*buf)
+               EM_DEBUG_LOG("buf[%s], index[%d]", *buf, index);
+       else
+               EM_DEBUG_LOG("_get_stmt_field_data_string - No string got");
+#endif
+
+       return false;
+}
+
+static void _get_stmt_field_data_blob(DB_STMT hStmt, void **buf, int index)
+{
+       if( !hStmt || !buf || (index < 0))  { /*prevent 39618*/
+               EM_DEBUG_EXCEPTION("hStmt[%d], buf[%p], index[%d]", hStmt, buf, index);
+               return;
+       }
+
+       int sLen = 0;
+       sLen = sqlite3_column_bytes(hStmt, index);
+
+#ifdef _PRINT_STORAGE_LOG_
+       EM_DEBUG_LOG("_get_stmt_field_data_blob sqlite3_column_bytes sLen[%d]", sLen);
+#endif
+
+       if (sLen > 0) {
+               *buf = (char *) em_malloc(sLen);
+               memcpy(*buf, (void *)sqlite3_column_blob(hStmt, index), sLen);
+       }
+       else
+               *buf = NULL;
+
+}
+
+static int _get_stmt_field_data_string_without_allocation(DB_STMT hStmt, char *buf, int buffer_size, int ucs2, int index)
+{
+       if (!hStmt || !buf || (index < 0))  { /*prevent 39620*/
+               EM_DEBUG_EXCEPTION("hStmt[%d], buf[%p], buffer_size[%d], index[%d]", hStmt, buf, buffer_size, index);
+               return false;
+       }
+
+       int sLen = 0;
+       sLen = sqlite3_column_bytes(hStmt, index);
+
+#ifdef _PRINT_STORAGE_LOG_
+               EM_DEBUG_LOG("_get_stmt_field_data_string_without_allocation sqlite3_column_bytes sLen[%d]", sLen);
+#endif
+
+       if (sLen > 0) {
+               memset(buf, 0, buffer_size);
+               strncpy(buf, (char *)sqlite3_column_text(hStmt, index), buffer_size - 1);
+       }
+       else
+               strcpy(buf, "");
+
+#ifdef _PRINT_STORAGE_LOG_
+       EM_DEBUG_LOG("buf[%s], index[%d]", buf, index);
+#endif
+
+       return false;
+}
+
+static int _bind_stmt_field_data_char(DB_STMT hStmt, int index, char value)
+{
+       if ((hStmt == NULL) || (index < 0)) {
+               EM_DEBUG_EXCEPTION("index[%d]", index);
+               return false;
+       }
+
+       int ret = sqlite3_bind_int(hStmt, index+1, (int)value);
+
+       if (ret != SQLITE_OK)  {
+               EM_DEBUG_EXCEPTION("sqlite3_bind_int fail - %d", ret);
+               return false;
+       }
+
+       return true;
+}
+
+static int _bind_stmt_field_data_int(DB_STMT hStmt, int index, int value)
+{
+       if ((hStmt == NULL) || (index < 0)) {
+               EM_DEBUG_EXCEPTION("index[%d]", index);
+               return false;
+       }
+
+       int ret = sqlite3_bind_int(hStmt, index+1, value);
+
+       if (ret != SQLITE_OK)  {
+               EM_DEBUG_EXCEPTION("sqlite3_bind_int fail - %d", ret);
+               return false;
+       }
+
+       return true;
+}
+
+static int _bind_stmt_field_data_time_t(DB_STMT hStmt, int index, time_t value)
+{
+       if ((hStmt == NULL) || (index < 0)) {
+               EM_DEBUG_EXCEPTION("index[%d]", index);
+               return false;
+       }
+
+       int ret = sqlite3_bind_int(hStmt, index+1, (int)value);
+
+       if (ret != SQLITE_OK)  {
+               EM_DEBUG_EXCEPTION("sqlite3_bind_int fail - %d", ret);
+               return false;
+       }
+
+       return true;
+}
+
+static int _bind_stmt_field_data_string(DB_STMT hStmt, int index, char *value, int ucs2, int max_len)
+{
+       if ((hStmt == NULL) || (index < 0)) {
+               EM_DEBUG_EXCEPTION("index[%d], max_len[%d]", index, max_len);
+               return false;
+       }
+
+#ifdef _PRINT_STORAGE_LOG_
+       EM_DEBUG_LOG("hStmt = %p, index = %d, max_len = %d, value = [%s]", hStmt, index, max_len, value);
+#endif
+
+       int ret = 0;
+       if (value != NULL)
+               ret = sqlite3_bind_text(hStmt, index+1, value, -1, SQLITE_STATIC);
+       else
+               ret = sqlite3_bind_text(hStmt, index+1, "", -1, NULL);
+
+       if (ret != SQLITE_OK)  {
+               EM_DEBUG_EXCEPTION("sqlite3_bind_text fail [%d]", ret);
+               return false;
+       }
+       return true;
+}
+
+
+static int _bind_stmt_field_data_blob(DB_STMT hStmt, int index, void *blob, int blob_size)
+{
+       if ((hStmt == NULL) || (index < 0)) {
+               EM_DEBUG_EXCEPTION("index[%d], blob_size[%d]", index, blob_size);
+               return false;
+       }
+
+#ifdef _PRINT_STORAGE_LOG_
+       EM_DEBUG_LOG("hStmt = %p, index = %d, blob_size = %d, blob = [%p]", hStmt, index, blob_size, blob);
+#endif
+
+       int ret = 0;
+       if (blob_size>0)
+               ret = sqlite3_bind_blob(hStmt, index+1, blob, blob_size, SQLITE_STATIC);
+       else
+               ret = sqlite3_bind_null(hStmt, index+1);
+
+       if (ret != SQLITE_OK)  {
+               EM_DEBUG_EXCEPTION("sqlite3_bind_blob fail [%d]", ret);
+               return false;
+       }
+       return true;
+}
+
+
+static int _delete_temp_file(const char *path)
+{
+       EM_DEBUG_FUNC_BEGIN("path[%p]", path);
+
+       DIR *dp = NULL;
+       struct dirent *entry = NULL;
+
+       char buf[1024] = {0x00, };
+
+       if ((dp = opendir(path)) == NULL)  {
+               EM_DEBUG_EXCEPTION("opendir(\"%s\") failed...", path);
+               return false;
+       }
+
+       while ((entry = readdir(dp)) != NULL)  {
+               SNPRINTF(buf, sizeof(buf), "%s/%s", path, entry->d_name);
+               remove(buf);
+       }
+
+       closedir(dp);
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+char *cpy_str(char *src)
+{
+       char *p = NULL;
+
+       if (src)  {
+               if (!(p = em_malloc((int)EM_SAFE_STRLEN(src) + 1)))  {
+                       EM_DEBUG_EXCEPTION("mailoc failed...");
+                       return NULL;
+               }
+               strncpy(p, src, EM_SAFE_STRLEN(src));
+       }
+
+       return p;
+}
+
+static void _emstorage_close_once(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       DELETE_CRITICAL_SECTION(_transactionBeginLock);
+       DELETE_CRITICAL_SECTION(_transactionEndLock);
+
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC int emstorage_close(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       emstorage_db_close(&error);
+
+       if (--_open_counter == 0)
+               _emstorage_close_once();
+
+       ret = true;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+static void *_emstorage_open_once(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int error = EMAIL_ERROR_NONE;
+
+       mkdir(USERDATA_PATH, DIRECTORY_PERMISSION);
+       mkdir(DATA_PATH, DIRECTORY_PERMISSION);
+       mkdir(EMAILPATH, DIRECTORY_PERMISSION);
+       mkdir(MAILHOME, DIRECTORY_PERMISSION);
+       mkdir(MAILTEMP, DIRECTORY_PERMISSION);
+
+       _delete_temp_file(MAILTEMP);
+
+       g_transaction = false;
+
+       if (!emstorage_create_table(EMAIL_CREATE_DB_NORMAL, &error)) {
+               EM_DEBUG_EXCEPTION(" emstorage_create_table failed - %d", error);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+
+       return NULL;
+}
+
+ /*  pData : a parameter which is registered when busy handler is registerd */
+ /*  count : retry count */
+#define EMAIL_STORAGE_MAX_RETRY_COUNT  20
+static int _callback_sqlite_busy_handler(void *pData, int count)
+{
+       EM_DEBUG_LOG("Busy Handler Called!!: [%d]", count);
+       usleep(200000);   /*   sleep time when SQLITE_LOCK */
+
+       /*  retry will be stopped if  busy handler return 0 */
+       return EMAIL_STORAGE_MAX_RETRY_COUNT - count;
+}
+
+static int _delete_all_files_and_directories(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+
+       if (!emstorage_delete_file(EMAIL_SERVICE_DB_FILE_PATH, &error)) {
+               if (error != EMAIL_ERROR_FILE_NOT_FOUND) {
+                       EM_DEBUG_EXCEPTION("remove failed - %s", EMAIL_SERVICE_DB_FILE_PATH);
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (!emstorage_delete_dir(MAILHOME, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_delete_dir failed");
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+static int _recovery_from_malformed_db_file(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+
+       /* Delete all files and directories */
+       if (!_delete_all_files_and_directories(&error)) {
+               EM_DEBUG_EXCEPTION("_delete_all_files_and_directories failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       /* Delete all accounts on MyAccount */
+
+       /* Delete all managed connection to DB */
+       emstorage_reset_db_handle_list();
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int em_db_open(sqlite3 **sqlite_handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int rc = 0;
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+
+       EM_DEBUG_LOG("*sqlite_handle[%p]", *sqlite_handle);
+
+       if (*sqlite_handle)  { /*prevent 33351*/
+               EM_DEBUG_LOG(">>>>> DB Already Opened......");
+               if (err_code != NULL)
+                       *err_code = error;
+               return true;
+       }
+
+       /*  db open */
+       EM_DEBUG_LOG("Open DB");
+       EMSTORAGE_PROTECTED_FUNC_CALL(db_util_open(EMAIL_SERVICE_DB_FILE_PATH, sqlite_handle, DB_UTIL_REGISTER_HOOK_METHOD), rc);
+       if (SQLITE_OK != rc) {
+               EM_DEBUG_EXCEPTION("db_util_open fail:%d -%s", rc, sqlite3_errmsg(*sqlite_handle));
+               error = EMAIL_ERROR_DB_FAILURE;
+               db_util_close(*sqlite_handle);
+               *sqlite_handle = NULL;
+
+               if (SQLITE_CORRUPT == rc) /* SQLITE_CORRUPT : The database disk image is malformed */ {/* Recovery DB file */
+                       EM_DEBUG_LOG("The database disk image is malformed. Trying to remove and create database disk image and directories");
+                       if (!_recovery_from_malformed_db_file(&error)) {
+                               EM_DEBUG_EXCEPTION("_recovery_from_malformed_db_file failed [%d]", error);
+                               goto FINISH_OFF;
+                       }
+
+                       EM_DEBUG_LOG("Open DB again");
+                       EMSTORAGE_PROTECTED_FUNC_CALL(db_util_open(EMAIL_SERVICE_DB_FILE_PATH, sqlite_handle, DB_UTIL_REGISTER_HOOK_METHOD), rc);
+                       if (SQLITE_OK != rc) {
+                               EM_DEBUG_EXCEPTION("db_util_open fail:%d -%s", rc, sqlite3_errmsg(*sqlite_handle));
+                               error = EMAIL_ERROR_DB_FAILURE;
+                               db_util_close(*sqlite_handle);
+                               *sqlite_handle = NULL;
+                               goto FINISH_OFF; /*prevent 33351*/
+                       }
+               }
+               else
+                       goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG(">>>>> DB Handle : *sqlite_handle[%p]", *sqlite_handle);
+
+       /* register busy handler */
+       EM_DEBUG_LOG(">>>>> Register busy handler.....");
+       rc = sqlite3_busy_handler(*sqlite_handle, _callback_sqlite_busy_handler, NULL);  /*  Busy Handler registration, NULL is a parameter which will be passed to handler */
+       if (SQLITE_OK != rc) {
+               EM_DEBUG_EXCEPTION("sqlite3_busy_handler fail:%d -%s", rc, sqlite3_errmsg(*sqlite_handle));
+               error = EMAIL_ERROR_DB_FAILURE;
+               db_util_close(*sqlite_handle);
+               *sqlite_handle = NULL;
+               goto FINISH_OFF;
+       }
+
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC sqlite3* emstorage_db_open(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+#ifdef _MULTIPLE_DB_HANDLE
+       sqlite3 *_db_handle = NULL;
+#endif
+
+       int error = EMAIL_ERROR_NONE;
+
+       _initialize_shm_mutex(SHM_FILE_FOR_DB_LOCK, &shm_fd_for_db_lock, &mapped_for_db_lock);
+
+#ifdef __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__
+       _initialize_shm_mutex(SHM_FILE_FOR_MAIL_ID_LOCK, &shm_fd_for_generating_mail_id, &mapped_for_generating_mail_id);
+#endif /*__FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__ */
+
+       if (!em_db_open(&_db_handle, &error)) {
+               EM_DEBUG_EXCEPTION("em_db_open failed[%d]", error);
+               goto FINISH_OFF;
+       }
+
+#ifdef _MULTIPLE_DB_HANDLE
+       emstorage_set_db_handle(_db_handle);
+#endif
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%p]", _db_handle);
+       return _db_handle;
+}
+
+INTERNAL_FUNC int emstorage_db_close(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+#ifdef _MULTIPLE_DB_HANDLE
+       sqlite3 *_db_handle = emstorage_get_db_handle();
+#endif
+
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+
+       DELETE_CRITICAL_SECTION(_transactionBeginLock);
+       DELETE_CRITICAL_SECTION(_transactionEndLock);
+
+       if (_db_handle) {
+               ret = db_util_close(_db_handle);
+
+               if (ret != SQLITE_OK) {
+                       EM_DEBUG_EXCEPTION(" db_util_close fail - %d", ret);
+                       error = EMAIL_ERROR_DB_FAILURE;
+                       ret = false;
+                       goto FINISH_OFF;
+               }
+#ifdef _MULTIPLE_DB_HANDLE
+               emstorage_remove_db_handle();
+#endif
+               _db_handle = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_open(int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       int retValue;
+
+       retValue = mkdir(DB_PATH, DIRECTORY_PERMISSION);
+
+       EM_DEBUG_LOG("mkdir return- %d", retValue);
+       EM_DEBUG_LOG("emstorage_open - before db_util_open - pid = %d", getpid());
+
+       if (emstorage_db_open(&error) == NULL) {
+               EM_DEBUG_EXCEPTION("emstorage_db_open failed[%d]", error);
+               goto FINISH_OFF;
+       }
+
+
+       if (_open_counter++ == 0)
+               _emstorage_open_once(&error);
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int error = EMAIL_ERROR_NONE;
+       int rc = -1, ret = false;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char *create_table_query[] =
+{
+       /*  1. create mail_account_tbl */
+       "CREATE TABLE mail_account_tbl \n"
+       "(\n"
+       "account_id                               INTEGER PRIMARY KEY,\n"
+       "account_name                             VARCHAR(51),\n"
+       "logo_icon_path                           VARCHAR(256),\n"
+       "user_data                                BLOB,\n"
+       "user_data_length                         INTEGER,\n"
+       "account_svc_id                           INTEGER,\n"
+       "sync_status                              INTEGER,\n"
+       "sync_disabled                            INTEGER,\n"
+       "default_mail_slot_size                   INTEGER,\n"
+       "user_display_name                        VARCHAR(31),\n"
+       "user_email_address                       VARCHAR(129),\n"
+       "reply_to_address                         VARCHAR(129),\n"
+       "return_address                           VARCHAR(129),\n"
+       "incoming_server_type                     INTEGER,\n"
+       "incoming_server_address                  VARCHAR(51),\n"
+       "incoming_server_port_number              INTEGER,\n"
+       "incoming_server_user_name                VARCHAR(51),\n"
+       "incoming_server_password                 VARCHAR(51),\n"
+       "incoming_server_secure_connection        INTEGER,\n"
+       "retrieval_mode                           INTEGER,\n"
+       "keep_mails_on_pop_server_after_download  INTEGER,\n"
+       "check_interval                           INTEGER,\n"
+       "auto_download_size                       INTEGER,\n"
+       "outgoing_server_type                     INTEGER,\n"
+       "outgoing_server_address                  VARCHAR(51),\n"
+       "outgoing_server_port_number              INTEGER,\n"
+       "outgoing_server_user_name                VARCHAR(51),\n"
+       "outgoing_server_password                 VARCHAR(51),\n"
+       "outgoing_server_secure_connection        INTEGER,\n"
+       "outgoing_server_need_authentication      INTEGER,\n"
+       "outgoing_server_use_same_authenticator   INTEGER,\n"
+       "priority                                 INTEGER,\n"
+       "keep_local_copy                          INTEGER,\n"
+       "req_delivery_receipt                     INTEGER,\n"
+       "req_read_receipt                         INTEGER,\n"
+       "download_limit                           INTEGER,\n"
+       "block_address                            INTEGER,\n"
+       "block_subject                            INTEGER,\n"
+       "display_name_from                        VARCHAR(256),\n"
+       "reply_with_body                          INTEGER,\n"
+       "forward_with_files                       INTEGER,\n"
+       "add_myname_card                          INTEGER,\n"
+       "add_signature                            INTEGER,\n"
+       "signature                                VARCHAR(256),\n"
+       "add_my_address_to_bcc                    INTEGER,\n"
+       "pop_before_smtp                          INTEGER,\n"
+       "incoming_server_requires_apop            INTEGER,\n"
+       "smime_type                               INTEGER,\n"
+       "certificate_path                         VARCHAR(256),\n"
+       "cipher_type                              INTEGER,\n"
+       "digest_type                              INTEGER\n"
+       "); \n ",
+       /*  2. create mail_box_tbl */
+       "CREATE TABLE mail_box_tbl \n"
+       "(\n"
+       "  mailbox_id                   INTEGER \n"
+       ", account_id                   INTEGER \n"
+       ", local_yn                     INTEGER \n"
+       ", mailbox_name                 VARCHAR(256) \n"
+       ", mailbox_type                 INTEGER \n"
+       ", alias                        VARCHAR(256) \n"
+       ", deleted_flag          INTEGER \n"
+       ", modifiable_yn                INTEGER \n"
+       ", total_mail_count_on_server   INTEGER \n"
+       ", has_archived_mails           INTEGER \n"
+       ", mail_slot_size               INTEGER \n"
+       ", no_select                    INTEGER \n"
+       ", last_sync_time               DATETIME \n"
+       "); \n ",
+
+       /*  3. create mail_read_mail_uid_tbl */
+       "CREATE TABLE mail_read_mail_uid_tbl \n"
+       "(\n"
+       "  account_id                   INTEGER \n"
+       ", mailbox_id                   VARCHAR(129) \n"
+       ", local_uid                    INTEGER \n"
+       ", mailbox_name                 VARCHAR(256) \n"
+       ", s_uid                        VARCHAR(129) \n"
+       ", data1                        INTEGER \n"
+       ", data2                        VARCHAR(257) \n"
+       ", flag                         INTEGER \n"
+       ", idx_num                      INTEGER PRIMARY KEY \n"
+       "); \n",
+       /*  4. create mail_rule_tbl */
+       "CREATE TABLE mail_rule_tbl \n"
+       "(\n"
+       "  account_id                   INTEGER \n"
+       ", rule_id                      INTEGER PRIMARY KEY\n"
+       ", type                         INTEGER \n"
+       ", value                        VARCHAR(257) \n"
+       ", action_type                  INTEGER \n"
+       ", target_mailbox_id            INTEGER \n"
+       ", flag1                        INTEGER \n"
+       ", flag2                        INTEGER \n"
+       "); \n ",
+       /*  5. create mail_tbl */
+       "CREATE TABLE mail_tbl \n"
+       "(\n"
+       "  mail_id                      INTEGER PRIMARY KEY \n"
+       ", account_id                   INTEGER \n"
+       ", mailbox_id                   INTEGER \n"
+       ", mailbox_name                 VARCHAR(129) \n"
+       ", mailbox_type                 INTEGER \n"
+       ", subject                      TEXT \n"
+       ", date_time                    DATETIME \n"
+       ", server_mail_status           INTEGER \n"
+       ", server_mailbox_name          VARCHAR(129) \n"
+       ", server_mail_id               VARCHAR(129) \n"
+       ", message_id                   VARCHAR(257) \n"
+       ", reference_mail_id            INTEGER \n"
+       ", full_address_from            TEXT \n"
+       ", full_address_reply           TEXT \n"
+       ", full_address_to              TEXT \n"
+       ", full_address_cc              TEXT \n"
+       ", full_address_bcc             TEXT \n"
+       ", full_address_return          TEXT \n"
+       ", email_address_sender         TEXT collation user1 \n"
+       ", email_address_recipient      TEXT collation user1 \n"
+       ", alias_sender                 TEXT \n"
+       ", alias_recipient              TEXT \n"
+       ", body_download_status         INTEGER \n"
+       ", file_path_plain              VARCHAR(257) \n"
+       ", file_path_html               VARCHAR(257) \n"
+       ", file_path_mime_entity        VARCHAR(257) \n"
+       ", mail_size                    INTEGER \n"
+       ", flags_seen_field             BOOLEAN \n"
+       ", flags_deleted_field          BOOLEAN \n"
+       ", flags_flagged_field          BOOLEAN \n"
+       ", flags_answered_field         BOOLEAN \n"
+       ", flags_recent_field           BOOLEAN \n"
+       ", flags_draft_field            BOOLEAN \n"
+       ", flags_forwarded_field        BOOLEAN \n"
+       ", DRM_status                   INTEGER \n"
+       ", priority                     INTEGER \n"
+       ", save_status                  INTEGER \n"
+       ", lock_status                  INTEGER \n"
+       ", report_status                INTEGER \n"
+       ", attachment_count             INTEGER \n"
+       ", inline_content_count         INTEGER \n"
+       ", thread_id                    INTEGER \n"
+       ", thread_item_count            INTEGER \n"
+       ", preview_text                 TEXT \n"
+       ", meeting_request_status       INTEGER \n"
+       ", message_class                INTEGER \n"
+       ", digest_type                  INTEGER \n"
+       ", smime_type                   INTEGER \n"
+       ", FOREIGN KEY(account_id)      REFERENCES mail_account_tbl(account_id) \n"
+       "); \n ",
+
+       /*  6. create mail_attachment_tbl */
+       "CREATE TABLE mail_attachment_tbl \n"
+       "(\n"
+       "  attachment_id                    INTEGER PRIMARY KEY"
+       ", attachment_name                  VARCHAR(257) \n"
+       ", attachment_path                  VARCHAR(257) \n"
+       ", attachment_size                  INTEGER \n"
+       ", mail_id                          INTEGER \n"
+       ", account_id                       INTEGER \n"
+       ", mailbox_id                       INTEGER \n"
+       ", attachment_save_status           INTEGER \n"
+       ", attachment_drm_type              INTEGER \n"
+       ", attachment_drm_method            INTEGER \n"
+       ", attachment_inline_content_status INTEGER \n"
+       ", attachment_mime_type             VARCHAR(257) \n"
+#ifdef __ATTACHMENT_OPTI__
+       ", encoding                     INTEGER \n"
+       ", section                      varchar(257) \n"
+#endif
+       "); \n ",
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+       "CREATE TABLE mail_partial_body_activity_tbl  \n"
+       "( \n"
+       "  account_id                   INTEGER \n"
+       ", mail_id                      INTEGER \n"
+       ", server_mail_id               INTEGER \n"
+       ", activity_id                  INTEGER PRIMARY KEY \n"
+       ", activity_type                INTEGER \n"
+       ", mailbox_id                   INTEGER \n"
+       ", mailbox_name                 VARCHAR(4000) \n"
+       "); \n ",
+#endif
+
+       "CREATE TABLE mail_meeting_tbl \n"
+       "(\n"
+       "  mail_id                     INTEGER PRIMARY KEY \n"
+       ", account_id                  INTEGER \n"
+       ", mailbox_id                  INTEGER \n"
+       ", meeting_response            INTEGER \n"
+       ", start_time                  INTEGER \n"
+       ", end_time                    INTEGER \n"
+       ", location                    TEXT \n"
+       ", global_object_id            TEXT \n"
+       ", offset                      INTEGER \n"
+       ", standard_name               TEXT \n"
+       ", standard_time_start_date    INTEGER \n"
+       ", standard_bias               INTEGER \n"
+       ", daylight_name               TEXT \n"
+       ", daylight_time_start_date    INTEGER \n"
+       ", daylight_bias               INTEGER \n"
+       "); \n ",
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       "CREATE TABLE mail_local_activity_tbl \n"
+       "( \n"
+       "  activity_id                 INTEGER \n"
+       ", account_id                  INTEGER \n"
+       ", mail_id                     INTEGER \n"
+       ", activity_type               INTEGER \n"
+       ", server_mailid               VARCHAR(129) \n"
+       ", src_mbox                    VARCHAR(129) \n"
+       ", dest_mbox                   VARCHAR(129) \n"
+       "); \n ",
+#endif
+       "CREATE TABLE mail_certificate_tbl \n"
+       "( \n"
+       "  certificate_id              INTEGER \n"
+       ", issue_year                  INTEGER \n"
+       ", issue_month                 INTEGER \n"
+       ", issue_day                   INTEGER \n"
+       ", expiration_year             INTEGER \n"
+       ", expiration_month            INTEGER \n"
+       ", expiration_day              INTEGER \n"
+       ", issue_organization_name     VARCHAR(256) \n"
+       ", email_address               VARCHAR(129) \n"
+       ", subject_str                 VARCHAR(256) \n"
+       ", filepath                    VARCHAR(256) \n"
+       ", password                    VARCHAR(51) \n"
+       "); \n ",
+
+       "CREATE TABLE mail_task_tbl \n"
+       "(\n"
+       "task_id                          INTEGER PRIMARY KEY, \n"
+       "task_type                        INTEGER, \n"
+       "task_status                      INTEGER, \n"
+       "task_priority                    INTEGER, \n"
+       "task_parameter_length            INTEGER,  \n"
+       "task_parameter                   BLOB, \n"
+       "date_time                        DATETIME \n"
+       "); \n",
+       NULL,
+};
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EM_DEBUG_LOG("local_db_handle = %p.", local_db_handle);
+
+       char *sql;
+       char **result;
+
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_account_tbl';";
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG("emstorage_create_table - result[1] = %s %c", result[1], result[1]);
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+               EM_DEBUG_LOG("CREATE TABLE mail_account_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_ACCOUNT_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               /*  create mail_account_tbl unique index */
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE UNIQUE INDEX mail_account_idx1 ON mail_account_tbl (account_id)");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+       } /*  mail_account_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_ACCOUNT_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_ACCOUNT_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+
+       sqlite3_free_table(result);
+
+
+       /*  2. create mail_box_tbl */
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_box_tbl';";
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+               EM_DEBUG_LOG("CREATE TABLE mail_box_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_BOX_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               /*  create mail_local_mailbox_tbl unique index */
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE UNIQUE INDEX mail_box_idx1 ON mail_box_tbl (account_id, local_yn, mailbox_name)");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+       } /*  mail_box_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               rc = sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_BOX_TBL], NULL, NULL, NULL);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_BOX_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+       sqlite3_free_table(result);
+
+       /*  3. create mail_read_mail_uid_tbl */
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_read_mail_uid_tbl';";
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+               EM_DEBUG_LOG("CREATE TABLE mail_read_mail_uid_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_READ_MAIL_UID_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               /*  create mail_read_mail_uid_tbl unique index */
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE UNIQUE INDEX mail_read_mail_uid_idx1 ON mail_read_mail_uid_tbl (account_id, mailbox_id, local_uid, mailbox_name, s_uid)");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+       } /*  mail_read_mail_uid_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_READ_MAIL_UID_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_READ_MAIL_UID_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+       sqlite3_free_table(result);
+
+
+       /*  4. create mail_rule_tbl */
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_rule_tbl';";
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+               EM_DEBUG_LOG("CREATE TABLE mail_rule_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_RULE_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+       } /*  mail_rule_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_RULE_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_RULE_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+       sqlite3_free_table(result);
+
+
+       /*  5. create mail_tbl */
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_tbl';";
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+               EM_DEBUG_LOG("CREATE TABLE mail_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               /*  create mail_tbl unique index */
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE UNIQUE INDEX mail_idx1 ON mail_tbl (mail_id, account_id)");
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               /*  create mail_tbl index for date_time */
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE INDEX mail_idx_date_time ON mail_tbl (date_time)");
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               /*  create mail_tbl index for thread_item_count */
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE INDEX mail_idx_thread_mail_count ON mail_tbl (thread_item_count)");
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+               /*  just one time call */
+/*             EFTSInitFTSIndex(FTS_EMAIL_IDX); */
+       } /*  mail_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+       sqlite3_free_table(result);
+
+
+       /*  6. create mail_attachment_tbl */
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_attachment_tbl';";
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+               EM_DEBUG_LOG("CREATE TABLE mail_attachment_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_ATTACHMENT_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               /*  create mail_attachment_tbl unique index */
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE UNIQUE INDEX mail_attachment_idx1 ON mail_attachment_tbl (mail_id, attachment_id) ");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+       } /*  mail_attachment_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_ATTACHMENT_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_ATTACHMENT_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+       sqlite3_free_table(result);
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_partial_body_activity_tbl';";
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (atoi(result[1]) < 1) {
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+               EM_DEBUG_LOG("CREATE TABLE mail_partial_body_activity_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+       } /*  mail_rule_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_PARTIAL_BODY_ACTIVITY_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+       sqlite3_free_table(result);
+
+#endif /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
+
+       /*  create mail_meeting_tbl */
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_meeting_tbl';";
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+               EM_DEBUG_LOG("CREATE TABLE mail_meeting_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_MEETING_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE UNIQUE INDEX mail_meeting_idx1 ON mail_meeting_tbl (mail_id)");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+       } /*  mail_contact_sync_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_MEETING_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_MEETING_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+       sqlite3_free_table(result);
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+
+               sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_local_activity_tbl';";
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+               if (atoi(result[1]) < 1) {
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+                       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+                               ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+                       EM_DEBUG_LOG(" CREATE TABLE mail_local_activity_tbl");
+
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string), create_table_query[CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL]);
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+                       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+
+               } /*  mail_rule_tbl */
+               else if (type == EMAIL_CREATE_DB_CHECK)  {
+                       rc = sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL], NULL, NULL, NULL);
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL], NULL, NULL, NULL), rc);
+                       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_LOCAL_ACTIVITY_TBL], rc, sqlite3_errmsg(local_db_handle)));
+               }
+               sqlite3_free_table(result);
+
+#endif /*  __FEATURE_LOCAL_ACTIVITY__ */
+       /*  create mail_certificate_tbl */
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_certificate_tbl';";
+       /*  rc = sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL);   */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; }, ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; }, ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+               EM_DEBUG_LOG("CREATE TABLE mail_certificate_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_CERTIFICATE_TBL], sizeof(sql_query_string)-1); /*prevent 21984*/
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE UNIQUE INDEX mail_certificate_idx1 ON mail_certificate_tbl (certificate_id)");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+       } /*  mail_contact_sync_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_CERTIFICATE_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_CERTIFICATE_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+
+       /*  create mail_task_tbl */
+       sql = "SELECT count(name) FROM sqlite_master WHERE name='mail_task_tbl';";
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; }, ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (atoi(result[1]) < 1) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN;", NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; }, ("SQL(BEGIN EXCLUSIVE) exec fail:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+               EM_DEBUG_LOG("CREATE TABLE mail_certificate_tbl");
+
+               EM_SAFE_STRNCPY(sql_query_string, create_table_query[CREATE_TABLE_MAIL_TASK_TBL], sizeof(sql_query_string)-1); /*prevent 21984 */
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "CREATE UNIQUE INDEX mail_certificate_idx1 ON mail_certificate_tbl (certificate_id)");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+       } /*  mail_task_tbl */
+       else if (type == EMAIL_CREATE_DB_CHECK)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, g_test_query[CREATE_TABLE_MAIL_CERTIFICATE_TBL], NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) exec fail:%d -%s", g_test_query[CREATE_TABLE_MAIL_TASK_TBL], rc, sqlite3_errmsg(local_db_handle)));
+       }
+
+       sqlite3_free_table(result);
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true) {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+       }
+       else {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "rollback", NULL, NULL, NULL), rc);
+       }
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/* Query series --------------------------------------------------------------*/
+
+INTERNAL_FUNC int emstorage_query_mail_count(const char *input_conditional_clause, int input_transaction, int *output_total_mail_count, int *output_unseen_mail_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_conditional_clause[%p], input_transaction[%d], output_total_mail_count[%p], output_unseen_mail_count[%p]", input_conditional_clause, input_transaction, output_total_mail_count, output_unseen_mail_count);
+       int rc = -1;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char err_msg[1024];
+       char **result;
+       sqlite3 *local_db_handle = NULL;
+
+       if (!input_conditional_clause || (!output_total_mail_count && !output_unseen_mail_count)) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       memset(&sql_query_string, 0x00, sizeof(sql_query_string));
+       local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(input_transaction);
+
+       SNPRINTF(sql_query_string, QUERY_SIZE, "SELECT COUNT(*) FROM mail_tbl");
+       EM_SAFE_STRCAT(sql_query_string, (char*)input_conditional_clause);
+
+       if (output_total_mail_count)  {
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+               EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+               _get_stmt_field_data_int(hStmt, output_total_mail_count, 0);
+       }
+
+       if (output_unseen_mail_count)  {
+               EM_SAFE_STRCAT(sql_query_string, " AND flags_seen_field = 0 ");
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               *output_unseen_mail_count = atoi(result[1]);
+               sqlite3_free_table(result);
+       }
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG("sqlite3_finalize failed [%d] : %s", rc, err_msg);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(input_transaction);
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+INTERNAL_FUNC int emstorage_query_mail_id_list(const char *input_conditional_clause, int input_transaction, int **output_mail_id_list, int *output_mail_id_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_conditional_clause [%p], input_transaction [%d], output_mail_id_list [%p], output_mail_id_count [%p]", input_conditional_clause, input_transaction, output_mail_id_list, output_mail_id_count);
+
+       int      i = 0;
+       int      count = 0;
+       int      rc = -1;
+       int      cur_query = 0;
+       int      col_index;
+       int      error = EMAIL_ERROR_NONE;
+       int     *result_mail_id_list = NULL;
+       char   **result = NULL;
+       char     sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EM_IF_NULL_RETURN_VALUE(input_conditional_clause, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(output_mail_id_list, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(output_mail_id_count, EMAIL_ERROR_INVALID_PARAM);
+
+       EMSTORAGE_START_READ_TRANSACTION(input_transaction);
+
+       /* Composing query */
+       SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, "SELECT mail_id FROM mail_tbl ");
+       EM_SAFE_STRCAT(sql_query_string, (char*)input_conditional_clause);
+
+       EM_DEBUG_LOG("query[%s].", sql_query_string);
+
+       /* Performing query */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       col_index = 1;
+
+       /*  to get mail list */
+       if (count == 0) {
+               EM_DEBUG_EXCEPTION("No mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("There are [%d] mails.", count);
+
+       if (!(result_mail_id_list = (int*)em_malloc(sizeof(int) * count))) {
+               EM_DEBUG_EXCEPTION("malloc for result_mail_id_list failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG(">>>> DATA ASSIGN START >> ");
+
+       for (i = 0; i < count; i++)
+               _get_table_field_data_int(result, result_mail_id_list + i, col_index++);
+
+       EM_DEBUG_LOG(">>>> DATA ASSIGN END [count : %d] >> ", count);
+
+       *output_mail_id_list  = result_mail_id_list;
+       *output_mail_id_count = count;
+
+FINISH_OFF:
+
+       if(result)
+               sqlite3_free_table(result);
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(input_transaction);
+       _DISCONNECT_DB;
+
+       if(error != EMAIL_ERROR_NONE)
+               EM_SAFE_FREE(result_mail_id_list);
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+INTERNAL_FUNC int emstorage_query_mail_list(const char *conditional_clause, int transaction, email_mail_list_item_t** result_mail_list,  int *result_count,  int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_PROFILE_BEGIN(emstorage_query_mail_list_func);
+
+       int i = 0, count = 0, rc = -1, to_get_count = (result_mail_list)?0:1;
+       int local_inline_content_count = 0, local_attachment_count = 0;
+       int cur_query = 0, base_count = 0, col_index;
+       int ret = false, error = EMAIL_ERROR_NONE;
+       char *date_time_string = NULL;
+       char **result = NULL, sql_query_string[QUERY_SIZE] = {0, };
+       char *field_list = "mail_id, account_id, mailbox_id, full_address_from, email_address_sender, full_address_to, subject, body_download_status, flags_seen_field, flags_deleted_field, flags_flagged_field, flags_answered_field, flags_recent_field, flags_draft_field, flags_forwarded_field, DRM_status, priority, save_status, lock_status, attachment_count, inline_content_count, date_time, preview_text, thread_id, thread_item_count, meeting_request_status, message_class, smime_type ";
+       email_mail_list_item_t *mail_list_item_from_tbl = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EM_IF_NULL_RETURN_VALUE(conditional_clause, false);
+       EM_IF_NULL_RETURN_VALUE(result_count, false);
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       /*  select clause */
+       if (to_get_count) /*  count only */
+               cur_query += SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, "SELECT mail_id FROM mail_tbl");
+       else /*  mail list in plain form */
+               cur_query += SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, "SELECT %s FROM mail_tbl ", field_list);
+
+       /* cur_query += SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, conditional_clause); This code caused some crashes.*/
+       strncat(sql_query_string, conditional_clause, QUERY_SIZE - cur_query);
+
+       EM_DEBUG_LOG("emstorage_query_mail_list : query[%s].", sql_query_string);
+
+       /*  performing query            */
+       EM_PROFILE_BEGIN(emstorage_query_mail_list_performing_query);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       EM_PROFILE_END(emstorage_query_mail_list_performing_query);
+
+       if (!base_count)
+               base_count = ({ int i=0; char *tmp = field_list; for (i=0; tmp && *(tmp + 1); tmp = index(tmp + 1, ','), i++); i; });
+
+       col_index = base_count;
+
+       EM_DEBUG_LOG("base_count [%d]", base_count);
+
+       if (to_get_count) {
+               /*  to get count */
+               if (!count) {
+                       EM_DEBUG_EXCEPTION("No mail found...");
+                       ret = false;
+                       error= EMAIL_ERROR_MAIL_NOT_FOUND;
+                       goto FINISH_OFF;
+               }
+               EM_DEBUG_LOG("There are [%d] mails.", count);
+       }
+       else {
+               /*  to get mail list */
+               if (!count) {
+                       EM_DEBUG_EXCEPTION("No mail found...");
+                       ret = false;
+                       error= EMAIL_ERROR_MAIL_NOT_FOUND;
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("There are [%d] mails.", count);
+               if (!(mail_list_item_from_tbl = (email_mail_list_item_t*)em_malloc(sizeof(email_mail_list_item_t) * count))) {
+                       EM_DEBUG_EXCEPTION("malloc for mail_list_item_from_tbl failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               EM_PROFILE_BEGIN(emstorage_query_mail_list_loop);
+               EM_DEBUG_LOG(">>>> DATA ASSIGN START >> ");
+               for (i = 0; i < count; i++) {
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].mail_id), col_index++);
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].account_id), col_index++);
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].mailbox_id), col_index++);
+                       _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].full_address_from, STRING_LENGTH_FOR_DISPLAY, 1, col_index++);
+                       _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].email_address_sender, MAX_EMAIL_ADDRESS_LENGTH, 1, col_index++);
+                       _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].email_address_recipient, STRING_LENGTH_FOR_DISPLAY,  1, col_index++);
+                       _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].subject, STRING_LENGTH_FOR_DISPLAY, 1, col_index++);
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].body_download_status), col_index++);
+                       _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_seen_field), col_index++);
+                       _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_deleted_field), col_index++);
+                       _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_flagged_field), col_index++);
+                       _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_answered_field), col_index++);
+                       _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_recent_field), col_index++);
+                       _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_draft_field), col_index++);
+                       _get_table_field_data_char(result, &(mail_list_item_from_tbl[i].flags_forwarded_field), col_index++);
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].DRM_status), col_index++);
+                       _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].priority), col_index++);
+                       _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].save_status), col_index++);
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].lock_status), col_index++);
+                       _get_table_field_data_int(result, &local_attachment_count, col_index++);
+                       _get_table_field_data_int(result, &local_inline_content_count, col_index++);
+                       _get_table_field_data_time_t(result, &(mail_list_item_from_tbl[i].date_time), col_index++);
+                       _get_table_field_data_string_without_allocation(result, mail_list_item_from_tbl[i].preview_text, MAX_PREVIEW_TEXT_LENGTH, 1, col_index++);
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].thread_id), col_index++);
+                       _get_table_field_data_int(result, &(mail_list_item_from_tbl[i].thread_item_count), col_index++);
+                       _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].meeting_request_status), col_index++);
+                       _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].message_class), col_index++);
+                       _get_table_field_data_int(result, (int*)&(mail_list_item_from_tbl[i].smime_type), col_index++);
+
+                       mail_list_item_from_tbl[i].attachment_count = ((local_attachment_count - local_inline_content_count)>0)?1:0;
+               }
+               EM_DEBUG_LOG(">>>> DATA ASSIGN END [count : %d] >> ", count);
+               EM_PROFILE_END(emstorage_query_mail_list_loop);
+       }
+
+       sqlite3_free_table(result);
+       result = NULL;
+       ret = true;
+
+FINISH_OFF:
+       EM_DEBUG_LOG("COUNT [%d]", count);
+
+       if (to_get_count)
+               *result_count = count;
+       else {
+               if (ret == true)  {
+                       if (result_mail_list)
+                               *result_mail_list = mail_list_item_from_tbl;
+                       *result_count = count;
+               }
+               else
+                       EM_SAFE_FREE(mail_list_item_from_tbl);
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+
+       sqlite3_release_memory(-1);
+
+       _DISCONNECT_DB;
+
+       EM_SAFE_FREE(date_time_string);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(emstorage_query_mail_list_func);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_query_mail_tbl(const char *conditional_clause, int transaction, emstorage_mail_tbl_t** result_mail_tbl, int *result_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("conditional_clause[%s], result_mail_tbl[%p], result_count [%p], transaction[%d], err_code[%p]", conditional_clause, result_mail_tbl, result_count, transaction, err_code);
+
+       if (!conditional_clause) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int i, col_index = FIELD_COUNT_OF_MAIL_TBL, rc, ret = false, count;
+       int error = EMAIL_ERROR_NONE;
+       char **result = NULL, sql_query_string[QUERY_SIZE] = {0, };
+       emstorage_mail_tbl_t* p_data_tbl = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_tbl %s", conditional_clause);
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (!count) {
+               EM_DEBUG_EXCEPTION("No mail found...");
+               ret = false;
+               error= EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("There are [%d] mails.", count);
+       if (!(p_data_tbl = (emstorage_mail_tbl_t*)em_malloc(sizeof(emstorage_mail_tbl_t) * count))) {
+               EM_DEBUG_EXCEPTION("malloc for emstorage_mail_tbl_t failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG(">>>> DATA ASSIGN START >> ");
+       for (i = 0; i < count; i++) {
+               _get_table_field_data_int   (result, &(p_data_tbl[i].mail_id), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].account_id), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].mailbox_id), col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].mailbox_name), 0, col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].mailbox_type), col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].subject), 1, col_index++);
+               _get_table_field_data_time_t (result, &(p_data_tbl[i].date_time), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].server_mail_status), col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].server_mailbox_name), 0, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].server_mail_id), 0, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].message_id), 0, col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].reference_mail_id), col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].full_address_from), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].full_address_reply), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].full_address_to), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].full_address_cc), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].full_address_bcc), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].full_address_return), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].email_address_sender), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].email_address_recipient), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].alias_sender), 1, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].alias_recipient), 1, col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].body_download_status), col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].file_path_plain), 0, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].file_path_html), 0, col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].file_path_mime_entity), 0, col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].mail_size), col_index++);
+               _get_table_field_data_char  (result, &(p_data_tbl[i].flags_seen_field), col_index++);
+               _get_table_field_data_char  (result, &(p_data_tbl[i].flags_deleted_field), col_index++);
+               _get_table_field_data_char  (result, &(p_data_tbl[i].flags_flagged_field), col_index++);
+               _get_table_field_data_char  (result, &(p_data_tbl[i].flags_answered_field), col_index++);
+               _get_table_field_data_char  (result, &(p_data_tbl[i].flags_recent_field), col_index++);
+               _get_table_field_data_char  (result, &(p_data_tbl[i].flags_draft_field), col_index++);
+               _get_table_field_data_char  (result, &(p_data_tbl[i].flags_forwarded_field), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].DRM_status), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].priority), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].save_status), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].lock_status), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].report_status), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].attachment_count), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].inline_content_count), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].thread_id), col_index++);
+               _get_table_field_data_int   (result, &(p_data_tbl[i].thread_item_count), col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].preview_text), 1, col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].meeting_request_status), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].message_class), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].digest_type), col_index++);
+               _get_table_field_data_int   (result, (int*)&(p_data_tbl[i].smime_type), col_index++);
+               /*  check real body file... */
+               if (p_data_tbl[i].body_download_status) {
+                       struct stat buf;
+
+                       if (p_data_tbl[i].file_path_html && EM_SAFE_STRLEN(p_data_tbl[i].file_path_html) > 0) {
+                               if (stat(p_data_tbl[i].file_path_html, &buf) == -1) {
+                                       EM_DEBUG_LINE;
+                                       p_data_tbl[i].body_download_status = 0;
+                               }
+                       }
+                       else if (p_data_tbl[i].file_path_plain && EM_SAFE_STRLEN(p_data_tbl[i].file_path_plain) > 0) {
+                               if (stat(p_data_tbl[i].file_path_plain, &buf) == -1){
+                                       EM_DEBUG_LINE;
+                                       p_data_tbl[i].body_download_status = 0;
+                               }
+                       }
+                       else
+                               p_data_tbl[i].body_download_status = 0;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if(result)
+               sqlite3_free_table(result);
+
+       if (ret == true)  {
+               if (result_mail_tbl)
+                       *result_mail_tbl = p_data_tbl;
+               *result_count = count;
+       }
+       else
+               EM_SAFE_FREE(p_data_tbl);
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+
+       sqlite3_release_memory(-1);
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_query_mailbox_tbl(const char *input_conditional_clause, const char *input_ordering_clause, int input_get_mail_count,  int input_transaction, emstorage_mailbox_tbl_t **output_mailbox_list, int *output_mailbox_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_conditional_clause[%p], input_ordering_clause [%p], input_get_mail_count[%d], input_transaction[%d], output_mailbox_list[%p], output_mailbox_count[%d]", input_conditional_clause, input_ordering_clause, input_get_mail_count, input_transaction, output_mailbox_list, output_mailbox_count);
+
+       int i = 0;
+       int rc;
+       int count = 0;
+       int col_index = 0;
+       int error = EMAIL_ERROR_NONE;
+       int read_count = 0;
+       int total_count = 0;
+       char **result;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char *fields = "MBT.mailbox_id, MBT.account_id, local_yn, MBT.mailbox_name, MBT.mailbox_type, alias, deleted_flag, modifiable_yn, total_mail_count_on_server, has_archived_mails, mail_slot_size, no_select, last_sync_time ";
+       emstorage_mailbox_tbl_t* p_data_tbl = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(input_transaction);
+
+       if (input_get_mail_count == 0) {        /* without mail count */
+               col_index = 13;
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT %s FROM mail_box_tbl AS MBT %s", fields, input_conditional_clause);
+       }
+       else {  /* with read count and total count */
+               col_index = 15;
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT %s, total, read  FROM mail_box_tbl AS MBT LEFT OUTER JOIN (SELECT mailbox_name, count(mail_id) AS total, SUM(flags_seen_field) AS read FROM mail_tbl %s GROUP BY mailbox_name) AS MT ON MBT.mailbox_name = MT.mailbox_name %s %s", fields, input_conditional_clause, input_conditional_clause, input_ordering_clause);
+       }
+
+       EM_DEBUG_LOG("query[%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)))
+
+       EM_DEBUG_LOG("result count [%d]", count);
+
+       if(count == 0) {
+               EM_DEBUG_EXCEPTION("Can't find mailbox");
+               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if ((p_data_tbl = (emstorage_mailbox_tbl_t*)em_malloc(sizeof(emstorage_mailbox_tbl_t) * count)) == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < count; i++)  {
+               _get_table_field_data_int(result, &(p_data_tbl[i].mailbox_id), col_index++);
+               _get_table_field_data_int(result, &(p_data_tbl[i].account_id), col_index++);
+               _get_table_field_data_int(result, &(p_data_tbl[i].local_yn), col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].mailbox_name), 0, col_index++);
+               _get_table_field_data_int(result, (int*)&(p_data_tbl[i].mailbox_type), col_index++);
+               _get_table_field_data_string(result, &(p_data_tbl[i].alias), 0, col_index++);
+               _get_table_field_data_int(result, &(p_data_tbl[i].deleted_flag), col_index++);
+               _get_table_field_data_int(result, &(p_data_tbl[i].modifiable_yn), col_index++);
+               _get_table_field_data_int(result, &(p_data_tbl[i].total_mail_count_on_server), col_index++);
+               _get_table_field_data_int(result, &(p_data_tbl[i].has_archived_mails), col_index++);
+               _get_table_field_data_int(result, &(p_data_tbl[i].mail_slot_size), col_index++);
+               _get_table_field_data_int(result, &(p_data_tbl[i].no_select), col_index++);
+               _get_table_field_data_int(result, (int*)&(p_data_tbl[i].last_sync_time), col_index++);
+
+               if (input_get_mail_count == 1) {
+                       _get_table_field_data_int(result, &(total_count), col_index++);
+                       p_data_tbl[i].total_mail_count_on_local = total_count;
+                       _get_table_field_data_int(result, &(read_count), col_index++);
+                       p_data_tbl[i].unread_count = total_count - read_count;                  /*  return unread count, NOT  */
+               }
+       }
+
+
+FINISH_OFF:
+       if (result)
+               sqlite3_free_table(result);
+
+       if (error == EMAIL_ERROR_NONE)  {
+               *output_mailbox_list = p_data_tbl;
+               *output_mailbox_count = count;
+               EM_DEBUG_LOG("Mailbox Count [ %d]", count);
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(input_transaction);
+
+       sqlite3_release_memory(-1);
+
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+/* Query series --------------------------------------------------------------*/
+
+INTERNAL_FUNC int emstorage_check_duplicated_account(email_account_t* account, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!account)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char **result;
+       int count;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "SELECT COUNT(*) FROM mail_account_tbl "
+               " WHERE "
+               " user_email_address = '%s' AND "
+               " incoming_server_user_name = '%s' AND "
+               " incoming_server_type = %d AND "
+               " incoming_server_address = '%s' AND "
+               " outgoing_server_user_name = '%s' AND "
+               " outgoing_server_type = %d AND "
+               " outgoing_server_address = '%s'; ",
+               account->user_email_address,
+               account->incoming_server_user_name, account->incoming_server_type, account->incoming_server_address,
+               account->outgoing_server_user_name, account->outgoing_server_type, account->outgoing_server_address
+       );
+       EM_DEBUG_LOG("Query[%s]", sql_query_string);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       EM_DEBUG_LOG("Count of Duplicated Account Information: [%d]", count);
+
+       if (count == 0) {       /*  not duplicated account */
+               ret = true;
+               EM_DEBUG_LOG("NOT duplicated account: user_email_address[%s]", account->user_email_address);
+       }
+       else {  /*  duplicated account */
+               ret = false;
+               EM_DEBUG_LOG("The same account already exists. Duplicated account: user_email_address[%s]", account->user_email_address);
+               error = EMAIL_ERROR_ALREADY_EXISTS;
+       }
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+
+INTERNAL_FUNC int emstorage_get_account_count(int *count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!count)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char err_msg[1024];
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_account_tbl");
+       EM_DEBUG_LOG("SQL STMT [ %s ]", sql_query_string);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("Before sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       *count = sqlite3_column_int(hStmt, 0);
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt=NULL;
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d: %s", rc, err_msg);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+               EM_DEBUG_LOG("sqlite3_finalize- %d", rc);
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_tbl_t** account_list, int transaction, int with_password, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int i = 0, count = 0, rc = -1, ret = false;
+       int field_index = 0;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *p_data_tbl = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char *sql = "SELECT count(*) FROM mail_account_tbl;";
+       char **result;
+       sqlite3 *local_db_handle = NULL;
+       DB_STMT hStmt = NULL;
+
+       if (!select_num || !account_list)  {
+               EM_DEBUG_EXCEPTION("select_num[%p], account_list[%p]", select_num, account_list);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       EM_DEBUG_LOG("count = %d", rc);
+
+       if (count == 0) {
+               EM_DEBUG_EXCEPTION("no account found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               ret = true;
+               goto FINISH_OFF;
+       }
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_account_tbl ORDER BY account_id");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_LOG("After sqlite3_prepare_v2 hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no account found...");
+
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               count = 0;
+               ret = true;
+               goto FINISH_OFF;
+       }
+
+       if (!(p_data_tbl = (emstorage_account_tbl_t*)malloc(sizeof(emstorage_account_tbl_t) * count)))  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       memset(p_data_tbl, 0x00, sizeof(emstorage_account_tbl_t) * count);
+       for (i = 0; i < count; i++)  {
+               /*  get recordset */
+               field_index = 0;
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].account_id), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].account_name), 0, field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].logo_icon_path), 0, field_index++);
+               _get_stmt_field_data_blob(hStmt, &(p_data_tbl[i].user_data), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].user_data_length), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].account_svc_id), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].sync_status), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].sync_disabled), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].default_mail_slot_size), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].user_display_name), 0, field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].user_email_address), 0, field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].reply_to_address), 0, field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].return_address), 0, field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].incoming_server_type), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].incoming_server_address), 0, field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].incoming_server_port_number), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].incoming_server_user_name), 0, field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].incoming_server_password), 0, field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].incoming_server_secure_connection), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].retrieval_mode), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].keep_mails_on_pop_server_after_download), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].check_interval), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].auto_download_size), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].outgoing_server_type), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].outgoing_server_address), 0, field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].outgoing_server_port_number), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].outgoing_server_user_name), 0, field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].outgoing_server_password), 0, field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].outgoing_server_secure_connection), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].outgoing_server_need_authentication), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].outgoing_server_use_same_authenticator), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].options.priority), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.keep_local_copy), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.req_delivery_receipt), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.req_read_receipt), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.download_limit), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.block_address), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.block_subject), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].options.display_name_from), 0, field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.reply_with_body), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.forward_with_files), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.add_myname_card), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].options.add_signature), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].options.signature), 0, field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl[i].options.add_my_address_to_bcc), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].pop_before_smtp), field_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].incoming_server_requires_apop), field_index++);
+               _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl[i].smime_type), field_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].certificate_path), 0, field_index++);
+               _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl[i].cipher_type), field_index++);
+               _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl[i].digest_type), field_index++);
+
+               if (with_password == true) {
+                       /*  get password from the secure storage */
+                       char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+                       char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+
+                       EM_SAFE_FREE(p_data_tbl[i].incoming_server_password);
+                       EM_SAFE_FREE(p_data_tbl[i].outgoing_server_password);
+
+                       /*  get password file name */
+                       if ((error = _get_password_file_name(p_data_tbl[i].account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("_get_password_file_name failed. [%d]", error);
+                               error = EMAIL_ERROR_SECURED_STORAGE_FAILURE;
+                               goto FINISH_OFF;
+                       }
+
+                       /*  read password from secure storage */
+                       if ((error = _read_password_from_secure_storage(recv_password_file_name, &(p_data_tbl[i].incoming_server_password))) < 0 ) {
+                               EM_DEBUG_EXCEPTION("_read_password_from_secure_storage()  failed. [%d]", error);
+                               error = EMAIL_ERROR_SECURED_STORAGE_FAILURE;
+                               goto FINISH_OFF;
+                       }
+
+                       if ((error = _read_password_from_secure_storage(send_password_file_name, &(p_data_tbl[i].outgoing_server_password))) < 0) {
+                               EM_DEBUG_EXCEPTION("_read_password_from_secure_storage()  failed. [%d]", error);
+                               error = EMAIL_ERROR_SECURED_STORAGE_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_LOG("after sqlite3_step(), i = %d, rc = %d.", i,  rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)  {
+               *account_list = p_data_tbl;
+               *select_num = count;
+               EM_DEBUG_LOG("COUNT : %d", count);
+       }
+       else if (p_data_tbl != NULL)
+               emstorage_free_account(&p_data_tbl, count, NULL);
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt = NULL;
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_maildata_by_servermailid(int account_id, char *server_mail_id, emstorage_mail_tbl_t** mail, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], server_mail_id[%s], mail[%p], transaction[%d], err_code[%p]", account_id, server_mail_id, mail, transaction, err_code);
+
+       int ret = false, error = EMAIL_ERROR_NONE, result_count;
+       char conditional_clause[QUERY_SIZE] = {0, };
+       emstorage_mail_tbl_t* p_data_tbl = NULL;
+
+       if (!server_mail_id || !mail) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (account_id == ALL_ACCOUNT)
+               SNPRINTF(conditional_clause, QUERY_SIZE, "WHERE UPPER(server_mail_id) =UPPER('%s')", server_mail_id);
+       else
+               SNPRINTF(conditional_clause, QUERY_SIZE, "WHERE UPPER(server_mail_id) =UPPER('%s') AND account_id = %d", server_mail_id, account_id);
+
+       EM_DEBUG_LOG("conditional_clause [%s]", conditional_clause);
+
+       if(!emstorage_query_mail_tbl(conditional_clause, transaction, &p_data_tbl, &result_count, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_tbl failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *mail = p_data_tbl;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+static int _write_conditional_clause_for_getting_mail_list(int account_id, int mailbox_id, email_email_address_list_t* addr_list, int thread_id, int start_index, int limit_count, int search_type, const char *search_value, email_sort_type_t sorting, bool input_except_delete_flagged_mails, char *conditional_clause_string, int buffer_size, int *err_code)
+{
+       int cur_clause = 0, conditional_clause_count = 0, i = 0;
+
+       if (account_id < ALL_ACCOUNT) {
+               EM_DEBUG_EXCEPTION("Invalid account_id [%d]", account_id);
+               EM_RETURN_ERR_CODE(err_code, EMAIL_ERROR_INVALID_PARAM, false);
+       }
+
+       /*  where clause */
+       if (account_id == ALL_ACCOUNT) {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE mailbox_type not in (3, 5, 7, 8)"):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND mailbox_type not in (3, 5, 7, 8)");
+       }
+       else {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE account_id = %d", account_id):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND account_id = %d", account_id);
+       }
+
+       if (mailbox_id > 0) {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE mailbox_id = %d", mailbox_id):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND mailbox_id = %d", mailbox_id);
+       }
+       else if(account_id != ALL_ACCOUNT) {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE mailbox_type not in (3, 5, 7, 8)"):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND mailbox_type not in (3, 5, 7, 8)");
+       }
+
+       if (thread_id > 0) {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE thread_id = %d ", thread_id):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND thread_id = %d ", thread_id);
+       }
+       else if (thread_id == EMAIL_LIST_TYPE_THREAD)   {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE thread_item_count > 0"):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND thread_item_count > 0");
+       }
+       else if (thread_id == EMAIL_LIST_TYPE_LOCAL) {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE server_mail_status = 0"):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND server_mail_status = 0");
+       }
+       else if (thread_id == EMAIL_LIST_TYPE_UNREAD) {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE flags_seen_field == 0"):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND flags_seen_field == 0");
+       }
+
+       /*  EM_DEBUG_LOG("where clause added [%s]", conditional_clause_string); */
+       if (addr_list && addr_list->address_count > 0) {
+               if (!addr_list->address_type) {
+                       cur_clause += (conditional_clause_count++ == 0)?
+                               SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE email_address_sender IN(\"%s\"", addr_list->address_list[0]):
+                               SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND email_address_sender IN(\"%s\"", addr_list->address_list[0]);
+
+                       for (i = 1; i < addr_list->address_count; i++)
+                               cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, ",\"%s\"", addr_list->address_list[i]);
+
+                       cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, ")");
+               } else {
+                       cur_clause += (conditional_clause_count++ == 0)?
+                               SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE full_address_to IN(\"%s\") or full_address_cc IN(\"%s\"", addr_list->address_list[0], addr_list->address_list[0]):
+                               SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND full_address_to IN(\"%s\") or full_address_cc IN(\"%s\"", addr_list->address_list[0], addr_list->address_list[0]);
+
+                       for (i = 1; i < addr_list->address_count; i++)
+                               cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, ",\"%s\"", addr_list->address_list[i]);
+
+                       cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, ")");
+               }
+       }
+
+       if (input_except_delete_flagged_mails) {
+               cur_clause += (conditional_clause_count++ == 0)?
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " WHERE flags_deleted_field = 0"):
+                       SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause, " AND flags_deleted_field = 0");
+       }
+
+       if (search_value) {
+               switch (search_type) {
+                       case EMAIL_SEARCH_FILTER_SUBJECT:
+                               cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause,
+                                       " %s (UPPER(subject) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') ", conditional_clause_count++ ? "AND" : "WHERE", search_value);
+                               break;
+                       case EMAIL_SEARCH_FILTER_SENDER:
+                               cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause,
+                                       " %s  ((UPPER(full_address_from) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') "
+                                       ") ", conditional_clause_count++ ? "AND" : "WHERE", search_value);
+                               break;
+                       case EMAIL_SEARCH_FILTER_RECIPIENT:
+                               cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause,
+                                       " %s ((UPPER(full_address_to) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') "
+                                       "       OR (UPPER(full_address_cc) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') "
+                                       "       OR (UPPER(full_address_bcc) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') "
+                                       ") ", conditional_clause_count++ ? "AND" : "WHERE", search_value, search_value, search_value);
+                               break;
+                       case EMAIL_SEARCH_FILTER_ALL:
+                               cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size - cur_clause,
+                                       " %s (UPPER(subject) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\' "
+                                       "       OR (((UPPER(full_address_from) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') "
+                                       "                       OR (UPPER(full_address_to) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') "
+                                       "                       OR (UPPER(full_address_cc) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') "
+                                       "                       OR (UPPER(full_address_bcc) LIKE UPPER(\'%%%%%s%%%%\') ESCAPE '\\') "
+                                       "               ) "
+                                       "       )"
+                                       ")", conditional_clause_count++ ? "AND" : "WHERE", search_value, search_value, search_value, search_value, search_value);
+                               break;
+               }
+       }
+
+       /*  EM_DEBUG_LOG("where clause [%s]", conditional_clause_string); */
+       static char sorting_str[][50] = {
+                        " ORDER BY date_time DESC",                                             /* case EMAIL_SORT_DATETIME_HIGH: */
+                        " ORDER BY date_time ASC",                                               /* case EMAIL_SORT_DATETIME_LOW: */
+                        " ORDER BY full_address_from DESC, date_time DESC", /* case EMAIL_SORT_SENDER_HIGH: */
+                        " ORDER BY full_address_from ASC, date_time DESC",  /* case EMAIL_SORT_SENDER_LOW: */
+                        " ORDER BY full_address_to DESC, date_time DESC",   /* case EMAIL_SORT_RCPT_HIGH: */
+                        " ORDER BY full_address_to ASC, date_time DESC",       /* case EMAIL_SORT_RCPT_LOW: */
+                        " ORDER BY subject DESC, date_time DESC",                 /* case EMAIL_SORT_SUBJECT_HIGH: */
+                        " ORDER BY subject ASC, date_time DESC",                       /* case EMAIL_SORT_SUBJECT_LOW: */
+                        " ORDER BY priority DESC, date_time DESC",               /* case EMAIL_SORT_PRIORITY_HIGH: */
+                        " ORDER BY priority ASC, date_time DESC",                 /* case EMAIL_SORT_PRIORITY_LOW: */
+                        " ORDER BY attachment_count DESC, date_time DESC",  /* case EMAIL_SORT_ATTACHMENT_HIGH: */
+                        " ORDER BY attachment_count ASC, date_time DESC",   /* case EMAIL_SORT_ATTACHMENT_LOW: */
+                        " ORDER BY lock_status DESC, date_time DESC",     /* case EMAIL_SORT_FAVORITE_HIGH: */
+                        " ORDER BY lock_status ASC, date_time DESC",           /* case EMAIL_SORT_FAVORITE_LOW: */
+                        " ORDER BY mailbox_name DESC, date_time DESC",   /* case EMAIL_SORT_MAILBOX_NAME_HIGH: */
+                        " ORDER BY mailbox_name ASC, date_time DESC"           /* case EMAIL_SORT_MAILBOX_NAME_LOW: */
+                        };
+
+       if (sorting < EMAIL_SORT_END && sorting >= 0)
+               cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size, " %s", sorting_str[sorting]);
+       else
+               EM_DEBUG_LOG(" Invalid Sorting order ");
+
+       /*  limit clause */
+       if (start_index != -1 && limit_count != -1)
+               cur_clause += SNPRINTF_OFFSET(conditional_clause_string, cur_clause, buffer_size, " LIMIT %d, %d", start_index, limit_count);
+
+       return true;
+}
+
+
+/**
+  *    emstorage_get_mail_list - Get the mail list information.
+  *
+  *
+  */
+INTERNAL_FUNC int emstorage_get_mail_list(int account_id, int mailbox_id, email_email_address_list_t* addr_list, int thread_id, int start_index, int limit_count, int search_type, const char *search_value, email_sort_type_t sorting, int transaction, email_mail_list_item_t** mail_list,  int *result_count,  int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_PROFILE_BEGIN(emstorage_get_mail_list_func);
+
+       int ret = false, error = EMAIL_ERROR_NONE;
+       char conditional_clause_string[QUERY_SIZE] = { 0, };
+
+       if (account_id < ALL_ACCOUNT) {
+               EM_DEBUG_EXCEPTION("Invalid account_id [%d]", account_id);
+               EM_RETURN_ERR_CODE(err_code, EMAIL_ERROR_INVALID_PARAM, false);
+       }
+       EM_IF_NULL_RETURN_VALUE(result_count, false);
+
+       _write_conditional_clause_for_getting_mail_list(account_id, mailbox_id, addr_list, thread_id, start_index, limit_count, search_type, search_value, sorting, true, conditional_clause_string, QUERY_SIZE, &error);
+
+       EM_DEBUG_LOG("conditional_clause_string[%s].", conditional_clause_string);
+
+       if(!emstorage_query_mail_list(conditional_clause_string, transaction, mail_list, result_count, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_list [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(emstorage_get_mail_list_func);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+/**
+  *    emstorage_get_mails - Get the Mail list information based on mailbox_name name
+  *
+  *
+  */
+INTERNAL_FUNC int emstorage_get_mails(int account_id, int mailbox_id, email_email_address_list_t* addr_list, int thread_id, int start_index, int limit_count, email_sort_type_t sorting,  int transaction, emstorage_mail_tbl_t** mail_list, int *result_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_PROFILE_BEGIN(emStorageGetMails);
+
+       int count = 0, ret = false, error = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *p_data_tbl = NULL;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+
+       EM_IF_NULL_RETURN_VALUE(mail_list, false);
+       EM_IF_NULL_RETURN_VALUE(result_count, false);
+
+       if (!result_count || !mail_list || account_id < ALL_ACCOUNT) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       _write_conditional_clause_for_getting_mail_list(account_id, mailbox_id, addr_list, thread_id, start_index, limit_count, 0, NULL, sorting, true, conditional_clause_string, QUERY_SIZE, &error);
+
+       EM_DEBUG_LOG("conditional_clause_string [%s]", conditional_clause_string);
+
+       if(!emstorage_query_mail_tbl(conditional_clause_string, transaction, &p_data_tbl, &count,  &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_tbl failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true) {
+               *mail_list = p_data_tbl;
+               *result_count = count;
+               EM_DEBUG_LOG("COUNT : %d", count);
+       }
+       else if (p_data_tbl != NULL)
+               emstorage_free_mail(&p_data_tbl, count, NULL);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(emStorageGetMails);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+
+/**
+  *    emstorage_get_searched_mail_list - Get the mail list information after filtering
+  *
+  *
+  */
+INTERNAL_FUNC int emstorage_get_searched_mail_list(int account_id, int mailbox_id, int thread_id, int search_type, const char *search_value, int start_index, int limit_count, email_sort_type_t sorting, int transaction, email_mail_list_item_t** mail_list,  int *result_count,  int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false, error = EMAIL_ERROR_NONE;
+       char conditional_clause[QUERY_SIZE] = {0, };
+       char *temp_search_value = NULL;
+       char *temp_search_value2 = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(mail_list, false);
+       EM_IF_NULL_RETURN_VALUE(result_count, false);
+
+       if (!result_count || !mail_list || account_id < ALL_ACCOUNT) {
+               EM_DEBUG_EXCEPTION("select_num[%p], Mail_list[%p]", result_count, mail_list);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       temp_search_value = em_replace_all_string((char*)search_value, "_", "\\_");
+       temp_search_value2 = em_replace_all_string(temp_search_value, "%", "\\%");
+
+       _write_conditional_clause_for_getting_mail_list(account_id, mailbox_id, NULL, thread_id, start_index, limit_count, search_type, temp_search_value2, sorting, true, conditional_clause, QUERY_SIZE, &error);
+
+       EM_DEBUG_LOG("conditional_clause[%s]", conditional_clause);
+
+       if(!emstorage_query_mail_list(conditional_clause, transaction, mail_list, result_count, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_list [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EM_DEBUG_LOG("emstorage_get_searched_mail_list finish off");
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_SAFE_FREE(temp_search_value);
+       EM_SAFE_FREE(temp_search_value2);
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+static int _get_password_file_name(int account_id, char *recv_password_file_name, char *send_password_file_name)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d]", account_id);
+
+       if (account_id <= 0 || !recv_password_file_name || !send_password_file_name)  {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       sprintf(recv_password_file_name, ".email_account_%d_recv", account_id);
+       sprintf(send_password_file_name, ".email_account_%d_send", account_id);
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+static int _read_password_from_secure_storage(char *file_name, char **password)
+{
+       EM_DEBUG_FUNC_BEGIN("file_name[%s], password[%p]", file_name, password);
+
+       if (!file_name || !password) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       size_t buf_len = 0, read_len = 0;
+       ssm_file_info_t sfi;
+       char *temp_password = NULL;
+       int error_code_from_ssm = 0;
+       int ret = EMAIL_ERROR_NONE;
+
+       if ( (error_code_from_ssm = ssm_getinfo(file_name, &sfi, SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
+               EM_DEBUG_EXCEPTION("ssm_getinfo() failed. [%d]", error_code_from_ssm);
+               ret = EMAIL_ERROR_SECURED_STORAGE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       buf_len = sfi.originSize;
+       EM_DEBUG_LOG("password buf_len[%d]", buf_len);
+       if ((temp_password = (char *)malloc(buf_len + 1)) == NULL) {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               ret = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       memset(temp_password, 0x00, buf_len + 1);
+
+       if ( (error_code_from_ssm = ssm_read(file_name, temp_password, buf_len, &read_len, SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
+               EM_DEBUG_EXCEPTION("ssm_read() failed. [%d]", error_code_from_ssm);
+               ret = EMAIL_ERROR_SECURED_STORAGE_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("password_file_name[%s], password[%s], originSize[%d], read len[%d]", file_name,  temp_password, sfi.originSize, read_len);
+
+       *password = temp_password;
+       temp_password = NULL;
+
+FINISH_OFF:
+       EM_SAFE_FREE(temp_password);
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, emstorage_account_tbl_t **account, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], pulloption[%d], account[%p], transaction[%d], err_code[%p]", account_id, pulloption, account, transaction, err_code);
+
+       if (!account)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], account[%p]", account_id, account);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t* p_data_tbl = NULL;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       int rc = -1;
+       int sql_len = 0;
+       char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+       char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       /*  Make query string */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT ");
+       sql_len = EM_SAFE_STRLEN(sql_query_string);
+
+       if (pulloption & EMAIL_ACC_GET_OPT_DEFAULT) {
+               SNPRINTF(sql_query_string + sql_len, sizeof(sql_query_string) - sql_len,
+                       "incoming_server_type,"
+                       "incoming_server_address,"
+                       "user_email_address,"
+                       "incoming_server_user_name,"
+                       "retrieval_mode,"
+                       "incoming_server_port_number,"
+                       "incoming_server_secure_connection,"
+                       "outgoing_server_type,"
+                       "outgoing_server_address,"
+                       "outgoing_server_port_number,"
+                       "outgoing_server_need_authentication,"
+                       "outgoing_server_secure_connection,"
+                       "outgoing_server_user_name,"
+                       "user_display_name,"
+                       "reply_to_address,"
+                       "return_address,"
+                       "account_id,"
+                       "keep_mails_on_pop_server_after_download,"
+                       "auto_download_size,"
+                       "outgoing_server_use_same_authenticator,"
+                       "pop_before_smtp,"
+                       "incoming_server_requires_apop,"
+                       "logo_icon_path,"
+                       "user_data,"
+                       "user_data_length,"
+                       "check_interval,"
+                       "sync_status,");
+               sql_len = EM_SAFE_STRLEN(sql_query_string);
+       }
+
+       if (pulloption & EMAIL_ACC_GET_OPT_ACCOUNT_NAME) {
+               SNPRINTF(sql_query_string + sql_len, sizeof(sql_query_string) - sql_len, " account_name, ");
+               sql_len = EM_SAFE_STRLEN(sql_query_string);
+       }
+
+       /*  get from secure storage, not from db */
+       if (pulloption & EMAIL_ACC_GET_OPT_OPTIONS) {
+               SNPRINTF(sql_query_string + sql_len, sizeof(sql_query_string) - sql_len,
+                       "priority,"
+                       "keep_local_copy,"
+                       "req_delivery_receipt,"
+                       "req_read_receipt,"
+                       "download_limit,"
+                       "block_address,"
+                       "block_subject,"
+                       "display_name_from,"
+                       "reply_with_body,"
+                       "forward_with_files,"
+                       "add_myname_card,"
+                       "add_signature,"
+                       "signature,"
+                       "add_my_address_to_bcc,"
+                       "account_svc_id,"
+                       "sync_disabled,"
+                       "default_mail_slot_size,"
+                       "smime_type,"
+                       "certificate_path,"
+                       "cipher_type,"
+                       "digest_type,");
+
+               sql_len = EM_SAFE_STRLEN(sql_query_string);
+       }
+
+       /*  dummy value, FROM WHERE clause */
+       SNPRINTF(sql_query_string + sql_len, sizeof(sql_query_string) - sql_len, "0 FROM mail_account_tbl WHERE account_id = %d", account_id);
+
+       /*  FROM clause */
+       EM_DEBUG_LOG("query = [%s]", sql_query_string);
+
+       /*  execute a sql and count rows */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no matched account found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       /*  Assign query result to structure */
+       if (!(p_data_tbl = (emstorage_account_tbl_t *)malloc(sizeof(emstorage_account_tbl_t) * 1)))  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(p_data_tbl, 0x00, sizeof(emstorage_account_tbl_t) * 1);
+       int col_index = 0;
+
+       if (pulloption & EMAIL_ACC_GET_OPT_DEFAULT) {
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->incoming_server_type), col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->incoming_server_address),  0, col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->user_email_address), 0, col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->incoming_server_user_name), 0, col_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->retrieval_mode), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->incoming_server_port_number), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->incoming_server_secure_connection), col_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->outgoing_server_type), col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->outgoing_server_address), 0, col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->outgoing_server_port_number), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->outgoing_server_need_authentication), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->outgoing_server_secure_connection), col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->outgoing_server_user_name), 0, col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->user_display_name), 0, col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->reply_to_address), 0, col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->return_address), 0, col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->keep_mails_on_pop_server_after_download), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->auto_download_size), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->outgoing_server_use_same_authenticator), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->pop_before_smtp), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->incoming_server_requires_apop), col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->logo_icon_path), 0, col_index++);
+               _get_stmt_field_data_blob(hStmt, &p_data_tbl->user_data, col_index++);
+               _get_stmt_field_data_int(hStmt, &p_data_tbl->user_data_length, col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->check_interval), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->sync_status), col_index++);
+       }
+
+       if (pulloption & EMAIL_ACC_GET_OPT_ACCOUNT_NAME)
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->account_name), 0, col_index++);
+
+       if (pulloption & EMAIL_ACC_GET_OPT_PASSWORD) {
+               /*  get password file name */
+               if ((error = _get_password_file_name(p_data_tbl->account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("_get_password_file_name failed. [%d]", error);
+                       goto FINISH_OFF;
+               }
+
+               /*  read password from secure storage */
+               if ((error = _read_password_from_secure_storage(recv_password_file_name, &(p_data_tbl->incoming_server_password))) < 0) {
+                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed. [%d]", error);
+                       goto FINISH_OFF;
+               }
+
+               EM_DEBUG_LOG("recv_password_file_name[%s], password[%s]", recv_password_file_name,  p_data_tbl->incoming_server_password);
+
+               if ((error = _read_password_from_secure_storage(send_password_file_name, &(p_data_tbl->outgoing_server_password))) < 0) {
+                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed. [%d]", error);
+                       goto FINISH_OFF;
+               }
+               EM_DEBUG_LOG("send_password_file_name[%s], password[%s]", send_password_file_name,  p_data_tbl->outgoing_server_password);
+       }
+
+       if (pulloption & EMAIL_ACC_GET_OPT_OPTIONS) {
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->options.priority), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.keep_local_copy), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.req_delivery_receipt), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.req_read_receipt), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.download_limit), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.block_address), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.block_subject), col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->options.display_name_from), 0, col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.reply_with_body), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.forward_with_files), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.add_myname_card), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->options.add_signature), col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->options.signature), 0, col_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->options.add_my_address_to_bcc), col_index++);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_svc_id), col_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->sync_disabled), col_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->default_mail_slot_size), col_index++);
+               _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl->smime_type), col_index++);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->certificate_path), 0, col_index++);
+               _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl->cipher_type), col_index++);
+               _get_stmt_field_data_int(hStmt, (int *)&(p_data_tbl->digest_type), col_index++);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *account = p_data_tbl;
+       else {
+               if (p_data_tbl)
+                       emstorage_free_account((emstorage_account_tbl_t **)&p_data_tbl, 1, NULL);
+       }
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_password_length_of_account(int account_id, int *password_length, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], password_length[%p], err_code[%p]", account_id, password_length, err_code);
+
+       if (account_id <= 0 || password_length == NULL)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+       char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+       char *temp_password = NULL;
+
+
+       /*  get password file name */
+       if ((error = _get_password_file_name(account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_get_password_file_name failed.");
+               goto FINISH_OFF;
+       }
+
+       /*  read password from secure storage */
+       if ((error = _read_password_from_secure_storage(recv_password_file_name, &temp_password)) < 0 || !temp_password) {
+               EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed...");
+               goto FINISH_OFF;
+       }
+
+       *password_length = EM_SAFE_STRLEN(temp_password);
+
+       EM_DEBUG_LOG("recv_password_file_name[%s], *password_length[%d]", recv_password_file_name,  *password_length);
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(temp_password);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl_t* account_tbl, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], account[%p], transaction[%d], err_code[%p]", account_id, account_tbl, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || !account_tbl)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int error = EMAIL_ERROR_NONE;
+       int rc, ret = false;
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+       char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_account_tbl SET"
+               "  account_name = ?"
+               ", logo_icon_path = ?"
+               ", user_data = ?"
+               ", user_data_length = ?"
+               ", account_svc_id = ?"
+               ", sync_status = ?"
+               ", sync_disabled = ?"
+               ", default_mail_slot_size = ?"
+               ", user_display_name = ?"
+               ", user_email_address = ?"
+               ", reply_to_address = ?"
+               ", return_address = ?"
+               ", incoming_server_type = ?"
+               ", incoming_server_address = ?"
+               ", incoming_server_port_number = ?"
+               ", incoming_server_user_name = ?"
+               ", incoming_server_secure_connection = ?"
+               ", retrieval_mode = ?"
+               ", keep_mails_on_pop_server_after_download = ?"
+               ", check_interval = ?"
+               ", auto_download_size = ?"
+               ", outgoing_server_type = ?"
+               ", outgoing_server_address = ?"
+               ", outgoing_server_port_number = ?"
+               ", outgoing_server_user_name = ?"
+               ", outgoing_server_secure_connection = ?"
+               ", outgoing_server_need_authentication = ?"
+               ", outgoing_server_use_same_authenticator = ?"
+               ", priority = ?"
+               ", keep_local_copy = ?"
+               ", req_delivery_receipt = ?"
+               ", req_read_receipt = ?"
+               ", download_limit = ?"
+               ", block_address = ?"
+               ", block_subject = ?"
+               ", display_name_from = ?"
+               ", reply_with_body = ?"
+               ", forward_with_files = ?"
+               ", add_myname_card = ?"
+               ", add_signature = ?"
+               ", signature = ?"
+               ", add_my_address_to_bcc = ?"
+               ", pop_before_smtp = ?"
+               ", incoming_server_requires_apop = ?"
+               ", smime_type = ?"
+               ", certificate_path = ?"
+               ", cipher_type = ?"
+               ", digest_type = ?"
+               " WHERE account_id = ?");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("After sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_LOG("SQL[%s]", sql_query_string);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_prepare fail:(%d) %s", rc, sqlite3_errmsg(local_db_handle)));
+
+       int i = 0;
+
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->account_name, 0, ACCOUNT_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, account_tbl->logo_icon_path, 0, LOGO_ICON_PATH_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_blob(hStmt, i++, account_tbl->user_data, account_tbl->user_data_length);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->user_data_length);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->account_svc_id);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->sync_status);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->sync_disabled);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->default_mail_slot_size);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->user_display_name, 0, DISPLAY_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->user_email_address, 0, EMAIL_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->reply_to_address, 0, REPLY_TO_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->return_address, 0, RETURN_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_type);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->incoming_server_address, 0, RECEIVING_SERVER_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_port_number);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->incoming_server_user_name, 0, USER_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_secure_connection);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->retrieval_mode);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->keep_mails_on_pop_server_after_download);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->check_interval);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->auto_download_size);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_type);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->outgoing_server_address, 0, SENDING_SERVER_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_port_number);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->outgoing_server_user_name, 0, SENDING_USER_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_secure_connection);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_need_authentication);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_use_same_authenticator);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.priority);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.keep_local_copy);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.req_delivery_receipt);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.req_read_receipt);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.download_limit);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.block_address);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.block_subject);
+       _bind_stmt_field_data_string(hStmt, i++, account_tbl->options.display_name_from, 0, DISPLAY_NAME_FROM_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.reply_with_body);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.forward_with_files);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_myname_card);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_signature);
+       _bind_stmt_field_data_string(hStmt, i++, account_tbl->options.signature, 0, SIGNATURE_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_my_address_to_bcc);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->pop_before_smtp);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_requires_apop);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->smime_type);
+       _bind_stmt_field_data_string(hStmt, i++, account_tbl->certificate_path, 0, CERTIFICATE_PATH_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->cipher_type);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->digest_type);
+       _bind_stmt_field_data_int(hStmt, i++, account_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       /*  validate account existence */
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0) {
+               EM_DEBUG_EXCEPTION(" no matched account found...");
+
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       /*  get password file name */
+       if ((error = _get_password_file_name(account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_get_password_file_name failed.");
+               goto FINISH_OFF;
+       }
+
+       /*  save passwords to the secure storage */
+       EM_DEBUG_LOG("save to the secure storage : recv_file[%s], recv_pass[%s], send_file[%s], send_pass[%s]", recv_password_file_name, account_tbl->incoming_server_password, send_password_file_name, account_tbl->outgoing_server_password);
+       if (account_tbl->incoming_server_password && (EM_SAFE_STRLEN(account_tbl->incoming_server_password) > 0)) {
+               if (ssm_write_buffer(account_tbl->incoming_server_password, EM_SAFE_STRLEN(account_tbl->incoming_server_password), recv_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+                       EM_DEBUG_EXCEPTION(" ssm_write_buffer failed -recv incoming_server_password : file[%s]", recv_password_file_name);
+                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (account_tbl->outgoing_server_password && (EM_SAFE_STRLEN(account_tbl->outgoing_server_password) > 0)) {
+               if (ssm_write_buffer(account_tbl->outgoing_server_password, EM_SAFE_STRLEN(account_tbl->outgoing_server_password), send_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+                       EM_DEBUG_EXCEPTION(" ssm_write_buffer failed -send password : file[%s]", send_password_file_name);
+                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (!emcore_notify_storage_event(NOTI_ACCOUNT_UPDATE, account_tbl->account_id, 0, NULL, 0))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_ACCOUNT_UPDATE] : Notification Failed >>> ");
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_set_field_of_accounts_with_integer_value(int account_id, char *field_name, int value, int transaction)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], field_name[%s], value[%d], transaction[%d]", account_id, field_name, value, transaction);
+       int error = EMAIL_ERROR_NONE;
+       int rc = 0;
+       int result = 0;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = NULL;
+
+       if (!account_id  || !field_name) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+
+       /* Write query string */
+       SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_account_tbl SET %s = %d WHERE account_id = %d", field_name, value, account_id);
+
+       EM_DEBUG_LOG("sql_query_string [%s]", sql_query_string);
+
+       /* Execute query */
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       if (sqlite3_changes(local_db_handle) == 0)
+               EM_DEBUG_LOG("no mail matched...");
+
+
+FINISH_OFF:
+       result = (error == EMAIL_ERROR_NONE) ? true : false;
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, result, error);
+       _DISCONNECT_DB;
+
+       if (!emcore_notify_storage_event(NOTI_ACCOUNT_UPDATE, account_id, 0, field_name, value))
+               EM_DEBUG_EXCEPTION("emcore_notify_storage_event failed : NOTI_ACCOUNT_UPDATE [%s,%d]", field_name, value);
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+INTERNAL_FUNC int emstorage_get_sync_status_of_account(int account_id, int *result_sync_status,int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], result_sync_status [%p], err_code[%p]", account_id, result_sync_status, err_code);
+
+       if(!result_sync_status) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int error = EMAIL_ERROR_NONE, rc, ret = false, sync_status, count, i, col_index;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char **result = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       if(account_id)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT sync_status FROM mail_account_tbl WHERE account_id = %d", account_id);
+       else
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT sync_status FROM mail_account_tbl");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (!count) {
+               EM_DEBUG_EXCEPTION("no matched account found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       col_index = 1;
+       *result_sync_status = 0;
+
+       for(i = 0; i < count; i++) {
+               _get_table_field_data_int(result, &sync_status, col_index++);
+               *result_sync_status |= sync_status;
+       }
+
+       EM_DEBUG_LOG("sync_status [%d]", sync_status);
+
+       sqlite3_free_table(result);
+
+       ret = true;
+
+FINISH_OFF:
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_update_sync_status_of_account(int account_id, email_set_type_t set_operator, int sync_status, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], set_operator[%d], sync_status [%d], transaction[%d], err_code[%p]", account_id, set_operator, sync_status, transaction, err_code);
+
+       int error = EMAIL_ERROR_NONE, rc, ret = false, set_value = sync_status, result_sync_status;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       if(set_operator != SET_TYPE_SET && account_id) {
+               if(!emstorage_get_sync_status_of_account(account_id, &result_sync_status, &error)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_sync_status_of_account failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+               switch(set_operator) {
+                       case SET_TYPE_UNION :
+                               set_value = result_sync_status | set_value;
+                               break;
+                       case SET_TYPE_MINUS :
+                               set_value = result_sync_status & (~set_value);
+                               break;
+                       default:
+                               EM_DEBUG_EXCEPTION("EMAIL_ERROR_NOT_SUPPORTED [%d]", set_operator);
+                               error = EMAIL_ERROR_NOT_SUPPORTED;
+                               break;
+               }
+               EM_DEBUG_LOG("set_value [%d]", set_value);
+       }
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       if(account_id)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_account_tbl SET sync_status = %d WHERE account_id = %d", set_value, account_id);
+       else
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_account_tbl SET sync_status = %d WHERE incoming_server_type <> 5", set_value);
+
+       EM_DEBUG_LOG("sql_query_string [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+
+       if (rc == 0) {
+               EM_DEBUG_EXCEPTION("no matched account found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_notify_storage_event(NOTI_ACCOUNT_UPDATE_SYNC_STATUS, account_id, 0, NULL, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_storage_event[NOTI_ACCOUNT_UPDATE_SYNC_STATUS] : Notification failed");
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t* account_tbl, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p], transaction[%d], err_code[%p]", account_tbl, transaction, err_code);
+
+       if (!account_tbl)  {
+               EM_DEBUG_EXCEPTION("account[%p], transaction[%d], err_code[%p]", account_tbl, transaction, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int error_from_ssm = 0;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+       char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       char *sql = "SELECT max(rowid) FROM mail_account_tbl;";
+       char **result = NULL;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL==result[1]) rc = 1;
+       else rc = atoi(result[1])+1;
+       sqlite3_free_table(result);
+       result = NULL;
+
+       account_tbl->account_id = rc;
+
+       if ((error = _get_password_file_name(account_tbl->account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_get_password_file_name failed.");
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG(" >>>> ACCOUNT_ID [ %d ] ", account_tbl->account_id);
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_account_tbl VALUES "
+               "(        "
+               "    ? "  /*   account_id */
+               "  , ? "  /*   account_name */
+               "  , ? "  /*   logo_icon_path */
+               "  , ? "  /*   user_data */
+               "  , ? "  /*   user_data_length */
+               "  , ? "  /*   account_svc_id */
+               "  , ? "  /*   sync_status */
+               "  , ? "  /*   sync_disabled */
+               "  , ? "  /*   default_mail_slot_size */
+               "  , ? "  /*   user_display_name */
+               "  , ? "  /*   user_email_address */
+               "  , ? "  /*   reply_to_address */
+               "  , ? "  /*   return_address */
+               "  , ? "  /*   incoming_server_type */
+               "  , ? "  /*   incoming_server_address */
+               "  , ? "  /*   incoming_server_port_number */
+               "  , ? "  /*   incoming_server_user_name */
+               "  , ? "  /*   incoming_server_password */
+               "  , ? "  /*   incoming_server_secure_connection */
+               "  , ? "  /*   retrieval_mode */
+               "  , ? "  /*   keep_mails_on_pop_server_after_download */
+               "  , ? "  /*   check_interval */
+               "  , ? "  /*   auto_download_size */
+               "  , ? "  /*   outgoing_server_type */
+               "  , ? "  /*   outgoing_server_address */
+               "  , ? "  /*   outgoing_server_port_number */
+               "  , ? "  /*   outgoing_server_user_name */
+               "  , ? "  /*   outgoing_server_password */
+               "  , ? "  /*   outgoing_server_secure_connection */
+               "  , ? "  /*   outgoing_server_need_authentication */
+               "  , ? "  /*   outgoing_server_use_same_authenticator */
+               "  , ? "  /*   priority */
+               "  , ? "  /*   keep_local_copy */
+               "  , ? "  /*   req_delivery_receipt */
+               "  , ? "  /*   req_read_receipt */
+               "  , ? "  /*   download_limit */
+               "  , ? "  /*   block_address */
+               "  , ? "  /*   block_subject */
+               "  , ? "  /*   display_name_from */
+               "  , ? "  /*   reply_with_body */
+               "  , ? "  /*   forward_with_files */
+               "  , ? "  /*   add_myname_card */
+               "  , ? "  /*   add_signature */
+               "  , ? "  /*   signature */
+               "  , ? "  /*   add_my_address_to_bcc */
+               "  , ? "  /*   pop_before_smtp */
+               "  , ? "  /*   incoming_server_requires_apop */
+               "  , ? "  /*   smime_type */
+               "  , ? "  /*   certificate_path */
+               "  , ? "  /*   cipher_type */
+               "  , ? "  /*   digest_type */
+               ") ");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG(">>>> SQL STMT [ %s ] ", sql_query_string);
+       int i = 0;
+
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->account_id);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->account_name, 0, ACCOUNT_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, account_tbl->logo_icon_path, 0, LOGO_ICON_PATH_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_blob(hStmt, i++, account_tbl->user_data, account_tbl->user_data_length);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->user_data_length);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->account_svc_id);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->sync_status);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->sync_disabled);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->default_mail_slot_size);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->user_display_name, 0, DISPLAY_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->user_email_address, 0, EMAIL_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->reply_to_address, 0, REPLY_TO_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->return_address, 0, RETURN_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_type);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->incoming_server_address, 0, RECEIVING_SERVER_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_port_number);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->incoming_server_user_name, 0, USER_NAME_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)"", 0, PASSWORD_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_secure_connection);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->retrieval_mode);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->keep_mails_on_pop_server_after_download);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->check_interval);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->auto_download_size);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_type);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->outgoing_server_address, 0, SENDING_SERVER_ADDR_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_port_number);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)account_tbl->outgoing_server_user_name, 0, SENDING_USER_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)"", 0, SENDING_PASSWORD_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_secure_connection);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_need_authentication);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->outgoing_server_use_same_authenticator);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.priority);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.keep_local_copy);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.req_delivery_receipt);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.req_read_receipt);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.download_limit);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.block_address);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.block_subject);
+       _bind_stmt_field_data_string(hStmt, i++, account_tbl->options.display_name_from, 0, DISPLAY_NAME_FROM_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.reply_with_body);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.forward_with_files);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_myname_card);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_signature);
+       _bind_stmt_field_data_string(hStmt, i++, account_tbl->options.signature, 0, SIGNATURE_LEN_IN_MAIL_ACCOUNT_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->options.add_my_address_to_bcc);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->pop_before_smtp);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->incoming_server_requires_apop);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->smime_type);
+       _bind_stmt_field_data_string(hStmt, i++, account_tbl->certificate_path, 0, FILE_NAME_LEN_IN_MAIL_CERTIFICATE_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->cipher_type);
+       _bind_stmt_field_data_int(hStmt, i++, account_tbl->digest_type);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d, errmsg = %s.", rc, sqlite3_errmsg(local_db_handle)));
+
+
+       /*  save passwords to the secure storage */
+       EM_DEBUG_LOG("save to the secure storage : recv_file[%s], send_file[%s]", recv_password_file_name, send_password_file_name);
+       if ( (error_from_ssm = ssm_write_buffer(account_tbl->incoming_server_password, EM_SAFE_STRLEN(account_tbl->incoming_server_password), recv_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
+               EM_DEBUG_EXCEPTION("ssm_write_buffer failed [%d] - recv password : file[%s]", error_from_ssm, recv_password_file_name);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       if ( (error_from_ssm = ssm_write_buffer(account_tbl->outgoing_server_password, EM_SAFE_STRLEN(account_tbl->outgoing_server_password), send_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL)) < 0) {
+               EM_DEBUG_EXCEPTION("ssm_write_buffer failed [%d] - send password : file[%s]", error_from_ssm, send_password_file_name);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+
+       if (!emcore_notify_storage_event(NOTI_ACCOUNT_ADD, account_tbl->account_id, 0, NULL, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_storage_event[NOTI_ACCOUNT_ADD] : Notification failed");
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG("sqlite3_finalize failed [%d]", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+       else
+               EM_DEBUG_LOG("hStmt is NULL!!!");
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_delete_account(int account_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], transaction[%d], err_code[%p]", account_id, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d]", account_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       /*  TODO : delete password files - file names can be obtained from db or a rule that makes a name */
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char recv_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+       char send_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+
+       /*  get password file name */
+       if ((error = _get_password_file_name(account_id, recv_password_file_name, send_password_file_name)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_get_password_file_name failed.");
+               goto FINISH_OFF;
+       }
+
+       /*  delete from db */
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_account_tbl WHERE account_id = %d", account_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       /*  validate account existence */
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no matched account found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+               /*  delete from secure storage */
+       if (ssm_delete_file(recv_password_file_name,  SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+               EM_DEBUG_EXCEPTION(" ssm_delete_file failed -recv password : file[%s]", recv_password_file_name);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       if (ssm_delete_file(send_password_file_name,  SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+               EM_DEBUG_EXCEPTION(" ssm_delete_file failed -send password : file[%s]", send_password_file_name);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_free_account(emstorage_account_tbl_t** account_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_list[%p], count[%d], err_code[%p]", account_list, count, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (count > 0)  {
+               if (!account_list || !*account_list)  {
+                       EM_DEBUG_EXCEPTION("account_list[%p], count[%d]", account_list, count);
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               emstorage_account_tbl_t* p = *account_list;
+               int i = 0;
+
+               for (; i < count; i++)  {
+                       EM_SAFE_FREE(p[i].account_name);
+                       EM_SAFE_FREE(p[i].incoming_server_address);
+                       EM_SAFE_FREE(p[i].user_email_address);
+                       EM_SAFE_FREE(p[i].user_data);
+                       EM_SAFE_FREE(p[i].incoming_server_user_name);
+                       EM_SAFE_FREE(p[i].incoming_server_password);
+                       EM_SAFE_FREE(p[i].outgoing_server_address);
+                       EM_SAFE_FREE(p[i].outgoing_server_user_name);
+                       EM_SAFE_FREE(p[i].outgoing_server_password);
+                       EM_SAFE_FREE(p[i].user_display_name);
+                       EM_SAFE_FREE(p[i].reply_to_address);
+                       EM_SAFE_FREE(p[i].return_address);
+                       EM_SAFE_FREE(p[i].logo_icon_path);
+                       EM_SAFE_FREE(p[i].options.display_name_from);
+                       EM_SAFE_FREE(p[i].options.signature);
+                       EM_SAFE_FREE(p[i].certificate_path);
+               }
+
+               EM_SAFE_FREE(p);
+               *account_list = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_count(int account_id, int local_yn, int *count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], count[%p], transaction[%d], err_code[%p]", account_id, local_yn, count, transaction, err_code);
+
+       if ((account_id < FIRST_ACCOUNT_ID) || (count == NULL))  {
+               EM_DEBUG_EXCEPTION(" account_list[%d], local_yn[%d], count[%p]", account_id, local_yn, count);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_box_tbl WHERE account_id = %d AND local_yn = %d", account_id, local_yn);
+
+       char **result;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       *count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_list(int account_id, int local_yn, email_mailbox_sort_type_t sort_type, int *select_num, emstorage_mailbox_tbl_t** mailbox_list, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], select_num[%p], mailbox_list[%p], transaction[%d], err_code[%p]", account_id, local_yn, select_num, mailbox_list, transaction, err_code);
+
+       if (!select_num || !mailbox_list) {
+               EM_DEBUG_EXCEPTION("Invalid parameters");
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+       char ordering_clause_string[QUERY_SIZE] = {0, };
+
+       if (account_id == ALL_ACCOUNT) {
+               if (local_yn == EMAIL_MAILBOX_FROM_SERVER || local_yn == EMAIL_MAILBOX_FROM_LOCAL)
+                       SNPRINTF(conditional_clause_string + EM_SAFE_STRLEN(conditional_clause_string), sizeof(conditional_clause_string)-(EM_SAFE_STRLEN(conditional_clause_string)+1), " WHERE local_yn = %d ", local_yn);
+       }
+       else {
+               SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d  ", account_id);
+               if (local_yn == EMAIL_MAILBOX_FROM_SERVER || local_yn == EMAIL_MAILBOX_FROM_LOCAL)
+                       SNPRINTF(conditional_clause_string + EM_SAFE_STRLEN(conditional_clause_string), sizeof(conditional_clause_string)-(EM_SAFE_STRLEN(conditional_clause_string)+1), " AND local_yn = %d ", local_yn);
+       }
+
+       EM_DEBUG_LOG("conditional_clause_string[%s]", conditional_clause_string);
+
+       switch (sort_type) {
+               case EMAIL_MAILBOX_SORT_BY_NAME_ASC :
+                       SNPRINTF(ordering_clause_string, QUERY_SIZE, " ORDER BY mailbox_name ASC");
+                       break;
+
+               case EMAIL_MAILBOX_SORT_BY_NAME_DSC :
+                       SNPRINTF(ordering_clause_string, QUERY_SIZE, " ORDER BY mailbox_name DESC");
+                       break;
+
+               case EMAIL_MAILBOX_SORT_BY_TYPE_ASC :
+                       SNPRINTF(ordering_clause_string, QUERY_SIZE, " ORDER BY mailbox_type ASC");
+                       break;
+
+               case EMAIL_MAILBOX_SORT_BY_TYPE_DSC :
+                       SNPRINTF(ordering_clause_string, QUERY_SIZE, " ORDER BY mailbox_type DEC");
+                       break;
+       }
+
+       EM_DEBUG_LOG("ordering_clause_string[%s]", ordering_clause_string);
+
+       if( (error = emstorage_query_mailbox_tbl(conditional_clause_string, ordering_clause_string, 0, transaction, mailbox_list, select_num)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_list_ex(int account_id, int local_yn, int with_count, int *select_num, emstorage_mailbox_tbl_t** mailbox_list, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], select_num[%p], mailbox_list[%p], transaction[%d], err_code[%p]", account_id, local_yn, select_num, mailbox_list, transaction, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int where_clause_count = 0;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+       char ordering_clause_string[QUERY_SIZE] = {0, };
+
+       if (!select_num || !mailbox_list) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (local_yn == EMAIL_MAILBOX_FROM_SERVER || local_yn == EMAIL_MAILBOX_FROM_LOCAL) {
+               SNPRINTF(conditional_clause_string + EM_SAFE_STRLEN(conditional_clause_string), sizeof(conditional_clause_string)-(EM_SAFE_STRLEN(conditional_clause_string)+1), "WHERE local_yn = %d ",  local_yn);
+               where_clause_count++;
+       }
+
+       if (account_id > 0) {
+               if (where_clause_count == 0) {
+                       SNPRINTF(conditional_clause_string + EM_SAFE_STRLEN(conditional_clause_string), sizeof(conditional_clause_string)-(EM_SAFE_STRLEN(conditional_clause_string)+1), " WHERE ");
+                       SNPRINTF(conditional_clause_string + EM_SAFE_STRLEN(conditional_clause_string), sizeof(conditional_clause_string)-(EM_SAFE_STRLEN(conditional_clause_string)+1), " account_id = %d ", account_id);
+               }
+               else
+                       SNPRINTF(conditional_clause_string + EM_SAFE_STRLEN(conditional_clause_string), sizeof(conditional_clause_string)-(EM_SAFE_STRLEN(conditional_clause_string)+1), " AND account_id = %d ", account_id);
+       }
+
+       SNPRINTF(ordering_clause_string, QUERY_SIZE, " ORDER BY MBT.mailbox_name ");
+       EM_DEBUG_LOG("conditional_clause_string[%s]", conditional_clause_string);
+       EM_DEBUG_LOG("ordering_clause_string[%s]", ordering_clause_string);
+
+       if( (error = emstorage_query_mailbox_tbl(conditional_clause_string, ordering_clause_string, 1, 1, mailbox_list, select_num)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_child_mailbox_list(int account_id, char *parent_mailbox_name, int *select_num, emstorage_mailbox_tbl_t** mailbox_list, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], parent_mailbox_name[%p], select_num[%p], mailbox_list[%p], transaction[%d], err_code[%p]", account_id, parent_mailbox_name, select_num, mailbox_list, transaction, err_code);
+       if (account_id < FIRST_ACCOUNT_ID || !select_num || !mailbox_list)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], parent_mailbox_name[%p], select_num[%p], mailbox_list[%p]", account_id, parent_mailbox_name, select_num, mailbox_list);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+
+       if (parent_mailbox_name)
+               SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d  AND UPPER(mailbox_name) LIKE UPPER('%s/%%')", account_id, parent_mailbox_name);
+       else
+               SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d  AND (mailbox_name NOT LIKE '%%/%%')", account_id);
+
+       EM_DEBUG_LOG("conditional_clause_string", conditional_clause_string);
+
+       if( (error = emstorage_query_mailbox_tbl(conditional_clause_string, " ORDER BY mailbox_name", 0, transaction, mailbox_list, select_num)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_by_modifiable_yn(int account_id, int local_yn, int *select_num, emstorage_mailbox_tbl_t** mailbox_list, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], select_num[%p], mailbox_list[%p], transaction[%d], err_code[%p]", account_id, local_yn, select_num, mailbox_list, transaction, err_code);
+       if (account_id < FIRST_ACCOUNT_ID || !select_num || !mailbox_list)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+
+       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d AND modifiable_yn = 0", account_id);
+       EM_DEBUG_LOG("conditional_clause_string [%s]", conditional_clause_string);
+
+       if( (error = emstorage_query_mailbox_tbl(conditional_clause_string, " ORDER BY mailbox_name", 0, transaction, mailbox_list, select_num)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_stamp_last_sync_time_of_mailbox(int input_mailbox_id, int input_transaction)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_transaction [%d]", input_mailbox_id, input_transaction);
+
+       int      result_code = false;
+       int      error = EMAIL_ERROR_NONE;
+       int      rc;
+       time_t   current_time = 0;
+       char     sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = NULL;
+
+       if (!input_mailbox_id )  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       time(&current_time);
+
+       local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(input_transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_box_tbl SET"
+               " last_sync_time = %d"
+               " WHERE mailbox_id = %d"
+               , (int)current_time
+               , input_mailbox_id);
+
+       EM_DEBUG_LOG("sql_query_string [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+FINISH_OFF:
+
+       if(error == EMAIL_ERROR_NONE)
+               result_code = true;
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(input_transaction, result_code, error);
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_by_name(int account_id, int local_yn, char *mailbox_name, emstorage_mailbox_tbl_t** result_mailbox, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], mailbox_name[%s], result_mailbox[%p], transaction[%d], err_code[%p]", account_id, local_yn, mailbox_name, result_mailbox, transaction, err_code);
+       EM_PROFILE_BEGIN(profile_emstorage_get_mailbox_by_name);
+
+       if (account_id < FIRST_ACCOUNT_ID || !mailbox_name || !result_mailbox)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], local_yn[%d], mailbox_name[%s], result_mailbox[%p]", account_id, local_yn, mailbox_name, result_mailbox);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int result_count = 0;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+
+       if(strcmp(mailbox_name, EMAIL_SEARCH_RESULT_MAILBOX_NAME) == 0) {
+               if (!(*result_mailbox = (emstorage_mailbox_tbl_t*)em_malloc(sizeof(emstorage_mailbox_tbl_t))))  {
+                       EM_DEBUG_EXCEPTION("malloc failed...");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               (*result_mailbox)->mailbox_id                 = 0;
+               (*result_mailbox)->account_id                 = account_id;
+               (*result_mailbox)->local_yn                   = 1;
+               (*result_mailbox)->mailbox_name               = EM_SAFE_STRDUP(mailbox_name);
+               (*result_mailbox)->mailbox_type               = EMAIL_MAILBOX_TYPE_SEARCH_RESULT;
+               (*result_mailbox)->alias                      = EM_SAFE_STRDUP(mailbox_name);
+               (*result_mailbox)->deleted_flag               = 0;
+               (*result_mailbox)->modifiable_yn              = 1;
+               (*result_mailbox)->total_mail_count_on_server = 1;
+               (*result_mailbox)->has_archived_mails         = 0;
+               (*result_mailbox)->mail_slot_size             = 0x0FFFFFFF;
+               (*result_mailbox)->no_select                  = 0;
+       }
+       else {
+
+               if (local_yn == -1)
+                       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d AND mailbox_name = '%s'", account_id, mailbox_name);
+               else
+                       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE account_id = %d AND local_yn = %d AND mailbox_name = '%s'", account_id, local_yn, mailbox_name);
+
+               EM_DEBUG_LOG("conditional_clause_string = [%s]", conditional_clause_string);
+
+               if( (error = emstorage_query_mailbox_tbl(conditional_clause_string, "", 0, transaction, result_mailbox, &result_count)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", error);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(profile_emstorage_get_mailbox_by_name);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, emstorage_mailbox_tbl_t** mailbox_name, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_type[%d], mailbox_name[%p], transaction[%d], err_code[%p]", account_id, mailbox_type, mailbox_name, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || (mailbox_type < EMAIL_MAILBOX_TYPE_INBOX || mailbox_type > EMAIL_MAILBOX_TYPE_USER_DEFINED) || !mailbox_name) {
+
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_type[%d], mailbox_name[%p]", account_id, mailbox_type, mailbox_name);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *p_data_tbl = NULL;
+       emstorage_account_tbl_t *account = NULL;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0,};
+       char *fields = "mailbox_id, account_id, local_yn, mailbox_name, mailbox_type, alias, deleted_flag, modifiable_yn, total_mail_count_on_server, has_archived_mails, mail_slot_size, no_select, last_sync_time ";
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       /* validate account */
+       /*  Check whether the account exists. */
+       if (!emstorage_get_account_by_id(account_id, EMAIL_ACC_GET_OPT_ACCOUNT_NAME,  &account, true, &error) || !account) {
+               EM_DEBUG_EXCEPTION(" emstorage_get_account_by_id failed - %d", error);
+               goto FINISH_OFF;
+       }
+
+       if (account)
+               emstorage_free_account(&account, 1, NULL);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT %s FROM mail_box_tbl WHERE account_id = %d AND mailbox_type = %d ", fields, account_id, mailbox_type);
+
+       EM_DEBUG_LOG("query = [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE; goto FINISH_OFF; }, ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE; goto FINISH_OFF; }, ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE) {
+               EM_DEBUG_EXCEPTION(" no matched mailbox_name found...");
+               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+
+       if (!(p_data_tbl = (emstorage_mailbox_tbl_t*)malloc(sizeof(emstorage_mailbox_tbl_t))))  {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(p_data_tbl, 0x00, sizeof(emstorage_mailbox_tbl_t));
+
+       int col_index = 0;
+
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mailbox_id), col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->local_yn), col_index++);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->mailbox_name), 0, col_index++);
+       _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->mailbox_type), col_index++);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->alias), 0, col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->deleted_flag), col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->modifiable_yn), col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->total_mail_count_on_server), col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->has_archived_mails), col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mail_slot_size), col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->no_select), col_index++);
+       _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->last_sync_time), col_index++);
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *mailbox_name = p_data_tbl;
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_by_id(int input_mailbox_id, emstorage_mailbox_tbl_t** output_mailbox)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], output_mailbox[%p]", input_mailbox_id, output_mailbox);
+
+       if (input_mailbox_id <= 0 || !output_mailbox)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return  EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int  ret = EMAIL_ERROR_NONE;
+       int  result_count = 0;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+
+       SNPRINTF(conditional_clause_string, sizeof(conditional_clause_string), "WHERE mailbox_id = %d", input_mailbox_id);
+
+       EM_DEBUG_LOG("conditional_clause_string = [%s]", conditional_clause_string);
+
+       if( (ret = emstorage_query_mailbox_tbl(conditional_clause_string, "", false, false, output_mailbox, &result_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mailbox_tbl failed [%d]", ret);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_id_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, int *mailbox_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_type[%d], mailbox_id[%p], transaction[%d], err_code[%p]", account_id, mailbox_type, mailbox_id, transaction, err_code);
+       if (account_id < FIRST_ACCOUNT_ID || (mailbox_type < EMAIL_MAILBOX_TYPE_INBOX || mailbox_type > EMAIL_MAILBOX_TYPE_ALL_EMAILS) || !mailbox_id)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], mailbox_type[%d], mailbox_id[%p]", account_id, mailbox_type, mailbox_id);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t* account = NULL;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       /*  Check whether the account exists. */
+       if (!emstorage_get_account_by_id(account_id, EMAIL_ACC_GET_OPT_ACCOUNT_NAME,  &account, true, &error) || !account) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed - %d", error);
+               goto FINISH_OFF;
+       }
+
+       if (account )
+               emstorage_free_account(&account, 1, NULL);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mailbox_id  FROM mail_box_tbl WHERE account_id = %d AND mailbox_type = %d ", account_id, mailbox_type);
+
+       EM_DEBUG_LOG("query = [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE) {
+               EM_DEBUG_EXCEPTION("no matched mailbox_name found...");
+               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       _get_stmt_field_data_int(hStmt, mailbox_id, 0);
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_name_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, char **mailbox_name, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_type[%d], mailbox_name[%p], transaction[%d], err_code[%p]", account_id, mailbox_type, mailbox_name, transaction, err_code);
+       if (account_id < FIRST_ACCOUNT_ID || (mailbox_type < EMAIL_MAILBOX_TYPE_INBOX || mailbox_type > EMAIL_MAILBOX_TYPE_ALL_EMAILS) || !mailbox_name)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], mailbox_type[%d], mailbox_name[%p]", account_id, mailbox_type, mailbox_name);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t* account = NULL;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       /*  Check whether the account exists. */
+       if (!emstorage_get_account_by_id(account_id, EMAIL_ACC_GET_OPT_ACCOUNT_NAME,  &account, true, &error) || !account) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed - %d", error);
+               goto FINISH_OFF;
+       }
+
+       if (account )
+               emstorage_free_account(&account, 1, NULL);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mailbox_name  FROM mail_box_tbl WHERE account_id = %d AND mailbox_type = %d ", account_id, mailbox_type);
+
+       EM_DEBUG_LOG("query = [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE) {
+               EM_DEBUG_EXCEPTION("no matched mailbox_name found...");
+               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       _get_stmt_field_data_string(hStmt, mailbox_name, 0, 0);
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_update_mailbox_modifiable_yn(int account_id, int local_yn, char *mailbox_name, int modifiable_yn, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], local_yn [%d], mailbox_name [%p], modifiable_yn [%d], transaction [%d], err_code [%p]", account_id, local_yn, mailbox_name, modifiable_yn, transaction, err_code);
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_box_tbl SET"
+               " modifiable_yn = %d"
+               " WHERE account_id = %d"
+               " AND local_yn = %d"
+               " AND mailbox_name = '%s'"
+               , modifiable_yn
+               , account_id
+               , local_yn
+               , mailbox_name);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+
+
+INTERNAL_FUNC int emstorage_update_mailbox_total_count(int account_id, int input_mailbox_id, int total_count_on_server, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], input_mailbox_id[%d], total_count_on_server[%d], transaction[%d], err_code[%p]", account_id, input_mailbox_id, total_count_on_server,  transaction, err_code);
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       if (account_id <= 0 || input_mailbox_id <= 0)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], input_mailbox_id[%d]", account_id, input_mailbox_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_box_tbl SET"
+               " total_mail_count_on_server = %d"
+               " WHERE account_id = %d"
+               " AND mailbox_id = %d"
+               , total_count_on_server
+               , account_id
+               , input_mailbox_id);
+       EM_DEBUG_LOG("query[%s]", sql_query_string);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+
+
+INTERNAL_FUNC int emstorage_update_mailbox(int account_id, int local_yn, int input_mailbox_id, emstorage_mailbox_tbl_t* result_mailbox, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], input_mailbox_id[%d], result_mailbox[%p], transaction[%d], err_code[%p]", account_id, local_yn, input_mailbox_id, result_mailbox, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || input_mailbox_id <= 0 || !result_mailbox)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], local_yn[%d], input_mailbox_id[%d], result_mailbox[%p]", account_id, local_yn, input_mailbox_id, result_mailbox);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       DB_STMT hStmt = NULL;
+       int i = 0;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       if (local_yn != -1) {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                       "UPDATE mail_box_tbl SET"
+                       "  mailbox_id = ?"
+                       ", mailbox_name = ?"
+                       ", mailbox_type = ?"
+                       ", alias = ?"
+                       ", deleted_flag = ?"
+                       ", modifiable_yn= ?"
+                       ", mail_slot_size= ?"
+                       ", total_mail_count_on_server = ?"
+                       " WHERE account_id = %d"
+                       " AND local_yn = %d"
+                       " AND mailbox_id = '%d'"
+                       , account_id
+                       , local_yn
+                       , input_mailbox_id);
+       }
+       else {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                       "UPDATE mail_box_tbl SET"
+                       "  mailbox_id = ?"
+                       ", mailbox_name = ?"
+                       ", mailbox_type = ?"
+                       ", alias = ?"
+                       ", deleted_flag = ?"
+                       ", modifiable_yn= ?"
+                       ", mail_slot_size= ?"
+                       ", total_mail_count_on_server = ?"
+                       " WHERE account_id = %d"
+                       " AND mailbox_id = '%d'"
+                       , account_id
+                       , input_mailbox_id);
+       }
+
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       _bind_stmt_field_data_int(hStmt, i++, result_mailbox->mailbox_id);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)result_mailbox->mailbox_name ? result_mailbox->mailbox_name : "", 0, MAILBOX_NAME_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, result_mailbox->mailbox_type);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)result_mailbox->alias ? result_mailbox->alias : "", 0, ALIAS_LEN_IN_MAIL_BOX_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, result_mailbox->deleted_flag);
+       _bind_stmt_field_data_int(hStmt, i++, result_mailbox->modifiable_yn);
+       _bind_stmt_field_data_int(hStmt, i++, result_mailbox->mail_slot_size);
+       _bind_stmt_field_data_int(hStmt, i++, result_mailbox->total_mail_count_on_server);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, char *mailbox_name, email_mailbox_type_e new_mailbox_type, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], mailbox_name[%s], new_mailbox_type[%d], transaction[%d], err_code[%p]", account_id, local_yn, mailbox_name, new_mailbox_type, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || !mailbox_name)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], local_yn[%d], mailbox_name[%s]", account_id, local_yn, mailbox_name);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       EM_DEBUG_LOG("emstorage_update_mailbox_type");
+
+       DB_STMT hStmt_box_tbl = NULL;
+       DB_STMT hStmt_mail_tbl = NULL;
+       int i = 0;
+
+       /*  Update mail_box_tbl */
+       if (local_yn != -1) {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string)-1,
+                       "UPDATE mail_box_tbl SET"
+                       " mailbox_type = ?"
+                       " WHERE account_id = %d"
+                       " AND local_yn = %d"
+                       " AND mailbox_name = '%s'"
+                       , account_id
+                       , local_yn
+                       , mailbox_name);
+       }
+       else {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string)-1,
+                       "UPDATE mail_box_tbl SET"
+                       " mailbox_type = ?"
+                       " WHERE account_id = %d"
+                       " AND mailbox_name = '%s'"
+                       , account_id
+                       , mailbox_name);
+       }
+
+       EM_DEBUG_LOG("SQL(%s)", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt_box_tbl, NULL), rc);
+
+       if(SQLITE_OK != rc) {
+               EM_DEBUG_EXCEPTION("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle));
+               error = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF; 
+       }
+
+       _bind_stmt_field_data_int(hStmt_box_tbl, i++, new_mailbox_type);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt_box_tbl), rc);
+
+       if(rc == SQLITE_FULL) {
+               EM_DEBUG_EXCEPTION("sqlite3_step fail:%d", rc);
+               error   = EMAIL_ERROR_MAIL_MEMORY_FULL;
+               goto FINISH_OFF; 
+       }
+       
+       if(rc != SQLITE_ROW && rc != SQLITE_DONE) {
+               EM_DEBUG_EXCEPTION("sqlite3_step fail:%d", rc);
+               error = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF; 
+       }
+       
+
+       /*  Update mail_tbl */
+       i = 0;
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                       "UPDATE mail_tbl SET"
+                       " mailbox_type = ?"
+                       " WHERE account_id = %d"
+                       " AND mailbox_name = '%s'"
+                       , account_id
+                       , mailbox_name);
+
+       EM_DEBUG_LOG("SQL[%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt_mail_tbl, NULL), rc);
+       if(SQLITE_OK != rc) {
+               EM_DEBUG_EXCEPTION("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle));
+               error = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF; 
+       }
+       
+       _bind_stmt_field_data_int(hStmt_mail_tbl, i++, new_mailbox_type);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt_mail_tbl), rc);
+       if(rc == SQLITE_FULL) {
+               EM_DEBUG_EXCEPTION("sqlite3_step fail:%d", rc);
+               error = EMAIL_ERROR_MAIL_MEMORY_FULL;
+               goto FINISH_OFF; 
+       }
+       
+       if(rc != SQLITE_ROW && rc != SQLITE_DONE){
+               EM_DEBUG_EXCEPTION("sqlite3_step fail:%d", rc);
+               error = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF; 
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (hStmt_box_tbl != NULL)  {
+               rc = sqlite3_finalize(hStmt_box_tbl);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       if (hStmt_mail_tbl != NULL)  {
+               rc = sqlite3_finalize(hStmt_mail_tbl);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_set_local_mailbox(int input_mailbox_id, int input_is_local_mailbox, int transaction)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], new_mailbox_type[%d], transaction[%d], err_code[%p]", input_mailbox_id, input_is_local_mailbox, transaction);
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       if (input_mailbox_id < 0)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       EM_DEBUG_LOG("emstorage_update_mailbox_type");
+
+       DB_STMT hStmt = NULL;
+       int i = 0;
+
+       /*  Update mail_box_tbl */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_box_tbl SET"
+               " local_yn = ?"
+               " WHERE mailbox_id = %d"
+               , input_mailbox_id);
+
+       EM_DEBUG_LOG("SQL(%s)", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       _bind_stmt_field_data_int(hStmt, i++, input_is_local_mailbox);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+               hStmt = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+INTERNAL_FUNC int emstorage_set_field_of_mailbox_with_integer_value(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, char *input_field_name, int input_value, int transaction)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d] input_mailbox_id_array[%p] input_mailbox_id_count[%d] input_field_name[%p] input_value[%d] err_code[%p]", input_account_id, input_mailbox_id_array, input_mailbox_id_count, input_field_name, input_value, transaction);
+       int i = 0;
+       int err = EMAIL_ERROR_NONE;
+       int rc = 0;
+       int result = false;
+       int cur_mailbox_id_string = 0;
+       int mailbox_id_string_buffer_length = 0;
+       char  sql_query_string[QUERY_SIZE] = {0, };
+       char *mailbox_id_string_buffer = NULL;
+       char *parameter_string = NULL;
+       sqlite3 *local_db_handle = NULL;
+
+       if (input_mailbox_id_array == NULL || input_mailbox_id_count == 0 || input_field_name == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+
+       /* Generating mail id list string */
+       mailbox_id_string_buffer_length = MAILBOX_ID_STRING_LENGTH * input_mailbox_id_count;
+
+       mailbox_id_string_buffer = em_malloc(mailbox_id_string_buffer_length);
+
+       if(!mailbox_id_string_buffer) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < input_mailbox_id_count; i++)
+               cur_mailbox_id_string += SNPRINTF_OFFSET(mailbox_id_string_buffer, cur_mailbox_id_string, mailbox_id_string_buffer_length, "%d,", input_mailbox_id_array[i]);
+
+       if(EM_SAFE_STRLEN(mailbox_id_string_buffer) > 1)
+               mailbox_id_string_buffer[EM_SAFE_STRLEN(mailbox_id_string_buffer) - 1] = NULL_CHAR;
+
+       /* Generating notification parameter string */
+       parameter_string = em_malloc(mailbox_id_string_buffer_length + EM_SAFE_STRLEN(input_field_name) + 2);
+
+       if(!parameter_string) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(parameter_string, QUERY_SIZE, "%s%c%s", input_field_name, 0x01, mailbox_id_string_buffer);
+
+       /* Write query string */
+       SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_box_tbl SET %s = %d WHERE mailbox_id in (%s) ", input_field_name, input_value, mailbox_id_string_buffer);
+
+       EM_DEBUG_LOG("sql_query_string [%s]", sql_query_string);
+
+       /* Execute query */
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, err);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       if (sqlite3_changes(local_db_handle) == 0)
+               EM_DEBUG_LOG("no mail matched...");
+
+       result = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, result, err);
+       _DISCONNECT_DB;
+
+       if (result && parameter_string && !emcore_notify_storage_event(NOTI_MAILBOX_FIELD_UPDATE, input_account_id, 0, parameter_string, input_value))
+               EM_DEBUG_EXCEPTION("emcore_notify_storage_event failed : NOTI_MAIL_FIELD_UPDATE [%s,%d]", input_field_name, input_value);
+
+       EM_SAFE_FREE(mailbox_id_string_buffer);
+       EM_SAFE_FREE(parameter_string);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emstorage_add_mailbox(emstorage_mailbox_tbl_t* mailbox_tbl, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_tbl[%p], transaction[%d], err_code[%p]", mailbox_tbl, transaction, err_code);
+
+       if (!mailbox_tbl)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0,};
+       char **result = NULL;
+       time_t current_time;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       EM_SAFE_STRCPY(sql_query_string, "SELECT max(rowid) FROM mail_box_tbl;");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       time(&current_time);
+
+       if (NULL == result[1])
+               rc = 1;
+       else
+               rc = atoi(result[1]) + 1;
+       sqlite3_free_table(result);
+
+       memset(sql_query_string, 0, sizeof(char) * QUERY_SIZE);
+
+       mailbox_tbl->mailbox_id = rc;
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_box_tbl VALUES "
+               "( ?"    /* mailbox_id */
+               ", ?"    /* account_id */
+               ", ?"    /* local_yn */
+               ", ?"    /* mailbox_name */
+               ", ?"    /* mailbox_type */
+               ", ?"    /* alias */
+               ", ?"    /* deleted_flag */
+               ", ?"    /* modifiable_yn */
+               ", ?"    /* total_mail_count_on_server */
+               ", ?"    /* has_archived_mails */
+               ", ?"    /* mail_slot_size */
+               ", ?"    /* no_select */
+               ", ? )");/* last_sync_time */
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("After sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       int col_index = 0;
+
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->mailbox_id);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->account_id);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->local_yn);
+       _bind_stmt_field_data_string(hStmt, col_index++, (char *)mailbox_tbl->mailbox_name, 0, MAILBOX_NAME_LEN_IN_MAIL_BOX_TBL);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->mailbox_type);
+       _bind_stmt_field_data_string(hStmt, col_index++, (char *)mailbox_tbl->alias, 0, ALIAS_LEN_IN_MAIL_BOX_TBL);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->deleted_flag);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->modifiable_yn);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->total_mail_count_on_server);
+       _bind_stmt_field_data_int(hStmt, col_index++, 0);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->mail_slot_size);
+       _bind_stmt_field_data_int(hStmt, col_index++, mailbox_tbl->no_select);
+       _bind_stmt_field_data_int(hStmt, col_index++, current_time);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%dn", rc));
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (error == EMAIL_ERROR_NONE && !emcore_notify_storage_event(NOTI_MAILBOX_ADD, mailbox_tbl->account_id, mailbox_tbl->mailbox_id, mailbox_tbl->mailbox_name, mailbox_tbl->mailbox_type))
+               EM_DEBUG_EXCEPTION("emcore_notify_storage_event[ NOTI_MAILBOX_ADD] : Notification Failed");
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_set_all_mailbox_modifiable_yn(int account_id, int modifiable_yn, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], modifiable_yn[%d], err_code[%p]", account_id, modifiable_yn, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID)  {
+
+               EM_DEBUG_EXCEPTION("account_id[%d]", account_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0,};
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_box_tbl SET modifiable_yn = %d WHERE account_id = %d", modifiable_yn, account_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)
+               EM_DEBUG_EXCEPTION("All mailbox_name modifiable_yn set to 0 already");
+
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+
+}
+
+INTERNAL_FUNC int emstorage_delete_mailbox(int account_id, int local_yn, int input_mailbox_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], local_yn[%d], input_mailbox_id[%d], transaction[%d], err_code[%p]", account_id, local_yn, input_mailbox_id, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], local_yn[%d], input_mailbox_id[%d]", account_id, local_yn, input_mailbox_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       if (local_yn == -1)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_box_tbl WHERE account_id = %d ", account_id);
+       else
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_box_tbl WHERE account_id = %d AND local_yn = %d ", account_id, local_yn);
+
+       if (input_mailbox_id > 0)  {            /*  0 means all mailbox_name */
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(1+ EM_SAFE_STRLEN(sql_query_string)), "AND mailbox_id = %d", input_mailbox_id);
+       }
+
+       EM_DEBUG_LOG("mailbox sql_query_string [%s]", sql_query_string);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no (matched) mailbox_name found...");
+               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+               ret = true;
+       }
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if(error == EMAIL_ERROR_NONE) {
+               if (!emcore_notify_storage_event(NOTI_MAILBOX_DELETE, account_id, input_mailbox_id, NULL, 0))
+                       EM_DEBUG_EXCEPTION("emcore_notify_storage_event[ NOTI_MAILBOX_ADD] : Notification Failed");
+       }
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_mailbox(emstorage_mailbox_tbl_t** mailbox_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_list[%p], count[%d], err_code[%p]", mailbox_list, count, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (count > 0)  {
+               if (!mailbox_list || !*mailbox_list)  {
+                       EM_DEBUG_EXCEPTION(" mailbox_list[%p], count[%d]", mailbox_list, count);
+
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               emstorage_mailbox_tbl_t* p = *mailbox_list;
+               int i = 0;
+
+               for (; i < count; i++) {
+                       EM_SAFE_FREE(p[i].mailbox_name);
+                       EM_SAFE_FREE(p[i].alias);
+               }
+
+               EM_SAFE_FREE(p); *mailbox_list = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_count_read_mail_uid(int account_id, char *mailbox_name, int *count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_name[%p], count[%p], transaction[%d], err_code[%p]", account_id, mailbox_name , count,  transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || !mailbox_name || !count)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_name[%p], count[%p], exist[%p]", account_id, mailbox_name, count);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_read_mail_uid_tbl WHERE account_id = %d AND mailbox_name = '%s'  ", account_id, mailbox_name);
+       EM_DEBUG_LOG(">>> SQL [ %s ] ", sql_query_string);
+
+       char **result;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       *count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+
+INTERNAL_FUNC int emstorage_check_read_mail_uid(int account_id, char *mailbox_name, char *uid, int *exist, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_name[%p], uid[%p], exist[%p], transaction[%d], err_code[%p]", account_id, mailbox_name , uid, exist, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || !uid || !exist)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_name[%p], uid[%p], exist[%p]", account_id, mailbox_name , uid, exist);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       if (mailbox_name)  {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_read_mail_uid_tbl WHERE account_id = %d AND mailbox_name = '%s' AND s_uid = '%s' ", account_id, mailbox_name, uid);
+       }
+       else  {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_read_mail_uid_tbl WHERE account_id = %d AND s_uid = '%s' ", account_id, uid);
+       }
+
+       char **result;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       *exist = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       if (*exist > 0)
+               *exist = 1;
+       else
+               *exist = 0;
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_downloaded_mail(int mail_id, emstorage_mail_tbl_t** mail, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], mail[%p], err_code[%p]", mail_id, mail, err_code);
+
+       if (!mail || mail_id <= 0) {
+               EM_DEBUG_EXCEPTION("mail_id[%d], mail[%p]", mail_id, mail);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false, temp_rule;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_read_mail_uid_tbl WHERE local_uid = %d", mail_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("sqlite3_prepare hStmt = %p", hStmt);
+
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       *mail = (emstorage_mail_tbl_t*)malloc(sizeof(emstorage_mail_tbl_t));
+       if (*mail == NULL) {
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               EM_DEBUG_EXCEPTION("Memory allocation for mail failed.");
+               goto FINISH_OFF;
+
+       }
+       memset(*mail, 0x00, sizeof(emstorage_mail_tbl_t));
+
+       _get_stmt_field_data_int(hStmt, &((*mail)->account_id), ACCOUNT_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_int(hStmt, &((*mail)->mailbox_id), LOCAL_MAILBOX_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_string(hStmt, &((*mail)->mailbox_name), 0, MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_int(hStmt, &((*mail)->mail_id), LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_string(hStmt, &((*mail)->server_mailbox_name), 0, MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_string(hStmt, &((*mail)->server_mail_id), 0, S_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_int(hStmt, &((*mail)->mail_size), DATA1_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+       _get_stmt_field_data_int(hStmt, &temp_rule, FLAG_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+
+       (*mail)->server_mail_status = 1;
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_downloaded_list(int account_id, int mailbox_id, emstorage_read_mail_uid_tbl_t** read_mail_uid, int *count, int transaction, int *err_code)
+{
+       EM_PROFILE_BEGIN(emStorageGetDownloadList);
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_id[%d], read_mail_uid[%p], count[%p], transaction[%d], err_code[%p]", account_id, mailbox_id, read_mail_uid, count, transaction, err_code);
+       if (account_id < FIRST_ACCOUNT_ID || !read_mail_uid || !count)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_id[%s], read_mail_uid[%p], count[%p]", account_id, mailbox_id, read_mail_uid, count);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       emstorage_read_mail_uid_tbl_t* p_data_tbl = NULL;
+       int i = 0;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       if (mailbox_id)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_read_mail_uid_tbl WHERE account_id = %d AND mailbox_id = %d", account_id, mailbox_id);
+       else
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_read_mail_uid_tbl WHERE account_id = %d", account_id);
+
+       EM_DEBUG_LOG(" sql_query_string : %s", sql_query_string);
+
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       char **result;
+       /*  rc = sqlite3_get_table(local_db_handle, sql_query_string, &result, count, NULL, NULL); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, count, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       sqlite3_free_table(result);
+       if (*count == 0)  {
+               EM_DEBUG_LOG("No mail found in mail_read_mail_uid_tbl");
+               ret = true;
+               goto FINISH_OFF;
+       }
+
+
+       if (!(p_data_tbl = (emstorage_read_mail_uid_tbl_t*)malloc(sizeof(emstorage_read_mail_uid_tbl_t) * *count)))  {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(p_data_tbl, 0x00, sizeof(emstorage_read_mail_uid_tbl_t)* *count);
+
+       for (i = 0; i < *count; ++i)  {
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].account_id), ACCOUNT_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].mailbox_id),LOCAL_MAILBOX_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].local_uid), LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].mailbox_name), 0, MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].s_uid), 0, S_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].data1), DATA1_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].data2), 0, DATA2_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].flag), FLAG_IDX_IN_MAIL_READ_MAIL_UID_TBL);
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *read_mail_uid = p_data_tbl;
+       else if (p_data_tbl)
+               emstorage_free_read_mail_uid(&p_data_tbl, *count, NULL);
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(emStorageGetDownloadList);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_downloaded_mail_size(int account_id, char *mailbox_id, int local_uid, char *mailbox_name, char *uid, int *mail_size, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_id[%p], locacal_uid[%d], mailbox_name[%p], uid[%p], mail_size[%p], transaction[%d], err_code[%p]", account_id, mailbox_id, local_uid, mailbox_name, uid, mail_size, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || !mail_size)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_id[%p], locacal_uid[%d], mailbox_name[%p], uid[%p], mail_size[%p]", account_id, mailbox_id, local_uid, mailbox_name, uid, mail_size);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       if (mailbox_name) {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                       "SELECT IFNULL(MAX(data1), 0) FROM mail_read_mail_uid_tbl "
+                       "WHERE account_id = %d "
+                       "AND mailbox_id = '%s' "
+                       "AND local_uid = %d "
+                       "AND mailbox_name = '%s' "
+                       "AND s_uid = '%s'",
+                       account_id, mailbox_id, local_uid, mailbox_name, uid);
+       }
+       else {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                       "SELECT IFNULL(MAX(data1), 0) FROM mail_read_mail_uid_tbl "
+                       "WHERE account_id = %d "
+                       "AND mailbox_id = '%s' "
+                       "AND local_uid = %d "
+                       "AND s_uid = '%s'",
+                       account_id, mailbox_id, local_uid, uid);
+       }
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE) {
+               EM_DEBUG_EXCEPTION(" no matched mail found....");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       _get_stmt_field_data_int(hStmt, mail_size, 0);
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_add_downloaded_mail(emstorage_read_mail_uid_tbl_t* read_mail_uid, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("read_mail_uid[%p], transaction[%d], err_code[%p]", read_mail_uid, transaction, err_code);
+
+       if (!read_mail_uid)  {
+               EM_DEBUG_EXCEPTION("read_mail_uid[%p]", read_mail_uid);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, rc2,  ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       char *sql = "SELECT max(rowid) FROM mail_read_mail_uid_tbl;";
+       char **result = NULL;
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL==result[1]) rc = 1;
+       else rc = atoi(result[1])+1;
+       sqlite3_free_table(result);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_read_mail_uid_tbl VALUES "
+               "( ?"
+               ", ?"
+               ", ?"
+               ", ?"
+               ", ?"
+               ", ?"
+               ", ?"
+               ", ?"
+               ", ? )");
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc2);
+       if (rc2 != SQLITE_OK)  {
+               EM_DEBUG_LOG("sqlite3_prepare hStmt = %p", hStmt);
+               EM_DEBUG_EXCEPTION("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle));
+
+               error = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("account_id VALUE [%d] ", read_mail_uid->account_id);
+       EM_DEBUG_LOG("mailbox_id VALUE [%d] ", read_mail_uid->mailbox_id);
+       EM_DEBUG_LOG("local_uid VALUE [%d] ", read_mail_uid->local_uid);
+       EM_DEBUG_LOG("mailbox_name VALUE [%s] ", read_mail_uid->mailbox_name);
+       EM_DEBUG_LOG("s_uid VALUE [%s] ", read_mail_uid->s_uid);
+       EM_DEBUG_LOG("data1 VALUE [%d] ", read_mail_uid->data1);
+       EM_DEBUG_LOG("data2 VALUE [%s] ", read_mail_uid->data2);
+       EM_DEBUG_LOG("flag VALUE [%d] ", read_mail_uid->flag);
+       EM_DEBUG_LOG("rc VALUE [%d] ", rc);
+
+       _bind_stmt_field_data_int(hStmt, ACCOUNT_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->account_id);
+       _bind_stmt_field_data_int(hStmt, LOCAL_MAILBOX_ID_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->mailbox_id);
+       _bind_stmt_field_data_int(hStmt, LOCAL_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->local_uid);
+       _bind_stmt_field_data_string(hStmt, MAILBOX_NAME_IDX_IN_MAIL_READ_MAIL_UID_TBL, (char *)read_mail_uid->mailbox_name, 0, MAILBOX_NAME_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_string(hStmt, S_UID_IDX_IN_MAIL_READ_MAIL_UID_TBL, (char *)read_mail_uid->s_uid, 0, S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_int(hStmt, DATA1_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->data1);
+       _bind_stmt_field_data_string(hStmt, DATA2_IDX_IN_MAIL_READ_MAIL_UID_TBL, (char *)read_mail_uid->data2, 0, DATA2_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_int(hStmt, FLAG_IDX_IN_MAIL_READ_MAIL_UID_TBL, read_mail_uid->flag);
+       _bind_stmt_field_data_int(hStmt, IDX_NUM_IDX_IN_MAIL_READ_MAIL_UID_TBL, rc);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail[%d] [%s]", rc, sqlite3_errmsg(local_db_handle)));
+
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG(" sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_change_read_mail_uid(int account_id, int mailbox_id, int local_uid, char *mailbox_name, char *uid, emstorage_read_mail_uid_tbl_t* read_mail_uid, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_id[%d], local_uid[%d], mailbox_name[%p], uid[%p], read_mail_uid[%p], transaction[%d], err_code[%p]", account_id, mailbox_id, local_uid, mailbox_name, uid, read_mail_uid, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || !read_mail_uid)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_id[%d], local_uid[%d], mailbox_name[%p], uid[%p], read_mail_uid[%p]", account_id, mailbox_id, local_uid, mailbox_name, uid, read_mail_uid);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_read_mail_uid_tbl SET"
+               "  account_id = ?"
+               ", mailbox_id = ?"
+               ", local_uid  = ?"
+               ", mailbox_name = ?"
+               ", s_uid = ?"
+               ", data1 = ?"
+               ", data2 = ?"
+               ", flag  = ?"
+               " WHERE account_id = ?"
+               " AND mailbox_id  = ?"
+               " AND local_uid   = ?"
+               " AND mailbox_name= ?"
+               " AND s_uid = ?");
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       int i = 0;
+
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->account_id);
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->mailbox_id);
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->local_uid);
+       _bind_stmt_field_data_string(hStmt, i++, (char*)read_mail_uid->mailbox_name, 0, MAILBOX_NAME_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char*)read_mail_uid->s_uid, 0, S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->data1);
+       _bind_stmt_field_data_string(hStmt, i++, (char*)read_mail_uid->data2, 0, DATA2_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, read_mail_uid->flag);
+       _bind_stmt_field_data_int(hStmt, i++, account_id);
+       _bind_stmt_field_data_int(hStmt, i++, mailbox_id);
+       _bind_stmt_field_data_int(hStmt, i++, local_uid);
+       _bind_stmt_field_data_string(hStmt, i++, (char*)mailbox_name, 0, MAILBOX_NAME_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char*)uid, 0, S_UID_LEN_IN_MAIL_READ_MAIL_UID_TBL);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_remove_downloaded_mail(int account_id, char *mailbox_name, char *uid, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_name[%s], uid[%s], transaction[%d], err_code[%p]", account_id, mailbox_name, uid, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox_name[%s], uid[%s]", account_id, mailbox_name, uid);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_read_mail_uid_tbl WHERE account_id = %d ", account_id);
+
+       if (mailbox_name) {             /*  NULL means all mailbox_name */
+               SNPRINTF(sql_query_string+EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string) - (1 + EM_SAFE_STRLEN(sql_query_string)), "AND mailbox_name = '%s' ", mailbox_name);
+       }
+
+       if (uid) {              /*  NULL means all mail */
+               SNPRINTF(sql_query_string+EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string) - (1 + EM_SAFE_STRLEN(sql_query_string)), "AND s_uid='%s' ", uid);
+       }
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_read_mail_uid(emstorage_read_mail_uid_tbl_t** read_mail_uid, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("read_mail_uid[%p], count[%d], err_code[%p]", read_mail_uid, count, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (count > 0)  {
+               if (!read_mail_uid || !*read_mail_uid)  {
+                       EM_DEBUG_EXCEPTION(" read_mail_uid[%p], count[%d]", read_mail_uid, count);
+
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               emstorage_read_mail_uid_tbl_t* p = *read_mail_uid;
+               int i;
+
+               for (i = 0; i < count; i++)  {
+                       EM_SAFE_FREE(p[i].mailbox_name);
+                       EM_SAFE_FREE(p[i].s_uid);
+                       EM_SAFE_FREE(p[i].data2);
+               }
+
+               EM_SAFE_FREE(p); *read_mail_uid = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_rule_count(int account_id, int *count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], count[%p], transaction[%d], err_code[%p]", account_id, count, transaction, err_code);
+
+       if (account_id != ALL_ACCOUNT || !count) {              /*  only global rule supported. */
+               EM_DEBUG_EXCEPTION(" account_id[%d], count[%p]", account_id, count);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error =  EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_rule_tbl WHERE account_id = %d", account_id);
+
+       char **result;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       *count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_rule(int account_id, int type, int start_idx, int *select_num, int *is_completed, emstorage_rule_tbl_t** rule_list, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], type[%d], start_idx[%d], select_num[%p], is_completed[%p], rule_list[%p], transaction[%d], err_code[%p]", account_id, type, start_idx, select_num, is_completed, rule_list, transaction, err_code);
+
+       if (account_id != ALL_ACCOUNT || !select_num || !is_completed || !rule_list) {          /*  only global rule supported. */
+               EM_DEBUG_EXCEPTION(" account_id[%d], type[%d], start_idx[%d], select_num[%p], is_completed[%p], rule_list[%p]", account_id, type, start_idx, select_num, is_completed, rule_list);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       emstorage_rule_tbl_t* p_data_tbl = NULL;
+       int i = 0, count = 0;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int rc;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       if (type)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_rule_tbl WHERE account_id = %d AND type = %d", account_id, type);
+       else
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_rule_tbl WHERE account_id = %d ORDER BY type", account_id);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       char **result;
+       /*  rc = sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, NULL, NULL); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       sqlite3_free_table(result);
+
+       if (count == 0)  {
+               EM_DEBUG_LOG(" no matched rule found...");
+               ret = true;
+               goto FINISH_OFF;
+       }
+
+
+       if (!(p_data_tbl = (emstorage_rule_tbl_t*)malloc(sizeof(emstorage_rule_tbl_t) * count))) {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(p_data_tbl, 0x00, sizeof(emstorage_rule_tbl_t) * count);
+
+       for (i = 0; i < count; i++)  {
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].account_id), ACCOUNT_ID_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].rule_id), RULE_ID_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].type), TYPE_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].value), 0, VALUE_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].action_type), ACTION_TYPE_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].target_mailbox_id), TARGET_MAILBOX_ID_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].flag1), FLAG1_IDX_IN_MAIL_RULE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].flag2), FLAG2_IDX_IN_MAIL_RULE_TBL);
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       EM_DEBUG_LOG("[%d] rules found.", count);
+
+       if (ret == true)  {
+               *rule_list = p_data_tbl;
+               *select_num = count;
+       }
+       else if (p_data_tbl != NULL)
+               emstorage_free_rule(&p_data_tbl, count, NULL); /* CID FIX */
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("  sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_rule_by_id(int account_id, int rule_id, emstorage_rule_tbl_t** rule, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], rule_id[%d], rule[%p], transaction[%d], err_code[%p]", account_id, rule_id, rule, transaction, err_code);
+
+       if (account_id != ALL_ACCOUNT || !rule)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], rule_id[%d], rule[%p]", account_id, rule_id, rule);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       emstorage_rule_tbl_t* p_data_tbl = NULL;
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_rule_tbl WHERE account_id = %d AND rule_id = %d", account_id, rule_id);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION(" no matched rule found...");
+               error = EMAIL_ERROR_FILTER_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (!(p_data_tbl = (emstorage_rule_tbl_t*)malloc(sizeof(emstorage_rule_tbl_t))))  {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(p_data_tbl, 0x00, sizeof(emstorage_rule_tbl_t));
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), ACCOUNT_ID_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->rule_id), RULE_ID_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->type), TYPE_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->value), 0, VALUE_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->action_type), ACTION_TYPE_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->target_mailbox_id), TARGET_MAILBOX_ID_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->flag1), FLAG1_IDX_IN_MAIL_RULE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->flag2), FLAG2_IDX_IN_MAIL_RULE_TBL);
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *rule = p_data_tbl;
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG(" before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_change_rule(int account_id, int rule_id, emstorage_rule_tbl_t* new_rule, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], rule_id[%d], new_rule[%p], transaction[%d], err_code[%p]", account_id, rule_id, new_rule, transaction, err_code);
+
+       if (account_id != ALL_ACCOUNT || !new_rule) {           /*  only global rule supported. */
+               EM_DEBUG_EXCEPTION(" account_id[%d], rule_id[%d], new_rule[%p]", account_id, rule_id, new_rule);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_rule_tbl SET"
+               "  type = ?"
+               ", value = ?"
+               ", action_type = ?"
+               ", target_mailbox_id = ?"
+               ", flag1 = ?"
+               ", flag2 = ?"
+               " WHERE account_id = ?"
+               " AND rule_id = ?");
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG(" Before sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       int i = 0;
+
+       _bind_stmt_field_data_int(hStmt, i++, new_rule->type);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)new_rule->value, 0, VALUE_LEN_IN_MAIL_RULE_TBL);
+       _bind_stmt_field_data_int(hStmt, i++, new_rule->action_type);
+       _bind_stmt_field_data_int(hStmt, i++, new_rule->target_mailbox_id);
+       _bind_stmt_field_data_int(hStmt, i++, new_rule->flag1);
+       _bind_stmt_field_data_int(hStmt, i++, new_rule->flag2);
+       _bind_stmt_field_data_int(hStmt, i++, account_id);
+       _bind_stmt_field_data_int(hStmt, i++, rule_id);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_find_rule(emstorage_rule_tbl_t* rule, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("rule[%p], transaction[%d], err_code[%p]", rule, transaction, err_code);
+
+       if (!rule || rule->account_id != ALL_ACCOUNT) {         /*  only global rule supported. */
+               if (rule != NULL)
+                       EM_DEBUG_EXCEPTION(" rule->account_id[%d]", rule->account_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int error = EMAIL_ERROR_NONE;
+       int rc, ret = false;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "SELECT rule_id FROM mail_rule_tbl WHERE type = %d AND UPPER(value) = UPPER('%s')",
+               rule->type, rule->value);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION(" no matched rule found...");
+               error = EMAIL_ERROR_FILTER_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_add_rule(emstorage_rule_tbl_t* rule, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("rule[%p], transaction[%d], err_code[%p]", rule, transaction, err_code);
+
+       if (!rule || rule->account_id != ALL_ACCOUNT)  {        /*  only global rule supported. */
+               if (rule != NULL)
+                       EM_DEBUG_EXCEPTION(" rule->account_id[%d]", rule->account_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, rc_2, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       char *sql;
+       char **result;
+       sql = "SELECT max(rowid) FROM mail_rule_tbl;";
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL==result[1])
+               rc = 1;
+       else
+               rc = atoi(result[1])+1;
+       sqlite3_free_table(result);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_rule_tbl VALUES "
+               "( ?"           /*  account id */
+               ", ?"           /*  rule_id */
+               ", ?"           /*  type */
+               ", ?"           /*  value */
+               ", ?"           /*  action_type */
+               ", ?"           /*  target_mailbox_id */
+               ", ?"           /*  flag1 */
+               ", ?)");        /*  flag2 */
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc_2);
+       if (rc_2 != SQLITE_OK)  {
+               EM_DEBUG_EXCEPTION("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc_2, sqlite3_errmsg(local_db_handle));
+               error = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       _bind_stmt_field_data_int(hStmt, ACCOUNT_ID_IDX_IN_MAIL_RULE_TBL, rule->account_id);
+       _bind_stmt_field_data_int(hStmt, RULE_ID_IDX_IN_MAIL_RULE_TBL, rc);
+       _bind_stmt_field_data_int(hStmt, TYPE_IDX_IN_MAIL_RULE_TBL, rule->type);
+       _bind_stmt_field_data_string(hStmt, VALUE_IDX_IN_MAIL_RULE_TBL, (char*)rule->value, 0, VALUE_LEN_IN_MAIL_RULE_TBL);
+       _bind_stmt_field_data_int(hStmt, ACTION_TYPE_IDX_IN_MAIL_RULE_TBL, rule->action_type);
+       _bind_stmt_field_data_int(hStmt, TARGET_MAILBOX_ID_IDX_IN_MAIL_RULE_TBL, rule->target_mailbox_id);
+       _bind_stmt_field_data_int(hStmt, FLAG1_IDX_IN_MAIL_RULE_TBL, rule->flag1);
+       _bind_stmt_field_data_int(hStmt, FLAG2_IDX_IN_MAIL_RULE_TBL, rule->flag2);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK) {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_rule(int account_id, int rule_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], rule_id[%d], transaction[%d], err_code[%p]", account_id, rule_id, transaction, err_code);
+
+       if (account_id != ALL_ACCOUNT) {                /*  only global rule supported. */
+               EM_DEBUG_EXCEPTION(" account_id[%d], rule_id[%d]", account_id, rule_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_rule_tbl WHERE account_id = %d AND rule_id = %d", account_id, rule_id);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0) {
+               EM_DEBUG_EXCEPTION(" no matched rule found...");
+
+               error = EMAIL_ERROR_FILTER_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_rule(emstorage_rule_tbl_t** rule_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("rule_list[%p], conut[%d], err_code[%p]", rule_list, count, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (count > 0) {
+               if (!rule_list || !*rule_list) {
+                       EM_DEBUG_EXCEPTION(" rule_list[%p], conut[%d]", rule_list, count);
+
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               emstorage_rule_tbl_t* p = *rule_list;
+               int i = 0;
+
+               for (; i < count; i++) {
+                       EM_SAFE_FREE(p[i].value);
+               }
+
+               EM_SAFE_FREE(p); *rule_list = NULL;
+       }
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mail_count(int account_id, const char *mailbox_name, int *total, int *unseen, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_name[%s], total[%p], unseen[%p], transaction[%d], err_code[%p]", account_id, mailbox_name, total, unseen, transaction, err_code);
+
+       if (!total && !unseen) {
+               EM_DEBUG_EXCEPTION(" accoun_id[%d], mailbox_name[%s], total[%p], unseen[%p]", account_id, mailbox_name, total, unseen);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char err_msg[1024];
+
+
+       memset(&sql_query_string, 0x00, sizeof(sql_query_string));
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       if (total)  {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_tbl");
+
+               if (account_id != ALL_ACCOUNT)  {
+                       SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " WHERE account_id = %d", account_id);
+                       if (mailbox_name)
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " AND UPPER(mailbox_name) =  UPPER('%s')", mailbox_name);
+               }
+               else if (mailbox_name)
+                       SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " WHERE UPPER(mailbox_name) =  UPPER('%s')", mailbox_name);
+
+#ifdef USE_GET_RECORD_COUNT_API
+               char **result;
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF2; },
+                       ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               *total = atoi(result[1]);
+               sqlite3_free_table(result);
+#else
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+               EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF2; },
+                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF2; },
+                       ("sqlite3_step fail:%d", rc));
+               _get_stmt_field_data_int(hStmt, total, 0);
+#endif         /*  USE_GET_RECORD_COUNT_API */
+       }
+
+       if (unseen)  {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_tbl WHERE flags_seen_field = 0");               /*  fSEEN = 0x01 */
+
+               if (account_id != ALL_ACCOUNT)
+                       SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " AND account_id = %d", account_id);
+
+               if (mailbox_name)
+                       SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " AND mailbox_name = '%s'", mailbox_name);
+               else
+                       SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " AND mailbox_type NOT IN (3, 5)");
+
+               char **result;
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+               *unseen = atoi(result[1]);
+               sqlite3_free_table(result);
+
+       }
+FINISH_OFF:
+       ret = true;
+
+FINISH_OFF2:
+
+#ifndef USE_PREPARED_QUERY_
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" EDBStmtClearRow failed - %d: %s", rc, err_msg);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+#endif
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mail_field_by_id(int mail_id, int type, emstorage_mail_tbl_t** mail, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], type[%d], mail[%p], transaction[%d], err_code[%p]", mail_id, type, mail, transaction, err_code);
+
+       if (mail_id <= 0 || !mail)  {
+               EM_DEBUG_EXCEPTION("mail_id[%d], mail[%p]", mail_id, mail);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       emstorage_mail_tbl_t* p_data_tbl = (emstorage_mail_tbl_t*)malloc(sizeof(emstorage_mail_tbl_t));
+
+       if (p_data_tbl == NULL)  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               return false;
+       }
+
+       memset(p_data_tbl, 0x00, sizeof(emstorage_mail_tbl_t));
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       switch (type)  {
+               case RETRIEVE_SUMMARY:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "SELECT account_id, mail_id, mailbox_id, mailbox_name, server_mail_status, server_mailbox_name, server_mail_id, file_path_plain, file_path_html, flags_seen_field, save_status, lock_status, thread_id, thread_item_count FROM mail_tbl WHERE mail_id = %d", mail_id);
+                       break;
+
+               case RETRIEVE_FIELDS_FOR_DELETE:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "SELECT account_id, mail_id, server_mail_status, server_mailbox_name, server_mail_id FROM mail_tbl WHERE mail_id = %d", mail_id);
+                       break;
+
+               case RETRIEVE_ACCOUNT:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "SELECT account_id FROM mail_tbl WHERE mail_id = %d", mail_id);
+                       break;
+
+               case RETRIEVE_FLAG:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "SELECT account_id, mailbox_name, flags_seen_field, thread_id, mailbox_id FROM mail_tbl WHERE mail_id = %d", mail_id);
+                       break;
+
+               default :
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM : type [%d]", type);
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no matched mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+       switch (type)  {
+               case RETRIEVE_SUMMARY:
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), 0);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mail_id), 1);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mailbox_id), 2);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->mailbox_name), 0, 3);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->server_mail_status), 4);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->server_mailbox_name), 0, 5);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->server_mail_id), 0, 6);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->file_path_plain), 0, 7);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->file_path_html), 0, 8);
+                       _get_stmt_field_data_char(hStmt, &(p_data_tbl->flags_seen_field), 9);
+                       _get_stmt_field_data_int(hStmt, (int*)&(p_data_tbl->save_status), 10);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->lock_status), 11);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->thread_id), 12);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->thread_item_count), 13);
+                       break;
+
+               case RETRIEVE_FIELDS_FOR_DELETE:
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), 0);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mail_id), 1);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->server_mail_status), 2);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->server_mailbox_name), 0, 3);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->server_mail_id), 0, 4);
+                       break;
+
+               case RETRIEVE_ACCOUNT:
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), 0);
+                       break;
+
+               case RETRIEVE_FLAG:
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), 0);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->mailbox_name), 0, 1);
+                       _get_stmt_field_data_char(hStmt, &(p_data_tbl->flags_seen_field), 2);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->thread_id), 3);
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mailbox_id), 4);
+                       break;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *mail = p_data_tbl;
+       else if (p_data_tbl != NULL)
+               emstorage_free_mail(&p_data_tbl,  1, NULL);
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mail_field_by_multiple_mail_id(int mail_ids[], int number_of_mails, int type, emstorage_mail_tbl_t** mail, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], number_of_mails [%d], type[%d], mail[%p], transaction[%d], err_code[%p]", mail_ids, number_of_mails, type, mail, transaction, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int query_string_length = 0;
+       int i = 0, item_count = 0, rc = -1, field_count, col_index, cur_sql_query_string = 0;
+       char **result = NULL;
+       char *sql_query_string = NULL;
+       emstorage_mail_tbl_t* p_data_tbl = NULL;
+       sqlite3 *local_db_handle = NULL;
+
+       if (number_of_mails <= 0 || !mail_ids)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       p_data_tbl = (emstorage_mail_tbl_t*)em_malloc(sizeof(emstorage_mail_tbl_t) * number_of_mails);
+
+       query_string_length = (sizeof(char) * 8 * number_of_mails) + 512;
+       sql_query_string = (char*)em_malloc(query_string_length);
+
+       if (p_data_tbl == NULL || sql_query_string == NULL)  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+
+               EM_SAFE_FREE(p_data_tbl);
+               EM_SAFE_FREE(sql_query_string);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_OUT_OF_MEMORY;
+               return false;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       switch (type) {
+               case RETRIEVE_SUMMARY:
+                       cur_sql_query_string = SNPRINTF(sql_query_string, query_string_length,
+                               "SELECT account_id, mail_id, mailbox_name, server_mail_status, server_mailbox_name, server_mail_id, file_path_plain, file_path_html, flags_seen_field, save_status, lock_status, thread_id, thread_item_count FROM mail_tbl WHERE mail_id in (");
+                       field_count = 13;
+                       break;
+
+               case RETRIEVE_FIELDS_FOR_DELETE:
+                       cur_sql_query_string = SNPRINTF(sql_query_string, query_string_length,
+                               "SELECT account_id, mail_id, server_mail_status, server_mailbox_name, server_mail_id FROM mail_tbl WHERE mail_id in (");
+                       field_count = 5;
+                       break;
+
+               case RETRIEVE_ACCOUNT:
+                       cur_sql_query_string = SNPRINTF(sql_query_string, query_string_length,
+                               "SELECT account_id FROM mail_tbl WHERE mail_id in (");
+                       field_count = 1;
+                       break;
+
+               case RETRIEVE_FLAG:
+                       cur_sql_query_string = SNPRINTF(sql_query_string, query_string_length,
+                               "SELECT account_id, mailbox_id, flags_seen_field, thread_id FROM mail_tbl WHERE mail_id in (");
+                       field_count = 4;
+                       break;
+
+               default :
+                       EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM : type [%d]", type);
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+       }
+
+       for(i = 0; i < number_of_mails; i++)
+               cur_sql_query_string += SNPRINTF_OFFSET(sql_query_string, cur_sql_query_string, QUERY_SIZE, "%d,", mail_ids[i]);
+       sql_query_string[EM_SAFE_STRLEN(sql_query_string) - 1] = ')';
+
+       EM_DEBUG_LOG("Query [%s], Length [%d]", sql_query_string, EM_SAFE_STRLEN(sql_query_string));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &item_count, 0, NULL), rc);
+       if (SQLITE_OK != rc && -1 != rc) {
+               EM_DEBUG_EXCEPTION("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle));
+               error = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no matched mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("item_count [%d]", item_count);
+
+       if(number_of_mails != item_count) {
+               EM_DEBUG_EXCEPTION("Can't find all emails");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       col_index = field_count;
+
+       for(i = 0; i < item_count; i++) {
+               switch (type) {
+                       case RETRIEVE_SUMMARY:
+                               _get_table_field_data_int(result, &(p_data_tbl[i].account_id), col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].mail_id), col_index++);
+                               _get_table_field_data_string(result, &(p_data_tbl[i].mailbox_name), 0, col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].server_mail_status), col_index++);
+                               _get_table_field_data_string(result, &(p_data_tbl[i].server_mailbox_name), 0, col_index++);
+                               _get_table_field_data_string(result, &(p_data_tbl[i].server_mail_id), 0, col_index++);
+                               _get_table_field_data_string(result, &(p_data_tbl[i].file_path_plain), 0, col_index++);
+                               _get_table_field_data_string(result, &(p_data_tbl[i].file_path_html), 0, col_index++);
+                               _get_table_field_data_char(result, &(p_data_tbl[i].flags_seen_field), col_index++);
+                               _get_table_field_data_int(result, (int*)&(p_data_tbl[i].save_status), col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].lock_status), col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].thread_id), col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].thread_item_count), col_index++);
+                               break;
+
+                       case RETRIEVE_FIELDS_FOR_DELETE:
+                               _get_table_field_data_int(result, &(p_data_tbl[i].account_id), col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].mail_id), col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].server_mail_status), col_index++);
+                               _get_table_field_data_string(result, &(p_data_tbl[i].server_mailbox_name), 0, col_index++);
+                               _get_table_field_data_string(result, &(p_data_tbl[i].server_mail_id), 0, col_index++);
+                               break;
+
+                       case RETRIEVE_ACCOUNT:
+                               _get_table_field_data_int(result, &(p_data_tbl[i].account_id), col_index++);
+                               break;
+
+                       case RETRIEVE_FLAG:
+                               _get_table_field_data_int(result, &(p_data_tbl[i].account_id), col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].mailbox_id), col_index++);
+                               _get_table_field_data_char(result, &(p_data_tbl[i].flags_seen_field), col_index++);
+                               _get_table_field_data_int(result, &(p_data_tbl[i].thread_id), col_index++);
+                               break;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *mail = p_data_tbl;
+       else
+               emstorage_free_mail(&p_data_tbl, number_of_mails, NULL);
+
+       if (result)
+               sqlite3_free_table(result);
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       EM_SAFE_FREE(sql_query_string);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mail_by_id(int mail_id, emstorage_mail_tbl_t** mail, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], mail[%p], transaction[%d], err_code[%p]", mail_id, mail, transaction, err_code);
+
+       if (mail_id <= 0 || !mail) {
+               EM_DEBUG_EXCEPTION("mail_id[%d], mail[%p]", mail_id, mail);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false, error = EMAIL_ERROR_NONE, count;
+       char conditional_clause[QUERY_SIZE] = {0, };
+       emstorage_mail_tbl_t* p_data_tbl = NULL;
+
+       SNPRINTF(conditional_clause, QUERY_SIZE, "WHERE mail_id = %d", mail_id);
+       EM_DEBUG_LOG("query = [%s]", conditional_clause);
+
+       if(!emstorage_query_mail_tbl(conditional_clause, transaction, &p_data_tbl, &count, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_tbl [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *mail = p_data_tbl;
+       else if (p_data_tbl != NULL)
+               emstorage_free_mail(&p_data_tbl, 1, &error);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_mail_search_start(emstorage_search_filter_t* search, int account_id, char *mailbox_name, int sorting, int *search_handle, int *searched, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("search[%p], account_id[%d], mailbox_name[%p], sorting[%d], search_handle[%p], searched[%p], transaction[%d], err_code[%p]", search, account_id, mailbox_name, sorting, search_handle, searched, transaction, err_code);
+
+       if (!search_handle || !searched)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               EM_DEBUG_FUNC_END("false");
+               return false;
+       }
+
+       emstorage_search_filter_t* p = search;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       int rc, ret = false;
+       int and = false, mail_count = 0;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_tbl");
+
+       if (account_id != ALL_ACCOUNT)  {
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " WHERE account_id = %d", account_id);
+               and = true;
+       }
+
+       if (mailbox_name)  {
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " %s mailbox_name = '%s'", and ? "AND" : "WHERE", mailbox_name);
+               and = true;
+       }
+
+       while (p)  {
+
+               if (p->key_type) {
+                       if (!strncmp(p->key_type, "subject", strlen("subject"))) {
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " %s subject LIKE '%%%%%s%%%%'", and ? "AND" : "WHERE", p->key_value);
+                               and = true;
+                       }
+                       else if (!strncmp(p->key_type, "full_address_from", strlen("full_address_from"))) {
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " %s full_address_from LIKE '%%%%%s%%%%'", and ? "AND" : "WHERE", p->key_value);
+                               and = true;
+                       }
+                       else if (!strncmp(p->key_type, "full_address_to", strlen("full_address_to"))) {
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " %s full_address_to LIKE '%%%%%s%%%%'", and ? "AND" : "WHERE", p->key_value);
+                               and = true;
+                       }
+                       else if (!strncmp(p->key_type, "email_address", strlen("email_address"))) {
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " %s email_address_sender = '%s' OR email_address_recipient = '%s'", and ? "AND" : "WHERE", p->key_value, p->key_value);
+                               and = true;
+                       }
+                       p = p->next;
+               }
+       }
+
+       if (sorting)
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " ORDER BY date_time");
+
+       EM_DEBUG_LOG("sql_query_string [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       char **result;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &mail_count, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       sqlite3_free_table(result);
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)  {
+               *search_handle = (int)hStmt;
+               *searched = mail_count;
+               EM_DEBUG_LOG("mail_count [%d]", mail_count);
+       }
+       else  {
+               if (hStmt != NULL)  {
+                       rc = sqlite3_finalize(hStmt);
+                       if (rc != SQLITE_OK)  {
+                               EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                               error = EMAIL_ERROR_DB_FAILURE;
+                       }
+               }
+
+               EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+               _DISCONNECT_DB;
+       }
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_mail_search_result(int search_handle, emstorage_mail_field_type_t type, void** data, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("search_handle[%d], type[%d], data[%p], transaction[%d], err_code[%p]", search_handle, type, data, transaction, err_code);
+
+       if (search_handle == 0 || !data) {
+               EM_DEBUG_EXCEPTION(" search_handle[%d], type[%d], data[%p]", search_handle, type, data);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       emstorage_mail_tbl_t* p_data_tbl = NULL;
+       DB_STMT hStmt = (DB_STMT)search_handle;
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       switch (type)  {
+               case RETRIEVE_ID:
+                       _get_stmt_field_data_int(hStmt, (int *)data, MAIL_ID_IDX_IN_MAIL_TBL);
+                       break;
+
+               case RETRIEVE_ENVELOPE:
+               case RETRIEVE_ALL:
+                       if (!(p_data_tbl = em_malloc(sizeof(emstorage_mail_tbl_t)))) {
+                               EM_DEBUG_EXCEPTION(" em_malloc failed...");
+
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->mail_id), MAIL_ID_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->account_id), ACCOUNT_ID_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->mailbox_name), 0, MAILBOX_NAME_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->mail_size), MAIL_SIZE_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->server_mail_id), 0, SERVER_MAIL_ID_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->full_address_from), 1, FULL_ADDRESS_FROM_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->full_address_to), 1, FULL_ADDRESS_TO_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->subject), 1, SUBJECT_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->body_download_status), BODY_DOWNLOAD_STATUS_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->file_path_plain), 0, FILE_PATH_PLAIN_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->file_path_html), 0, FILE_PATH_HTML_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->file_path_mime_entity), 0, FILE_PATH_HTML_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_time_t(hStmt, &(p_data_tbl->date_time), DATETIME_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_char  (hStmt, &(p_data_tbl->flags_seen_field), FLAGS_SEEN_FIELD_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->DRM_status), DRM_STATUS_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->priority), PRIORITY_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->save_status), SAVE_STATUS_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->lock_status), LOCK_STATUS_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->report_status), REPORT_STATUS_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->preview_text), 1, PREVIEW_TEXT_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->meeting_request_status), MEETING_REQUEST_STATUS_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->message_class), MESSAGE_CLASS_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->digest_type), DIGEST_TYPE_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, (int*)&(p_data_tbl->smime_type), SMIME_TYPE_IDX_IN_MAIL_TBL);
+
+                       if (type == RETRIEVE_ALL)  {
+                               _get_stmt_field_data_int   (hStmt, &(p_data_tbl->server_mail_status), SERVER_MAIL_STATUS_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->server_mailbox_name), 0, SERVER_MAILBOX_NAME_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->full_address_reply), 1, FULL_ADDRESS_REPLY_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->full_address_cc), 1, FULL_ADDRESS_CC_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->full_address_bcc), 1, FULL_ADDRESS_BCC_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->full_address_return), 1, FULL_ADDRESS_RETURN_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->message_id), 0, MESSAGE_ID_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->email_address_sender), 1, EMAIL_ADDRESS_SENDER_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->email_address_recipient), 1, EMAIL_ADDRESS_RECIPIENT_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_int   (hStmt, &(p_data_tbl->attachment_count), ATTACHMENT_COUNT_IDX_IN_MAIL_TBL);
+                               _get_stmt_field_data_string(hStmt, &(p_data_tbl->preview_text), 1, PREVIEW_TEXT_IDX_IN_MAIL_TBL);
+
+                       }
+
+                       if (p_data_tbl->body_download_status)  {
+                               struct stat buf;
+
+                               if (p_data_tbl->file_path_html)  {
+                                       if (stat(p_data_tbl->file_path_html, &buf) == -1)
+                                               p_data_tbl->body_download_status = 0;
+                               }
+                               else if (p_data_tbl->file_path_plain)  {
+                                       if (stat(p_data_tbl->file_path_plain, &buf) == -1)
+                                               p_data_tbl->body_download_status = 0;
+                               }
+                               else
+                                       p_data_tbl->body_download_status = 0;
+                       }
+
+                       *((emstorage_mail_tbl_t**)data) = p_data_tbl;
+                       break;
+
+               case RETRIEVE_SUMMARY:
+                       if (!(p_data_tbl = malloc(sizeof(emstorage_mail_tbl_t))))  {
+                               EM_DEBUG_EXCEPTION(" malloc failed...");
+
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       memset(p_data_tbl, 0x00, sizeof(emstorage_mail_tbl_t));
+
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->mail_id), MAIL_ID_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->account_id), ACCOUNT_ID_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->mailbox_name), 0, MAILBOX_NAME_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_int   (hStmt, &(p_data_tbl->server_mail_status), SERVER_MAIL_STATUS_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->server_mailbox_name), 0, SERVER_MAILBOX_NAME_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->server_mail_id), 0, SERVER_MAIL_ID_IDX_IN_MAIL_TBL);
+
+                       *((emstorage_mail_tbl_t**)data) = p_data_tbl;
+                       break;
+
+               case RETRIEVE_ADDRESS:
+                       if (!(p_data_tbl = malloc(sizeof(emstorage_mail_tbl_t))))  {
+                               EM_DEBUG_EXCEPTION(" malloc failed...");
+                               error = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+
+                       memset(p_data_tbl, 0x00, sizeof(emstorage_mail_tbl_t));
+                       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mail_id), MAIL_ID_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->email_address_sender), 1, EMAIL_ADDRESS_SENDER_IDX_IN_MAIL_TBL);
+                       _get_stmt_field_data_string(hStmt, &(p_data_tbl->email_address_recipient), 1, EMAIL_ADDRESS_RECIPIENT_IDX_IN_MAIL_TBL);
+                       *((emstorage_mail_tbl_t**)data) = p_data_tbl;
+                       break;
+
+               default:
+                       break;
+       }
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_mail_search_end(int search_handle, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("search_handle[%d], transaction[%d], err_code[%p]", search_handle, transaction, err_code);
+
+       int error = EMAIL_ERROR_NONE;
+       int rc, ret = false;
+
+       if (search_handle == 0)  {
+               EM_DEBUG_EXCEPTION(" search_handle[%d]", search_handle);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       DB_STMT hStmt = (DB_STMT)search_handle;
+
+       EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
+
+       rc = sqlite3_finalize(hStmt);
+       if (rc != SQLITE_OK)  {
+               EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+               error = EMAIL_ERROR_DB_FAILURE;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_change_mail(int mail_id, emstorage_mail_tbl_t* mail, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], mail[%p], transaction[%d], err_code[%p]", mail_id, mail, transaction, err_code);
+
+       if (mail_id <= 0 || !mail) {
+               EM_DEBUG_EXCEPTION(" mail_id[%d], mail[%p]", mail_id, mail);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int i = 0;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       char mailbox_id_param_string[10] = {0,};
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_tbl SET"
+               "  mail_id = ?"
+               ", account_id = ?"
+               ", mailbox_id = ?"
+               ", mailbox_name = ?"
+               ", mail_size = ?"
+               ", server_mail_status = ?"
+               ", server_mailbox_name = ?"
+               ", server_mail_id = ?"
+               ", reference_mail_id = ?"
+               ", full_address_from = ?"
+               ", full_address_reply = ?"  /* 10 */
+               ", full_address_to = ?"
+               ", full_address_cc = ?"
+               ", full_address_bcc = ?"
+               ", full_address_return = ?"
+               ", subject = ?"
+               ", body_download_status = ?"
+               ", file_path_plain = ?"
+               ", file_path_html = ?"
+               ", date_time = ?"
+               ", flags_seen_field      = ?"
+               ", flags_deleted_field   = ?"
+               ", flags_flagged_field   = ?"
+               ", flags_answered_field  = ?"
+               ", flags_recent_field    = ?"
+               ", flags_draft_field     = ?"
+               ", flags_forwarded_field = ?"
+               ", DRM_status = ?"
+               ", priority = ?"
+               ", save_status = ?"
+               ", lock_status = ?"
+               ", message_id = ?"
+               ", report_status = ?"
+               ", preview_text = ?"
+               ", smime_type = ?"
+               " WHERE mail_id = %d AND account_id != 0 "
+               , mail_id);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       _bind_stmt_field_data_int   (hStmt, i++, mail->mail_id);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->account_id);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->mailbox_id);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->mailbox_name, 0, MAILBOX_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->mail_size);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->server_mail_status);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->server_mailbox_name, 0, SERVER_MAILBOX_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->server_mail_id, 0, SERVER_MAIL_ID_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->reference_mail_id);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->full_address_from, 1, FROM_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->full_address_reply, 1, REPLY_TO_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->full_address_to, 1, TO_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->full_address_cc, 1, CC_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->full_address_bcc, 1, BCC_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->full_address_return, 1, RETURN_PATH_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->subject, 1, SUBJECT_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->body_download_status);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->file_path_plain, 0, TEXT_1_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->file_path_html, 0, TEXT_2_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->date_time);
+       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_seen_field);
+       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_deleted_field);
+       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_flagged_field);
+       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_answered_field);
+       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_recent_field);
+       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_draft_field);
+       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_forwarded_field);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->DRM_status);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->priority);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->save_status);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->lock_status);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->message_id, 0, MESSAGE_ID_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->report_status);
+       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, i++, mail->smime_type);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no matched mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+       SNPRINTF(mailbox_id_param_string, 10, "%d", mail->mailbox_id);
+       if (!emcore_notify_storage_event(NOTI_MAIL_UPDATE, mail->account_id, mail->mail_id, mailbox_id_param_string, 0))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_UPDATE ] >>>> ");
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_modify_mailbox_of_mails(char *old_mailbox_name, char *new_mailbox_name, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("old_mailbox_name[%p], new_mailbox_name[%p], transaction[%d], err_code[%p]", old_mailbox_name, new_mailbox_name, transaction, err_code);
+
+       if (!old_mailbox_name && !new_mailbox_name)  {
+               EM_DEBUG_EXCEPTION(" old_mailbox_name[%p], new_mailbox_name[%p]", old_mailbox_name, new_mailbox_name);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       EM_DEBUG_LOG("Old Mailbox Name  [ %s ] , New Mailbox name [ %s ] ", old_mailbox_name, new_mailbox_name);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET mailbox_name = '%s' WHERE mailbox_name = '%s'", new_mailbox_name, old_mailbox_name);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0) {
+               EM_DEBUG_EXCEPTION(" no matched mail found...");
+
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG(" Modification done in mail_read_mail_uid_tbl based on Mailbox name ");
+       /* Modify the mailbox_name name in mail_read_mail_uid_tbl table */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_read_mail_uid_tbl SET mailbox_name = '%s' WHERE mailbox_name = '%s'", new_mailbox_name, old_mailbox_name);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no matched mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_notify_storage_event(NOTI_MAILBOX_UPDATE, 1, 0, new_mailbox_name, 0))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_MAILBOX_UPDATE] : Notification Failed >>> ");
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/**
+  *  emstorage_clean_save_status(int save_status, int  *err_code) - set the all mail status to the set value
+  *
+  *
+  **/
+INTERNAL_FUNC int emstorage_clean_save_status(int save_status, int  *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("save_status[%d], err_code[%p]", save_status, err_code);
+
+       EM_IF_NULL_RETURN_VALUE(err_code, false);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int rc = 0;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET save_status = %d WHERE save_status = %d", save_status, EMAIL_MAIL_STATUS_SENDING);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0) {
+               EM_DEBUG_LOG(" No Matched Mail Exists ");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_set_field_of_mails_with_integer_value(int account_id, int mail_ids[], int mail_ids_count, char *field_name, int value, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], mail_ids[%p], mail_ids_count[%d], field_name[%s], value[%d], transaction[%d], err_code[%p]", account_id, mail_ids, mail_ids_count, field_name, value, transaction, err_code);
+       int i = 0;
+       int error = EMAIL_ERROR_NONE;
+       int rc = 0;
+       int ret = false;
+       int cur_mail_id_string = 0;
+       int mail_id_string_buffer_length = 0;
+       char  sql_query_string[QUERY_SIZE] = {0, };
+       char *mail_id_string_buffer = NULL;
+       char *parameter_string = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       email_mail_attribute_type target_mail_attribute_type = 0;
+
+       if (!mail_ids  || !field_name || account_id == 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       if( (error = _get_attribute_type_by_mail_field_name(field_name, &target_mail_attribute_type)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attribute_type_by_mail_field_name failed [%d]", error);
+               if (err_code != NULL)
+                       *err_code = error;
+               return false;
+       }
+
+       /* Generating mail id list string */
+       mail_id_string_buffer_length = MAIL_ID_STRING_LENGTH * mail_ids_count;
+
+       mail_id_string_buffer = em_malloc(mail_id_string_buffer_length);
+
+       if(!mail_id_string_buffer) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < mail_ids_count; i++)
+               cur_mail_id_string += SNPRINTF_OFFSET(mail_id_string_buffer, cur_mail_id_string, mail_id_string_buffer_length, "%d,", mail_ids[i]);
+
+       if(EM_SAFE_STRLEN(mail_id_string_buffer) > 1)
+               mail_id_string_buffer[EM_SAFE_STRLEN(mail_id_string_buffer) - 1] = NULL_CHAR;
+
+       /* Generating notification parameter string */
+       parameter_string = em_malloc(mail_id_string_buffer_length + EM_SAFE_STRLEN(field_name) + 2);
+
+       if(!parameter_string) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(parameter_string, QUERY_SIZE, "%s%c%s", field_name, 0x01, mail_id_string_buffer);
+
+       /* Write query string */
+       SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_tbl SET %s = %d WHERE mail_id in (%s) AND account_id = %d", field_name, value, mail_id_string_buffer, account_id);
+
+       EM_DEBUG_LOG("sql_query_string [%s]", sql_query_string);
+
+       /* Execute query */
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       if (sqlite3_changes(local_db_handle) == 0)
+               EM_DEBUG_LOG("no mail matched...");
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (ret && parameter_string && !emcore_notify_storage_event(NOTI_MAIL_FIELD_UPDATE, account_id, target_mail_attribute_type, parameter_string, value))
+               EM_DEBUG_EXCEPTION("emcore_notify_storage_event failed : NOTI_MAIL_FIELD_UPDATE [%s,%d]", field_name, value);
+
+       EM_SAFE_FREE(mail_id_string_buffer);
+       EM_SAFE_FREE(parameter_string);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_type_t type, emstorage_mail_tbl_t* mail, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], type[%d], mail[%p], transaction[%d], err_code[%p]", mail_id, type, mail, transaction, err_code);
+
+       if (mail_id <= 0 || !mail)  {
+               EM_DEBUG_EXCEPTION(" mail_id[%d], type[%d], mail[%p]", mail_id, type, mail);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int move_flag = 0;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int rc = 0;
+       int i = 0;
+
+       char *mailbox_name = NULL;
+       char mailbox_id_param_string[10] = {0,};
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       switch (type) {
+               case APPEND_BODY:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               "  body_download_status = ?"
+                               ", file_path_plain = ?"
+                               ", file_path_html = ?"
+                               ", flags_seen_field      = ?"
+                               ", flags_deleted_field   = ?"
+                               ", flags_flagged_field   = ?"
+                               ", flags_answered_field  = ?"
+                               ", flags_recent_field    = ?"
+                               ", flags_draft_field     = ?"
+                               ", flags_forwarded_field = ?"
+                               ", DRM_status = ?"
+                               ", attachment_count = ?"
+                               ", preview_text= ?"
+                               ", meeting_request_status = ? "
+                               ", message_class = ? "
+                               ", digest_type = ? "
+                               ", smime_type = ? "
+                               " WHERE mail_id = %d AND account_id != 0"
+                               , mail_id);
+
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                        i = 0;
+
+                       _bind_stmt_field_data_int(hStmt, i++, mail->body_download_status);
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->file_path_plain, 0, TEXT_1_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->file_path_html, 0, TEXT_2_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->flags_seen_field);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->flags_deleted_field);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->flags_flagged_field);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->flags_answered_field);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->flags_recent_field);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->flags_draft_field);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->flags_forwarded_field);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->DRM_status);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->attachment_count);
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->preview_text, 0, PREVIEWBODY_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->meeting_request_status);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->message_class);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->digest_type);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->smime_type);
+                       break;
+
+               case UPDATE_MAILBOX: {
+                               int err;
+                               emstorage_mailbox_tbl_t *mailbox_tbl;
+
+                               if (!emstorage_get_mailbox_by_name(mail->account_id, -1, mail->mailbox_name, &mailbox_tbl, false, &err)) {
+                                       EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_by_name failed - %d", err);
+
+                                       goto FINISH_OFF;
+                               }
+
+                               SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                                       "UPDATE mail_tbl SET"
+                                       " mailbox_id = '%d'"
+                                       " mailbox_name = '%s'"
+                                       ",mailbox_type = '%d'"
+                                       " WHERE mail_id = %d AND account_id != 0"
+                                       , mailbox_tbl->mailbox_id
+                                       , mail->mailbox_name ? mail->mailbox_name : ""
+                                       , mailbox_tbl->mailbox_type
+                                       , mail_id);
+                                       move_flag = 1;
+
+                               emstorage_free_mailbox(&mailbox_tbl, 1, NULL); /*prevent 26251*/
+                               EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+                               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                               EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+                       }
+                       break;
+
+               case UPDATE_FLAG:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               " flags_seen_field      = %d"
+                               ",flags_deleted_field   = %d"
+                               ",flags_flagged_field   = %d"
+                               ",flags_answered_field  = %d"
+                               ",flags_recent_field    = %d"
+                               ",flags_draft_field     = %d"
+                               ",flags_forwarded_field = %d"
+                               "  WHERE mail_id = %d AND account_id != 0"
+                               , mail->flags_seen_field
+                               , mail->flags_deleted_field
+                               , mail->flags_flagged_field
+                               , mail->flags_answered_field
+                               , mail->flags_recent_field
+                               , mail->flags_draft_field
+                               , mail->flags_forwarded_field
+                               , mail_id);
+                       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+                       break;
+
+               case UPDATE_EXTRA_FLAG:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               "  priority = %d"
+                               ", save_status = %d"
+                               ", lock_status = %d"
+                               ", report_status = %d"
+                               ", DRM_status = %d"
+                               " WHERE mail_id = %d AND account_id != 0"
+                               , mail->priority
+                               , mail->save_status
+                               , mail->lock_status
+                               , mail->report_status
+                               , mail->DRM_status
+                               , mail_id);
+                       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       break;
+
+               case UPDATE_STICKY_EXTRA_FLAG:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               "  lock_status = %d"
+                               "  WHERE mail_id = %d AND account_id != 0"
+                               , mail->lock_status
+                               , mail_id);
+                       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       break;
+
+               case UPDATE_MAIL:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               "  full_address_from = ?"
+                               ", full_address_reply = ?"
+                               ", full_address_to = ?"
+                               ", full_address_cc = ?"
+                               ", full_address_bcc = ?"
+                               ", full_address_return = ?"
+                               ", subject = ?"
+                               ", file_path_plain = ?"
+                               ", date_time = ?"
+                               ", flags_seen_field = ?"
+                               ", flags_deleted_field = ?"
+                               ", flags_flagged_field = ?"
+                               ", flags_answered_field = ?"
+                               ", flags_recent_field = ?"
+                               ", flags_draft_field = ?"
+                               ", flags_forwarded_field = ?"
+                               ", priority = ?"
+                               ", save_status = ?"
+                               ", lock_status = ?"
+                               ", report_status = ?"
+                               ", DRM_status = ?"
+                               ", file_path_html = ?"
+                               ", file_path_mime_entity = ?"
+                               ", mail_size = ?"
+                               ", preview_text = ?"
+                               ", body_download_status = ?"
+                               ", attachment_count = ?"
+                               ", inline_content_count = ?"
+                               ", meeting_request_status = ?"
+                               ", message_class = ?"
+                               ", digest_type = ?"
+                               ", smime_type = ?"
+                               " WHERE mail_id = %d AND account_id != 0"
+                               , mail_id);
+
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_LOG(" before sqlite3_prepare hStmt = %p", hStmt);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       i = 0;
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->full_address_from, 1, FROM_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->full_address_reply, 1, REPLY_TO_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->full_address_to, 1, TO_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->full_address_cc, 1, CC_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->full_address_bcc, 1, BCC_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->full_address_return, 1, RETURN_PATH_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->subject, 1, SUBJECT_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->file_path_plain, 0, TEXT_1_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_time_t(hStmt, i++, mail->date_time);
+                       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_seen_field);
+                       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_deleted_field);
+                       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_flagged_field);
+                       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_answered_field);
+                       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_recent_field);
+                       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_draft_field);
+                       _bind_stmt_field_data_char  (hStmt, i++, mail->flags_forwarded_field);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->priority);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->save_status);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->lock_status);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->report_status);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->DRM_status);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->file_path_html, 0, TEXT_2_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->file_path_mime_entity, 0, MIME_ENTITY_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->mail_size);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->body_download_status);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->attachment_count);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->inline_content_count);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->meeting_request_status);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->message_class);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->digest_type);
+                       _bind_stmt_field_data_int   (hStmt, i++, mail->smime_type);
+                       break;
+
+               case UPDATE_DATETIME:  {
+                       time_t now = time(NULL);
+
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               " date_time = '%d'"
+                               " WHERE mail_id = %d AND account_id != 0"
+                               , (int)now
+                               , mail_id);
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       break;
+               }
+
+               case UPDATE_FROM_CONTACT_INFO:
+                       EM_DEBUG_LOG("NVARCHAR : emstorage_change_mail_field - mail change type is UPDATE_FROM_CONTACT_INFO");
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               " email_address_sender = ?,"
+                               " WHERE mail_id = %d",
+                               mail_id);
+
+                       hStmt = NULL;
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       i = 0;
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->email_address_sender, 1, FROM_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+                       break;
+
+               case UPDATE_TO_CONTACT_INFO:
+                       EM_DEBUG_LOG("NVARCHAR : emstorage_change_mail_field - mail change type is UPDATE_TO_CONTACT_INFO");
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               " email_address_recipient = ?,"
+                               " WHERE mail_id = %d",
+                               mail_id);
+
+                       hStmt = NULL;
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       i = 0;
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->email_address_recipient, 1, TO_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+                       break;
+
+                       case UPDATE_ALL_CONTACT_INFO:
+                               EM_DEBUG_LOG("emstorage_change_mail_field - mail change type is UPDATE_ALL_CONTACT_INFO");
+                               SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                                       "UPDATE mail_tbl SET"
+                                       " email_address_sender = ?,"
+                                       " email_address_recipient = ?,"
+                                       " WHERE mail_id = %d",
+                                       mail_id);
+
+                               hStmt = NULL;
+
+                               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                               EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                               i = 0;
+                               _bind_stmt_field_data_string(hStmt, i++, (char *)mail->email_address_sender, 1, FROM_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+                               _bind_stmt_field_data_string(hStmt, i++, (char *)mail->email_address_recipient, 1, TO_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+                               break;
+
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+                       case UPDATE_PARTIAL_BODY_DOWNLOAD:
+
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                       "UPDATE mail_tbl SET"
+                       "  body_download_status = ?"
+                       ", file_path_plain = ?"
+                       ", file_path_html = ?"
+                       ", attachment_count = ?"
+                       ", inline_content_count = ?"
+                       ", preview_text= ?"
+                       " WHERE mail_id = %d"
+                       , mail_id);
+
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                        i = 0;
+
+                       _bind_stmt_field_data_int(hStmt, i++, mail->body_download_status);
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->file_path_plain, 0, TEXT_1_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->file_path_html,  0, TEXT_2_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->attachment_count);
+                       _bind_stmt_field_data_int(hStmt, i++, mail->inline_content_count);
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)mail->preview_text,    0, PREVIEWBODY_LEN_IN_MAIL_TBL);
+
+                       break;
+
+#endif
+               case UPDATE_FILE_PATH:
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_tbl SET"
+                               ", file_path_plain = ?"
+                               ", file_path_html = ?"
+                               ", file_path_mime_entity = ?"
+                               " WHERE mail_id = %d"
+                               , mail_id);
+
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_LOG(" before sqlite3_prepare hStmt = %p", hStmt);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+                       i = 0;
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->file_path_plain, 0, TEXT_1_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->file_path_html, 0, TEXT_2_LEN_IN_MAIL_TBL);
+                       _bind_stmt_field_data_string(hStmt, i++, (char*)mail->file_path_mime_entity, 0, MIME_ENTITY_LEN_IN_MAIL_TBL);
+                       break;
+
+               default:
+                       EM_DEBUG_LOG(" type[%d]", type);
+
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+       }
+
+       if (hStmt != NULL)  {
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+               rc = sqlite3_changes(local_db_handle);
+               if (rc == 0)  {
+                       EM_DEBUG_EXCEPTION(" no matched mail found...");
+
+                       error = EMAIL_ERROR_MAIL_NOT_FOUND;
+                       goto FINISH_OFF;
+               }
+       }
+
+       if (mail->account_id == 0) {
+               emstorage_mail_tbl_t* mail_for_account_tbl = NULL;
+               if (!emstorage_get_mail_field_by_id(mail_id, RETRIEVE_ACCOUNT, &mail_for_account_tbl, true, &error) || !mail_for_account_tbl) {
+                       EM_DEBUG_EXCEPTION(" emstorage_get_mail_field_by_id failed - %d", error);
+/*              */
+                       goto FINISH_OFF;
+               }
+               mail->account_id = mail_for_account_tbl->account_id;
+               if (mail_for_account_tbl)
+                       emstorage_free_mail(&mail_for_account_tbl, 1, NULL);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+               hStmt = NULL;
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       /*h.gahlaut@samsung.com: Moving publication of notification after commiting transaction to DB */
+
+       if (ret == true &&  move_flag != 1) {
+               if (!emstorage_get_mailbox_name_by_mailbox_type(mail->account_id, EMAIL_MAILBOX_TYPE_SENTBOX, &mailbox_name, false, &error))
+                       EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_name_by_mailbox_type failed - %d", error);
+
+               if (mail->mailbox_name && mailbox_name) {
+                       if (strcmp(mail->mailbox_name, mailbox_name) != 0) {
+                               SNPRINTF(mailbox_id_param_string, 10, "%d", mail->mailbox_id);
+                               if (!emcore_notify_storage_event(NOTI_MAIL_UPDATE, mail->account_id, mail_id, mailbox_id_param_string, type))
+                                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_UPDATE ] >>>> ");
+                       }
+               }
+               else {
+                       /* h.gahlaut@samsung.com: Jan 10, 2011 Publishing noti to refresh outbox when email sending status changes */
+                       if (!emcore_notify_storage_event(NOTI_MAIL_UPDATE, mail->account_id, mail_id, NULL, type))
+                               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_UPDATE ] ");
+               }
+       }
+
+       EM_SAFE_FREE(mailbox_name);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+INTERNAL_FUNC int emstorage_increase_mail_id(int *mail_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%p], transaction[%d], err_code[%p]", mail_id, transaction, err_code);
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int latest_mail_id = 0;
+       sqlite3 *local_db_handle = NULL;
+       char *sql = "SELECT MAX(mail_id) FROM mail_tbl;";
+       char **result = NULL;
+
+#ifdef __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__
+       _timedlock_shm_mutex(&mapped_for_generating_mail_id, 2);
+#endif /* __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__ */
+
+       ret = vconf_get_int(VCONF_KEY_LATEST_MAIL_ID, &latest_mail_id);
+       if (ret < 0 || latest_mail_id == 0) {
+               EM_DEBUG_LOG("vconf_get_int() failed [%d] or latest_mail_id is zero", ret);
+
+               local_db_handle = emstorage_get_db_connection();
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+               if (NULL == result[1])
+                       rc = 1;
+               else
+                       rc = atoi(result[1]) + 1;
+
+               sqlite3_free_table(result);
+               latest_mail_id = rc;
+       }
+
+       latest_mail_id++;
+
+       ret = vconf_set_int(VCONF_KEY_LATEST_MAIL_ID, latest_mail_id);
+
+       if (mail_id)
+               *mail_id = latest_mail_id;
+
+#ifdef __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__
+       _unlockshm_mutex(&mapped_for_generating_mail_id);
+#endif /* __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__ */
+
+       ret = true;
+
+FINISH_OFF:
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_add_mail(emstorage_mail_tbl_t *mail_tbl_data, int get_id, int transaction, int *err_code)
+{
+       EM_PROFILE_BEGIN(profile_emstorage_add_mail);
+       EM_DEBUG_FUNC_BEGIN("mail_tbl_data[%p], get_id[%d], transaction[%d], err_code[%p]", mail_tbl_data, get_id, transaction, err_code);
+
+       if (!mail_tbl_data)  {
+               EM_DEBUG_EXCEPTION("mail_tbl_data[%p], get_id[%d]", mail_tbl_data, get_id);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       DB_STMT hStmt = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       if (get_id)  {
+               /*  increase unique id */
+               char *sql = "SELECT max(rowid) FROM mail_tbl;";
+               char **result;
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+                       ("SQL[%s] sqlite3_get_table fail[%d] [%s]", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+               if (NULL == result[1])
+                       rc = 1;
+               else
+                       rc = atoi(result[1])+1;
+
+               sqlite3_free_table(result);
+
+               mail_tbl_data->mail_id   = rc;
+               mail_tbl_data->thread_id = rc;
+       }
+
+       if (mail_tbl_data->date_time == 0)
+               mail_tbl_data->date_time = time(NULL);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_tbl VALUES "
+               "( ?" /*  mail_id */
+               ", ?" /*  account_id */
+               ", ?" /*  mailbox_id */
+               ", ?" /*  mailbox_name */
+               ", ?" /*  mailbox_type */
+               ", ?" /*  subject */
+               ", ?" /*  date_time */
+               ", ?" /*  server_mail_status */
+               ", ?" /*  server_mailbox_name */
+               ", ?" /*  server_mail_id */
+               ", ?" /*  message_id */
+               ", ?" /*  reference_mail_id */
+               ", ?" /*  full_address_from */
+               ", ?" /*  full_address_reply */
+               ", ?" /*  full_address_to */
+               ", ?" /*  full_address_cc */
+               ", ?" /*  full_address_bcc */
+               ", ?" /*  full_address_return */
+               ", ?" /*  email_address_sender */
+               ", ?" /*  email_address_recipient */
+               ", ?" /*  alias_sender */
+               ", ?" /*  alias_recipient */
+               ", ?" /*  body_download_status */
+               ", ?" /*  file_path_plain */
+               ", ?" /*  file_path_html */
+               ", ?" /*  file_path_mime_entity */
+               ", ?" /*  mail_size */
+               ", ?" /*  flags_seen_field */
+               ", ?" /*  flags_deleted_field */
+               ", ?" /*  flags_flagged_field */
+               ", ?" /*  flags_answered_field */
+               ", ?" /*  flags_recent_field */
+               ", ?" /*  flags_draft_field */
+               ", ?" /*  flags_forwarded_field */
+               ", ?" /*  DRM_status */
+               ", ?" /*  priority */
+               ", ?" /*  save_status */
+               ", ?" /*  lock_status */
+               ", ?" /*  report_status */
+               ", ?" /*  attachment_count */
+               ", ?" /*  inline_content_count */
+               ", ?" /*  thread_id */
+               ", ?" /*  thread_item_count */
+               ", ?" /*  preview_text */
+               ", ?" /*  meeting_request_status */
+               ", ?" /*  message_class */
+               ", ?" /*  digest_type */
+               ", ?" /*  smime_type */
+               ")");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       _bind_stmt_field_data_int   (hStmt, MAIL_ID_IDX_IN_MAIL_TBL, mail_tbl_data->mail_id);
+       _bind_stmt_field_data_int   (hStmt, ACCOUNT_ID_IDX_IN_MAIL_TBL, mail_tbl_data->account_id);
+       _bind_stmt_field_data_int   (hStmt, MAILBOX_ID_IDX_IN_MAIL_TBL, mail_tbl_data->mailbox_id);
+       _bind_stmt_field_data_string(hStmt, MAILBOX_NAME_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->mailbox_name, 0, MAILBOX_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, MAILBOX_TYPE_IDX_IN_MAIL_TBL, mail_tbl_data->mailbox_type);
+       _bind_stmt_field_data_string(hStmt, SUBJECT_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->subject, 1, SUBJECT_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, DATETIME_IDX_IN_MAIL_TBL, mail_tbl_data->date_time);
+       _bind_stmt_field_data_int   (hStmt, SERVER_MAIL_STATUS_IDX_IN_MAIL_TBL, mail_tbl_data->server_mail_status);
+       _bind_stmt_field_data_string(hStmt, SERVER_MAILBOX_NAME_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->server_mailbox_name, 0, SERVER_MAILBOX_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, SERVER_MAIL_ID_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->server_mail_id, 0, SERVER_MAIL_ID_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, MESSAGE_ID_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->message_id, 0, MESSAGE_ID_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, REFERENCE_ID_IDX_IN_MAIL_TBL, mail_tbl_data->reference_mail_id);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_FROM_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->full_address_from, 1, FROM_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_REPLY_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->full_address_reply, 1, REPLY_TO_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_TO_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->full_address_to, 1, TO_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_CC_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->full_address_cc, 1, CC_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_BCC_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->full_address_bcc, 1, BCC_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_RETURN_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->full_address_return, 1, RETURN_PATH_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, EMAIL_ADDRESS_SENDER_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->email_address_sender, 1, FROM_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, EMAIL_ADDRESS_RECIPIENT_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->email_address_recipient, 1, TO_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, ALIAS_SENDER_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->alias_sender, 1, FROM_CONTACT_NAME_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, ALIAS_RECIPIENT_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->alias_recipient, 1, FROM_CONTACT_NAME_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, BODY_DOWNLOAD_STATUS_IDX_IN_MAIL_TBL, mail_tbl_data->body_download_status);
+       _bind_stmt_field_data_string(hStmt, FILE_PATH_PLAIN_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->file_path_plain, 0, TEXT_1_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FILE_PATH_HTML_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->file_path_html, 0, TEXT_2_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FILE_PATH_MIME_ENTITY_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->file_path_mime_entity, 0, MIME_ENTITY_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, MAIL_SIZE_IDX_IN_MAIL_TBL, mail_tbl_data->mail_size);
+       _bind_stmt_field_data_int   (hStmt, FLAGS_SEEN_FIELD_IDX_IN_MAIL_TBL, mail_tbl_data->flags_seen_field);
+       _bind_stmt_field_data_int   (hStmt, FLAGS_DELETED_FIELD_IDX_IN_MAIL_TBL, mail_tbl_data->flags_deleted_field);
+       _bind_stmt_field_data_int   (hStmt, FLAGS_FLAGGED_FIELD_IDX_IN_MAIL_TBL, mail_tbl_data->flags_flagged_field);
+       _bind_stmt_field_data_int   (hStmt, FLAGS_ANSWERED_FIELD_IDX_IN_MAIL_TBL, mail_tbl_data->flags_answered_field);
+       _bind_stmt_field_data_int   (hStmt, FLAGS_RECENT_FIELD_IDX_IN_MAIL_TBL, mail_tbl_data->flags_recent_field);
+       _bind_stmt_field_data_int   (hStmt, FLAGS_DRAFT_FIELD_IDX_IN_MAIL_TBL, mail_tbl_data->flags_draft_field);
+       _bind_stmt_field_data_int   (hStmt, FLAGS_FORWARDED_FIELD_IDX_IN_MAIL_TBL, mail_tbl_data->flags_forwarded_field);
+       _bind_stmt_field_data_int   (hStmt, DRM_STATUS_IDX_IN_MAIL_TBL, mail_tbl_data->DRM_status);
+       _bind_stmt_field_data_int   (hStmt, PRIORITY_IDX_IN_MAIL_TBL, mail_tbl_data->priority);
+       _bind_stmt_field_data_int   (hStmt, SAVE_STATUS_IDX_IN_MAIL_TBL, mail_tbl_data->save_status);
+       _bind_stmt_field_data_int   (hStmt, LOCK_STATUS_IDX_IN_MAIL_TBL, mail_tbl_data->lock_status);
+       _bind_stmt_field_data_int   (hStmt, REPORT_STATUS_IDX_IN_MAIL_TBL, mail_tbl_data->report_status);
+       _bind_stmt_field_data_int   (hStmt, ATTACHMENT_COUNT_IDX_IN_MAIL_TBL, mail_tbl_data->attachment_count);
+       _bind_stmt_field_data_int   (hStmt, INLINE_CONTENT_COUNT_IDX_IN_MAIL_TBL, mail_tbl_data->inline_content_count);
+       _bind_stmt_field_data_int   (hStmt, THREAD_ID_IDX_IN_MAIL_TBL, mail_tbl_data->thread_id);
+       _bind_stmt_field_data_int   (hStmt, THREAD_ITEM_COUNT_IDX_IN_MAIL_TBL, mail_tbl_data->thread_item_count);
+       _bind_stmt_field_data_string(hStmt, PREVIEW_TEXT_IDX_IN_MAIL_TBL, (char*)mail_tbl_data->preview_text, 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int   (hStmt, MEETING_REQUEST_STATUS_IDX_IN_MAIL_TBL, mail_tbl_data->meeting_request_status);
+       _bind_stmt_field_data_int   (hStmt, MESSAGE_CLASS_IDX_IN_MAIL_TBL, mail_tbl_data->message_class);
+       _bind_stmt_field_data_int   (hStmt, DIGEST_TYPE_IDX_IN_MAIL_TBL, mail_tbl_data->digest_type);
+       _bind_stmt_field_data_int   (hStmt, SMIME_TYPE_IDX_IN_MAIL_TBL, mail_tbl_data->smime_type);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; }, ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("sqlite3_step fail:%d", rc));
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG("sqlite3_finalize failed [%d]", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(profile_emstorage_add_mail);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_move_multiple_mails_on_db(int input_source_account_id, int input_mailbox_id, int mail_ids[], int number_of_mails, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_source_account_id [%d], input_mailbox_id [%d], mail_ids[%p], number_of_mails [%d], transaction[%d], err_code[%p]", input_source_account_id, input_mailbox_id, mail_ids, number_of_mails, transaction, err_code);
+
+       int rc, ret = false, i, cur_conditional_clause = 0;
+       int error = EMAIL_ERROR_NONE;
+       int target_account_id;
+       char sql_query_string[QUERY_SIZE] = {0, }, conditional_clause[QUERY_SIZE] = {0, };
+       emstorage_mailbox_tbl_t *result_mailbox = NULL;
+       email_mailbox_type_e target_mailbox_type = EMAIL_MAILBOX_TYPE_USER_DEFINED;
+       char* target_mailbox_name = NULL;
+
+       if (!mail_ids || input_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       if ((error = emstorage_get_mailbox_by_id(input_mailbox_id, &result_mailbox)) != EMAIL_ERROR_NONE || !result_mailbox) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       target_mailbox_name = EM_SAFE_STRDUP(result_mailbox->mailbox_name);
+       target_mailbox_type = result_mailbox->mailbox_type;
+       target_account_id   = result_mailbox->account_id;
+       emstorage_free_mailbox(&result_mailbox, 1, NULL);
+
+       cur_conditional_clause = SNPRINTF(conditional_clause, QUERY_SIZE, "WHERE mail_id in (");
+
+       for(i = 0; i < number_of_mails; i++)
+               cur_conditional_clause += SNPRINTF_OFFSET(conditional_clause, cur_conditional_clause, QUERY_SIZE, "%d,", mail_ids[i]);
+
+       conditional_clause[EM_SAFE_STRLEN(conditional_clause) - 1] = ')';
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       /* Updating a mail_tbl */
+
+       memset(sql_query_string, 0x00, QUERY_SIZE);
+       SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_tbl SET mailbox_name = '%s', mailbox_type = %d, mailbox_id = %d, account_id = %d %s", target_mailbox_name, target_mailbox_type, input_mailbox_id, target_account_id, conditional_clause);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       /* Updating a mail_attachment_tbl */
+
+       memset(sql_query_string, 0x00, QUERY_SIZE);
+       SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_attachment_tbl SET mailbox_id = '%d', account_id = %d %s", input_mailbox_id, target_account_id, conditional_clause);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       /* Updating a mail_meeting_tbl */
+       memset(sql_query_string, 0x00, QUERY_SIZE);
+       SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_meeting_tbl SET mailbox_id = %d, account_id = %d %s", input_mailbox_id, target_account_id, conditional_clause);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       /* Updating a mail_read_mail_uid_tbl */
+       memset(conditional_clause, 0x00, QUERY_SIZE);
+       cur_conditional_clause = SNPRINTF(conditional_clause, QUERY_SIZE, "WHERE local_uid in (");
+
+       for(i = 0; i < number_of_mails; i++)
+               cur_conditional_clause += SNPRINTF_OFFSET(conditional_clause, cur_conditional_clause, QUERY_SIZE, "%d,", mail_ids[i]);
+
+       /* prevent 34415 */
+       char *last_comma = rindex(conditional_clause, ',');
+       *last_comma = ')'; /* replace , with ) */
+
+       memset(sql_query_string, 0x00, QUERY_SIZE);
+       SNPRINTF(sql_query_string, QUERY_SIZE, "UPDATE mail_read_mail_uid_tbl SET mailbox_name = '%s', mailbox_id = %d, account_id = %d %s", target_mailbox_name, input_mailbox_id, target_account_id, conditional_clause);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       EM_SAFE_FREE(target_mailbox_name);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_mail(int mail_id, int from_server, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], transaction[%d], err_code[%p]", mail_id, transaction, err_code);
+
+       if (!mail_id)  {
+               EM_DEBUG_EXCEPTION("mail_id[%d]", mail_id);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_tbl WHERE mail_id = %d ", mail_id);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_multiple_mails(int mail_ids[], int number_of_mails, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], number_of_mails [%d], transaction[%d], err_code[%p]", mail_ids, number_of_mails, transaction, err_code);
+
+       int rc, ret = false, i, cur_sql_query_string = 0;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       if (!mail_ids) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       cur_sql_query_string = SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_tbl WHERE mail_id in (");
+
+       for(i = 0; i < number_of_mails; i++)
+               cur_sql_query_string += SNPRINTF_OFFSET(sql_query_string, cur_sql_query_string, QUERY_SIZE, "%d,", mail_ids[i]);
+
+       /* prevent 34414 */
+       char *last_comma = rindex(sql_query_string, ',');
+       *last_comma = ')'; /* replace , with ) */
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_mail_by_account(int account_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], transaction[%d], err_code[%p]", account_id, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID)  {
+               EM_DEBUG_EXCEPTION("account_id[%d]", account_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_tbl WHERE account_id = %d", account_id);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+       }
+
+       /* Delete all mails  mail_read_mail_uid_tbl table based on account id */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_read_mail_uid_tbl WHERE account_id = %d", account_id);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION("no mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+       }
+
+       if (!emcore_notify_storage_event(NOTI_MAIL_DELETE_WITH_ACCOUNT, account_id, 0 , NULL, 0))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_DELETE_ALL ]");
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_mail_by_mailbox(int account_id, char *mailbox, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox[%p], transaction[%d], err_code[%p]", account_id, mailbox, transaction, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || !mailbox)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mailbox[%p]", account_id, mailbox);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_tbl WHERE account_id = %d AND mailbox_name = '%s'", account_id, mailbox);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       /* Delete Mails from mail_read_mail_uid_tbl */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_read_mail_uid_tbl WHERE account_id = %d AND mailbox_name = '%s'", account_id, mailbox);
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (!emcore_notify_storage_event(NOTI_MAIL_DELETE_ALL, account_id, 0 , mailbox, 0))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAIL_DELETE_ALL ] >>>> ");
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_mail(emstorage_mail_tbl_t** mail_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_list[%p], count[%d], err_code[%p]", mail_list, count, err_code);
+
+       if (count > 0)  {
+               if ((mail_list == NULL) || (*mail_list == NULL))  {
+                       EM_DEBUG_EXCEPTION("mail_ilst[%p], count[%d]", mail_list, count);
+
+                       if (err_code)
+                               *err_code = EMAIL_ERROR_INVALID_PARAM;
+                       return false;
+               }
+
+               emstorage_mail_tbl_t* p = *mail_list;
+               int i = 0;
+
+               for (; i < count; i++, p++) {
+                       EM_SAFE_FREE(p->mailbox_name);
+                       EM_SAFE_FREE(p->server_mailbox_name);
+                       EM_SAFE_FREE(p->server_mail_id);
+                       EM_SAFE_FREE(p->full_address_from);
+                       EM_SAFE_FREE(p->full_address_reply);
+                       EM_SAFE_FREE(p->full_address_to);
+                       EM_SAFE_FREE(p->full_address_cc);
+                       EM_SAFE_FREE(p->full_address_bcc);
+                       EM_SAFE_FREE(p->full_address_return);
+                       EM_SAFE_FREE(p->subject);
+                       EM_SAFE_FREE(p->file_path_plain);
+                       EM_SAFE_FREE(p->file_path_html);
+                       EM_SAFE_FREE(p->file_path_mime_entity);
+                       EM_SAFE_FREE(p->message_id);
+                       EM_SAFE_FREE(p->email_address_sender);
+                       EM_SAFE_FREE(p->email_address_recipient);
+                       EM_SAFE_FREE(p->preview_text);
+                       EM_SAFE_FREE(p->alias_sender);
+                       EM_SAFE_FREE(p->alias_recipient);
+               }
+               EM_SAFE_FREE(*mail_list);
+       }
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+INTERNAL_FUNC int emstorage_get_attachment_count(int mail_id, int *count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], count[%p], transaction[%d], err_code[%p]", mail_id, count, transaction, err_code);
+
+       if (mail_id <= 0 || !count)  {
+               EM_DEBUG_EXCEPTION("mail_id[%d], count[%p]", mail_id, count);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_attachment_tbl WHERE mail_id = %d", mail_id);
+
+       char **result;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       *count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_attachment_list(int input_mail_id, int input_transaction, emstorage_attachment_tbl_t** output_attachment_list, int *output_attachment_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_id[%d], input_transaction[%d], output_attachment_list[%p], output_attachment_count[%p]", input_mail_id, input_transaction, output_attachment_list, output_attachment_count);
+
+       if (input_mail_id <= 0 || !output_attachment_list || !output_attachment_count)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int                         error = EMAIL_ERROR_NONE;
+       int                         i = 0;
+       int                         rc = -1;
+       char                      **result = NULL;
+       char                        sql_query_string[QUERY_SIZE] = {0, };
+       emstorage_attachment_tbl_t* p_data_tbl = NULL;
+       DB_STMT hStmt = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(input_transaction);
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT COUNT(*) FROM mail_attachment_tbl WHERE mail_id = %d", input_mail_id);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       *output_attachment_count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       if(*output_attachment_count == 0) {
+               error = EMAIL_ERROR_NONE;
+               goto FINISH_OFF;
+       }
+
+       p_data_tbl = (emstorage_attachment_tbl_t*)em_malloc(sizeof(emstorage_attachment_tbl_t) * (*output_attachment_count));
+
+       if (!p_data_tbl)  {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_attachment_tbl WHERE mail_id = %d ORDER BY attachment_id", input_mail_id);
+       EM_DEBUG_LOG("sql_query_string [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },   ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no matched attachment found...");
+               error = EMAIL_ERROR_ATTACHMENT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+       for (i = 0; i < *output_attachment_count; i++)  {
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].attachment_id), ATTACHMENT_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].attachment_name), 0, ATTACHMENT_NAME_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].attachment_path), 0, ATTACHMENT_PATH_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].attachment_size), ATTACHMENT_SIZE_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].mail_id), MAIL_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].account_id), ACCOUNT_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].mailbox_id), MAILBOX_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].attachment_save_status), ATTACHMENT_SAVE_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].attachment_drm_type), ATTACHMENT_DRM_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].attachment_drm_method), ATTACHMENT_DRM_METHOD_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_int   (hStmt, &(p_data_tbl[i].attachment_inline_content_status), ATTACHMENT_INLINE_CONTENT_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].attachment_mime_type), 0, ATTACHMENT_MIME_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL);
+
+               EM_DEBUG_LOG("attachment[%d].attachment_id : %d", i, p_data_tbl[i].attachment_id);
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; }, ("sqlite3_step fail:%d", rc));
+       }
+
+FINISH_OFF:
+
+       if (error == EMAIL_ERROR_NONE)
+               *output_attachment_list = p_data_tbl;
+       else if (p_data_tbl != NULL)
+               emstorage_free_attachment(&p_data_tbl, *output_attachment_count, NULL);
+
+       if (hStmt) {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed [%d]", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(input_transaction);
+
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+INTERNAL_FUNC int emstorage_get_attachment(int attachment_id, emstorage_attachment_tbl_t** attachment, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_id[%d], attachment[%p], transaction[%d], err_code[%p]", attachment_id, attachment, transaction, err_code);
+
+       if (attachment_id <= 0 || !attachment)  {
+               EM_DEBUG_EXCEPTION("attachment_id[%d], attachment[%p]", attachment_id, attachment);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       emstorage_attachment_tbl_t* p_data_tbl = NULL;
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_attachment_tbl WHERE attachment_id = %d",  attachment_id);
+
+       sqlite3_stmt* hStmt = NULL;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG(" before sqlite3_prepare hStmt = %p", hStmt);
+
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no matched attachment found...");
+               error = EMAIL_ERROR_ATTACHMENT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (!(p_data_tbl = (emstorage_attachment_tbl_t*)em_malloc(sizeof(emstorage_attachment_tbl_t) * 1)))  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->attachment_id), ATTACHMENT_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->attachment_name), 0, ATTACHMENT_NAME_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->attachment_path), 0, ATTACHMENT_PATH_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->attachment_size), ATTACHMENT_SIZE_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mail_id), MAIL_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->account_id), ACCOUNT_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->mailbox_id), MAILBOX_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->attachment_save_status), ATTACHMENT_SAVE_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->attachment_drm_type), ATTACHMENT_DRM_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->attachment_drm_method), ATTACHMENT_DRM_METHOD_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->attachment_inline_content_status), ATTACHMENT_INLINE_CONTENT_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->attachment_mime_type), 0, ATTACHMENT_MIME_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL);
+
+#ifdef __ATTACHMENT_OPTI__
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl->encoding), ENCODING_IDX_IN_MAIL_ATTACHMENT_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl->section), 0, SECTION_IDX_IN_MAIL_ATTACHMENT_TBL);
+#endif
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *attachment = p_data_tbl;
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_attachment_nth(int mail_id, int nth, emstorage_attachment_tbl_t** attachment_tbl, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], nth[%d], attachment_tbl[%p], transaction[%d], err_code[%p]", mail_id, nth, attachment_tbl, transaction, err_code);
+
+       if (mail_id <= 0 || nth <= 0 || !attachment_tbl)  {
+               EM_DEBUG_EXCEPTION(" mail_id[%d], nth[%d], attachment[%p]", mail_id, nth, attachment_tbl);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       emstorage_attachment_tbl_t* p_data_tbl = NULL;
+       char *p = NULL;
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_attachment_tbl WHERE mail_id = %d ORDER BY attachment_id LIMIT %d, 1", mail_id, (nth - 1));
+       EM_DEBUG_LOG("query = [%s]", sql_query_string);
+
+       DB_STMT hStmt = NULL;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION(" no matched attachment found...");
+               error = EMAIL_ERROR_ATTACHMENT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (!(p_data_tbl = (emstorage_attachment_tbl_t*)em_malloc(sizeof(emstorage_attachment_tbl_t) * 1)))  {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       p_data_tbl->attachment_id = sqlite3_column_int(hStmt, ATTACHMENT_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+       if ((p = (char *)sqlite3_column_text(hStmt, ATTACHMENT_NAME_IDX_IN_MAIL_ATTACHMENT_TBL)) && (int)EM_SAFE_STRLEN(p))
+               p_data_tbl->attachment_name = cpy_str(p);
+       if ((p = (char *)sqlite3_column_text(hStmt, ATTACHMENT_PATH_IDX_IN_MAIL_ATTACHMENT_TBL)) && (int)EM_SAFE_STRLEN(p))
+               p_data_tbl->attachment_path = cpy_str(p);
+       p_data_tbl->attachment_size = sqlite3_column_int(hStmt, ATTACHMENT_SIZE_IDX_IN_MAIL_ATTACHMENT_TBL);
+       p_data_tbl->mail_id = sqlite3_column_int(hStmt, MAIL_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+       p_data_tbl->account_id = sqlite3_column_int(hStmt, ACCOUNT_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+       p_data_tbl->mailbox_id = sqlite3_column_int(hStmt, MAILBOX_ID_IDX_IN_MAIL_ATTACHMENT_TBL);
+       p_data_tbl->attachment_save_status = sqlite3_column_int(hStmt, ATTACHMENT_SAVE_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL);
+       p_data_tbl->attachment_drm_type = sqlite3_column_int(hStmt, ATTACHMENT_DRM_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL);
+       p_data_tbl->attachment_drm_method = sqlite3_column_int(hStmt, ATTACHMENT_DRM_METHOD_IDX_IN_MAIL_ATTACHMENT_TBL);
+       p_data_tbl->attachment_inline_content_status = sqlite3_column_int(hStmt, ATTACHMENT_INLINE_CONTENT_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL);
+       if ((p = (char *)sqlite3_column_text(hStmt, ATTACHMENT_MIME_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL)) && (int)EM_SAFE_STRLEN(p))
+               p_data_tbl->attachment_mime_type = cpy_str(p);
+#ifdef __ATTACHMENT_OPTI__
+               p_data_tbl->encoding = sqlite3_column_int(hStmt, ENCODING_IDX_IN_MAIL_ATTACHMENT_TBL);
+               if ((p = (char *)sqlite3_column_text(hStmt, SECTION_IDX_IN_MAIL_ATTACHMENT_TBL)) && (int)EM_SAFE_STRLEN(p))
+                       p_data_tbl->section= cpy_str(p);
+#endif
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *attachment_tbl = p_data_tbl;
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_change_attachment_field(int mail_id, email_mail_change_type_t type, emstorage_attachment_tbl_t* attachment, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], type[%d], attachment[%p], transaction[%d], err_code[%p]", mail_id, type, attachment, transaction, err_code);
+
+       if (mail_id <= 0 || !attachment)  {
+               EM_DEBUG_EXCEPTION(" mail_id[%d], type[%d], attachment[%p]", mail_id, type, attachment);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int i = 0;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       switch (type)  {
+               case UPDATE_MAILBOX:
+                               EM_DEBUG_LOG("UPDATE_MAILBOX");
+                       if (!attachment->mailbox_id)  {
+                               EM_DEBUG_EXCEPTION(" attachment->mailbox_id[%d]", attachment->mailbox_id);
+                               error = EMAIL_ERROR_INVALID_PARAM;
+                               goto FINISH_OFF;
+                       }
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_attachment_tbl SET mailbox_id = ? WHERE mail_id = %d", mail_id);
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_LOG(" Before sqlite3_prepare hStmt = %p", hStmt);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+                       _bind_stmt_field_data_int(hStmt, i++, attachment->mailbox_id);
+                       break;
+
+               case UPDATE_SAVENAME:
+                       EM_DEBUG_LOG("UPDATE_SAVENAME");
+                       if (!attachment->attachment_path)  {
+                               EM_DEBUG_EXCEPTION(" attachment->attachment_path[%p]", attachment->attachment_path);
+                               error = EMAIL_ERROR_INVALID_PARAM;
+                               goto FINISH_OFF;
+                       }
+
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                               "UPDATE mail_attachment_tbl SET"
+                               "  attachment_size = ?"
+                               ", attachment_save_status = 1"
+                               ", attachment_path = ?"
+                               " WHERE mail_id = %d"
+                               " AND attachment_id = %d"
+                               , attachment->mail_id
+                               , attachment->attachment_id);
+
+
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+                       EM_DEBUG_LOG(" Before sqlite3_prepare hStmt = %p", hStmt);
+                       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+                       _bind_stmt_field_data_int(hStmt, i++, attachment->attachment_size);
+                       _bind_stmt_field_data_string(hStmt, i++, (char *)attachment->attachment_path, 0, ATTACHMENT_PATH_LEN_IN_MAIL_ATTACHMENT_TBL);
+                       break;
+
+               default:
+                       EM_DEBUG_LOG("type[%d]", type);
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG("query = [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_name, char *input_new_mailbox_alias, int input_transaction)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_new_mailbox_name[%p], input_new_mailbox_alias [%p], input_transaction[%d]", input_mailbox_id, input_new_mailbox_name, input_new_mailbox_alias, input_transaction);
+
+       int rc = 0;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = NULL;
+       int account_id = 0;
+       emstorage_mailbox_tbl_t *old_mailbox_data = NULL;
+
+       if (input_mailbox_id <= 0 || !input_new_mailbox_name || !input_new_mailbox_alias)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+
+       if ((error = emstorage_get_mailbox_by_id(input_mailbox_id, &old_mailbox_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", error);
+               goto FINISH_OFF;
+       }
+       account_id = old_mailbox_data->account_id;
+
+       EMSTORAGE_START_WRITE_TRANSACTION(input_transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_box_tbl SET"
+               " mailbox_name = '%s'"
+               ",alias = '%s'"
+               " WHERE mailbox_id = %d"
+               , input_new_mailbox_name
+               , input_new_mailbox_alias
+               , input_mailbox_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (sqlite3_changes(local_db_handle) == 0)
+               EM_DEBUG_LOG("no mail_meeting_tbl matched...");
+
+       /* Update mail_tbl */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_tbl SET"
+               " mailbox_name = '%s'"
+               " WHERE mailbox_id = %d"
+               , input_new_mailbox_name
+               , input_mailbox_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (sqlite3_changes(local_db_handle) == 0)
+               EM_DEBUG_LOG("no mail matched...");
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(input_transaction, ret, error);
+
+       if (ret) {
+               if (!emcore_notify_storage_event(NOTI_MAILBOX_RENAME, account_id, input_mailbox_id, input_new_mailbox_name, 0))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAILBOX_RENAME ] >>>> ");
+       }
+       else {
+               if (!emcore_notify_storage_event(NOTI_MAILBOX_RENAME_FAIL, account_id, input_mailbox_id, input_new_mailbox_name, error))
+                       EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [ NOTI_MAILBOX_RENAME_FAIL ] >>>> ");
+       }
+
+       if (old_mailbox_data)
+               emstorage_free_mailbox(&old_mailbox_data, 1, NULL);
+
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return error;
+}
+
+INTERNAL_FUNC int emstorage_get_new_attachment_no(int *attachment_no, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_no [%p], err_code[%p]", attachment_no, err_code);
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char *sql = "SELECT max(rowid) FROM mail_attachment_tbl;";
+       char **result;
+
+       if (!attachment_no)  {
+               EM_DEBUG_EXCEPTION("Invalid attachment");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       *attachment_no = -1;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL == result[1])
+               rc = 1;
+       else
+               rc = atoi(result[1])+1;
+
+       sqlite3_free_table(result);
+
+       *attachment_no = rc;
+       EM_DEBUG_LOG("attachment_no [%d]", *attachment_no);
+       ret = true;
+
+FINISH_OFF:
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_add_attachment(emstorage_attachment_tbl_t* attachment_tbl, int iscopy, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_tbl[%p], iscopy[%d], transaction[%d], err_code[%p]", attachment_tbl, iscopy, transaction, err_code);
+
+       char *sql = NULL;
+       char **result;
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       if (!attachment_tbl)  {
+               EM_DEBUG_EXCEPTION("attachment_tbl[%p], iscopy[%d]", attachment_tbl, iscopy);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       sql = "SELECT max(rowid) FROM mail_attachment_tbl;";
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL==result[1]) rc = 1;
+       else rc = atoi(result[1]) + 1;
+       sqlite3_free_table(result);
+
+       attachment_tbl->attachment_id = rc;
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_attachment_tbl VALUES "
+               "( ?"   /* attachment_id */
+               ", ?"   /* attachment_name */
+               ", ?"   /* attachment_path */
+               ", ?"   /* attachment_size */
+               ", ?"   /* mail_id */
+               ", ?"   /* account_id */
+               ", ?"   /* mailbox_id */
+               ", ?"   /* attachment_save_status */
+               ", ?"   /* attachment_drm_type */
+               ", ?"   /* attachment_drm_method */
+               ", ?"   /* attachment_inline_content_status */
+               ", ?"   /* attachment_mime_type */
+#ifdef __ATTACHMENT_OPTI__
+               ", ?"
+               ", ?"
+#endif
+               ")");
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       _bind_stmt_field_data_int   (hStmt, ATTACHMENT_ID_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->attachment_id);
+       _bind_stmt_field_data_string(hStmt, ATTACHMENT_NAME_IDX_IN_MAIL_ATTACHMENT_TBL, (char*)attachment_tbl->attachment_name, 0, ATTACHMENT_NAME_LEN_IN_MAIL_ATTACHMENT_TBL);
+       _bind_stmt_field_data_string(hStmt, ATTACHMENT_PATH_IDX_IN_MAIL_ATTACHMENT_TBL, (char*)attachment_tbl->attachment_path, 0, ATTACHMENT_PATH_LEN_IN_MAIL_ATTACHMENT_TBL);
+       _bind_stmt_field_data_int   (hStmt, ATTACHMENT_SIZE_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->attachment_size);
+       _bind_stmt_field_data_int   (hStmt, MAIL_ID_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->mail_id);
+       _bind_stmt_field_data_int   (hStmt, ACCOUNT_ID_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->account_id);
+       _bind_stmt_field_data_int   (hStmt, MAILBOX_ID_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->mailbox_id);
+       _bind_stmt_field_data_int   (hStmt, ATTACHMENT_SAVE_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->attachment_save_status);
+       _bind_stmt_field_data_int   (hStmt, ATTACHMENT_DRM_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->attachment_drm_type);
+       _bind_stmt_field_data_int   (hStmt, ATTACHMENT_DRM_METHOD_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->attachment_drm_method);
+       _bind_stmt_field_data_int   (hStmt, ATTACHMENT_INLINE_CONTENT_STATUS_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->attachment_inline_content_status);
+       _bind_stmt_field_data_string(hStmt, ATTACHMENT_MIME_TYPE_IDX_IN_MAIL_ATTACHMENT_TBL, (char*)attachment_tbl->attachment_mime_type, 0, ATTACHMENT_MIME_TYPE_LEN_IN_MAIL_ATTACHMENT_TBL);
+#ifdef __ATTACHMENT_OPTI__
+       _bind_stmt_field_data_int(hStmt, ENCODING_IDX_IN_MAIL_ATTACHMENT_TBL, attachment_tbl->encoding);
+       _bind_stmt_field_data_string(hStmt, SECTION_IDX_IN_MAIL_ATTACHMENT_TBL, (char*)attachment_tbl->section, 0, ATTACHMENT_LEN_IN_MAIL_ATTACHMENT_TBL);
+#endif
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+/*
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_tbl SET attachment_count = 1 WHERE mail_id = %d", attachment_tbl->mail_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+*/
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no matched mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+       *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_update_attachment(emstorage_attachment_tbl_t* attachment_tbl, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_tbl[%p], transaction[%d], err_code[%p]", attachment_tbl, transaction, err_code);
+
+       int rc, ret = false, field_idx = 0;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       if (!attachment_tbl)  {
+               EM_DEBUG_EXCEPTION(" attachment_tbl[%p] ", attachment_tbl);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_attachment_tbl SET  "
+               "  attachment_name = ?"
+               ", attachment_path =  ?"
+               ", attachment_size = ?"
+               ", mail_id = ?"
+               ", account_id = ?"
+               ", mailbox_id = ?"
+               ", attachment_save_status = ?"
+               ", attachment_drm_type = ?"
+               ", attachment_drm_method = ?"
+               ", attachment_inline_content_status = ? "
+               ", attachment_mime_type = ? "
+               " WHERE attachment_id = ?;");
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       _bind_stmt_field_data_string(hStmt, field_idx++ , (char*)attachment_tbl->attachment_name, 0, ATTACHMENT_NAME_LEN_IN_MAIL_ATTACHMENT_TBL);
+       _bind_stmt_field_data_string(hStmt, field_idx++ , (char*)attachment_tbl->attachment_path, 0, ATTACHMENT_PATH_LEN_IN_MAIL_ATTACHMENT_TBL);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->attachment_size);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->mail_id);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->account_id);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->mailbox_id);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->attachment_save_status);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->attachment_drm_type);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->attachment_drm_method);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->attachment_inline_content_status);
+       _bind_stmt_field_data_string(hStmt, field_idx++ , (char*)attachment_tbl->attachment_mime_type, 0, ATTACHMENT_MIME_TYPE_LEN_IN_MAIL_ATTACHMENT_TBL);
+       _bind_stmt_field_data_int   (hStmt, field_idx++ , attachment_tbl->attachment_id);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+/*
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_tbl SET attachment_count = 1 WHERE mail_id = %d", attachment_tbl->mail_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+*/
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no matched mail found...");
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+       *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_attachment_on_db(int attachment_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_id[%d], transaction[%d], err_code[%p]", attachment_id, transaction, err_code);
+
+       if (attachment_id < 0)  {
+               EM_DEBUG_EXCEPTION("attachment_id[%d]", attachment_id);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_attachment_tbl WHERE attachment_id = %d", attachment_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_all_attachments_of_mail(int mail_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], transaction[%d], err_code[%p]", mail_id, transaction, err_code);
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = NULL;
+
+       if (mail_id <= 0)  {
+               EM_DEBUG_EXCEPTION("mail_id[%d]", mail_id);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_attachment_tbl WHERE mail_id = %d", mail_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_attachment_all_on_db(int account_id, char *mailbox, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox[%p], transaction[%d], err_code[%p]", account_id, mailbox, transaction, err_code);
+
+       int error = EMAIL_ERROR_NONE;
+       int rc, ret = false;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_attachment_tbl");
+
+       if (account_id != ALL_ACCOUNT) /*  '0' means all account */
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " WHERE account_id = %d", account_id);
+
+       if (mailbox)    /*  NULL means all mailbox_name */
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " %s mailbox_name = '%s'", account_id != ALL_ACCOUNT ? "AND" : "WHERE", mailbox);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_attachment(emstorage_attachment_tbl_t** attachment_tbl_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_tbl_list[%p], count[%d], err_code[%p]", attachment_tbl_list, count, err_code);
+
+       if (count > 0)  {
+               if ((attachment_tbl_list == NULL) || (*attachment_tbl_list == NULL))  {
+                       EM_DEBUG_EXCEPTION(" attachment_tbl_list[%p], count[%d]", attachment_tbl_list, count);
+                       if (err_code != NULL)
+                               *err_code = EMAIL_ERROR_INVALID_PARAM;
+                       return false;
+               }
+
+               emstorage_attachment_tbl_t* p = *attachment_tbl_list;
+               int i;
+
+               for (i = 0; i < count; i++)  {
+                       EM_SAFE_FREE(p[i].attachment_name);
+                       EM_SAFE_FREE(p[i].attachment_path);
+                       EM_SAFE_FREE(p[i].attachment_mime_type);
+#ifdef __ATTACHMENT_OPTI__
+                       EM_SAFE_FREE(p[i].section);
+#endif
+               }
+
+               EM_SAFE_FREE(p);
+               *attachment_tbl_list = NULL;
+       }
+
+       if (err_code != NULL)
+               *err_code = EMAIL_ERROR_NONE;
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+
+
+INTERNAL_FUNC int emstorage_begin_transaction(void *d1, void *d2, int *err_code)
+{
+       EM_PROFILE_BEGIN(emStorageBeginTransaction);
+       int ret = true;
+
+       ENTER_CRITICAL_SECTION(_transactionBeginLock);
+
+       /*  wait for the trnasaction authority to be changed. */
+       while (g_transaction)  {
+               EM_DEBUG_LOG(">>>>>>>> Wait for the transaction authority to be changed");
+               usleep(50000);
+       }
+
+       /*  take the transaction authority. */
+       g_transaction = true;
+
+       LEAVE_CRITICAL_SECTION(_transactionBeginLock);
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       int rc;
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "BEGIN immediate;", NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {ret = false; },
+               ("SQL(BEGIN) exec error:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+       if (ret == false && err_code != NULL)
+               *err_code = EMAIL_ERROR_DB_FAILURE;
+
+       EM_PROFILE_END(emStorageBeginTransaction);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_commit_transaction(void *d1, void *d2, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = true;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       ENTER_CRITICAL_SECTION(_transactionEndLock);
+
+       int rc;
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "END;", NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {ret = false; }, ("SQL(END) exec error:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+       /*  release the transaction authority. */
+       g_transaction = false;
+
+       LEAVE_CRITICAL_SECTION(_transactionEndLock);
+       if (ret == false && err_code != NULL)
+               *err_code = EMAIL_ERROR_DB_FAILURE;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_rollback_transaction(void *d1, void *d2, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = true;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       int rc;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, "ROLLBACK;", NULL, NULL, NULL), rc);
+
+       ENTER_CRITICAL_SECTION(_transactionEndLock);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {ret = false; },
+               ("SQL(ROLLBACK) exec error:%d -%s", rc, sqlite3_errmsg(local_db_handle)));
+
+       /*  release the transaction authority. */
+       g_transaction = false;
+
+       LEAVE_CRITICAL_SECTION(_transactionEndLock);
+
+       if (ret == false && err_code != NULL)
+               *err_code = EMAIL_ERROR_DB_FAILURE;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_is_mailbox_full(int account_id, email_mailbox_t *mailbox, int *result, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox[%p], result[%p], err_code[%p]", account_id, mailbox, result, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || !mailbox || !result)  {
+               if (mailbox)
+                       EM_DEBUG_EXCEPTION("Invalid Parameter. accoun_id[%d], mailbox[%p]", account_id, mailbox);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int mail_count = 0;
+
+       if (!emstorage_get_mail_count(account_id, mailbox->mailbox_name, &mail_count, NULL, true, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_count failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       if (mailbox) {
+               EM_DEBUG_LOG("mail_count[%d] mail_slot_size[%d]", mail_count, mailbox->mail_slot_size);
+               if (mail_count >= mailbox->mail_slot_size)
+                       *result = true;
+               else
+                       *result = false;
+
+               ret = true;
+       }
+
+       ret = true;
+FINISH_OFF:
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_clear_mail_data(int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("transaction[%d], err_code[%p]", transaction, err_code);
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       const email_db_object_t* tables = _g_db_tables;
+       const email_db_object_t* indexes = _g_db_indexes;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       if (!emstorage_delete_dir(MAILHOME, &error)) {
+               EM_DEBUG_EXCEPTION(" emstorage_delete_dir failed - %d", error);
+
+               goto FINISH_OFF;
+       }
+
+       mkdir(MAILHOME, DIRECTORY_PERMISSION);
+       mkdir(MAILTEMP, DIRECTORY_PERMISSION);
+
+       /*  first clear index. */
+       while (indexes->object_name)  {
+               if (indexes->data_flag)  {
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DROP index %s", indexes->object_name);
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+                       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               }
+               indexes++;
+       }
+
+       while (tables->object_name)  {
+               if (tables->data_flag)  {
+                       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DROP table %s", tables->object_name);
+                       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+                       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               }
+
+               tables++;
+       }
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+/*======================= DB File Utils =============================================*/
+#include <dirent.h>
+#include <sys/types.h>
+#define  DIR_SEPERATOR "/"
+
+INTERNAL_FUNC char *emstorage_make_directory_path_from_file_path(char *file_name)
+{
+       EM_DEBUG_FUNC_BEGIN("Filename [ %p ]", file_name);
+       char delims[] = "/";
+       char *result = NULL;
+
+       result = strtok(file_name, delims);
+
+       if (result)
+               EM_DEBUG_LOG(">>>> Directory_name [ %s ]", result);
+       else
+               EM_DEBUG_LOG(">>>> No Need to create Directory");
+
+       return result;
+}
+
+INTERNAL_FUNC int emstorage_get_save_name(int account_id, int mail_id, int atch_id, char *fname, char *name_buf, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], atch_id[%d], fname[%s], name_buf[%p], err_code[%p]", account_id, mail_id, atch_id, fname, name_buf, err_code);
+       EM_PROFILE_BEGIN(profile_emstorage_get_save_name);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char *dir_name = NULL;
+       char create_dir[1024]={0};
+       char *temp_file = NULL;
+
+       if (!name_buf || account_id < FIRST_ACCOUNT_ID || mail_id < 0 || atch_id < 0)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mail_id[%d], atch_id[%d], fname[%p], name_buf[%p]", account_id, mail_id, atch_id, fname, name_buf);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       sprintf(name_buf, "%s", MAILHOME);
+       sprintf(name_buf+EM_SAFE_STRLEN(name_buf), "%s%d", DIR_SEPERATOR, account_id);
+
+       if (mail_id > 0)
+               sprintf(name_buf+EM_SAFE_STRLEN(name_buf), "%s%d", DIR_SEPERATOR, mail_id);
+
+       if (atch_id > 0)
+               sprintf(name_buf+EM_SAFE_STRLEN(name_buf), "%s%d", DIR_SEPERATOR, atch_id);
+
+       if (fname) {
+               temp_file = EM_SAFE_STRDUP(fname);
+               if (strstr(temp_file, "/")) {
+                       dir_name = emstorage_make_directory_path_from_file_path(temp_file);
+               }
+       }
+
+       if (dir_name) {
+               sprintf(create_dir, "%s%s%s", name_buf, DIR_SEPERATOR, dir_name);
+               EM_DEBUG_LOG(">>>>> DIR PATH [ %s ]", create_dir);
+               mkdir(create_dir, DIRECTORY_PERMISSION);
+               EM_SAFE_FREE(temp_file);
+       }
+
+       if (fname) {
+               EM_DEBUG_LOG(">>>>> fname [ %s ]", fname);
+               sprintf(name_buf+EM_SAFE_STRLEN(name_buf), "%s%s", DIR_SEPERATOR, fname);
+       }
+
+       EM_DEBUG_LOG(">>>>> name_buf [ %s ]", name_buf);
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(temp_file);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(profile_emstorage_get_save_name);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_dele_name(int account_id, int mail_id, int atch_id, char *fname, char *name_buf, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], atch_id[%d], fname[%p], name_buf[%p], err_code[%p]", account_id, mail_id, atch_id, fname, name_buf, err_code);
+
+       if (!name_buf || account_id < FIRST_ACCOUNT_ID)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mail_id[%d], atch_id[%d], fname[%p], name_buf[%p]", account_id, mail_id, atch_id, fname, name_buf);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       sprintf(name_buf+EM_SAFE_STRLEN(name_buf),      "%s%s%d", MAILHOME, DIR_SEPERATOR, account_id);
+
+       if (mail_id > 0)
+               sprintf(name_buf+EM_SAFE_STRLEN(name_buf),      "%s%d", DIR_SEPERATOR, mail_id);
+       else
+               goto FINISH_OFF;
+
+       if (atch_id > 0)
+               sprintf(name_buf+EM_SAFE_STRLEN(name_buf),      "%s%d", DIR_SEPERATOR, atch_id);
+       else
+               goto FINISH_OFF;
+
+FINISH_OFF:
+       sprintf(name_buf+EM_SAFE_STRLEN(name_buf),      ".DELE");
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+INTERNAL_FUNC int emstorage_create_dir(int account_id, int mail_id, int atch_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], atch_id[%d], err_code[%p]", account_id, mail_id, atch_id, err_code);
+       EM_PROFILE_BEGIN(profile_emcore_save_create_dir);
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       char buf[512];
+       struct stat sbuf;
+       if (account_id >= FIRST_ACCOUNT_ID)  {
+               SNPRINTF(buf, sizeof(buf), "%s%s%d", MAILHOME, DIR_SEPERATOR, account_id);
+
+               if (stat(buf, &sbuf) == 0) {
+                       if ((sbuf.st_mode & S_IFMT) != S_IFDIR)  {
+                               EM_DEBUG_EXCEPTION(" a object which isn't directory aleady exists");
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+               else  {
+                       if (mkdir(buf, DIRECTORY_PERMISSION) != 0) {
+                               EM_DEBUG_EXCEPTION(" mkdir failed [%s]", buf);
+                               EM_DEBUG_EXCEPTION("mkdir failed l(Errno=%d)][ErrStr=%s]", errno, strerror(errno));
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       if (mail_id > 0)  {
+               if (account_id < FIRST_ACCOUNT_ID)  {
+                       EM_DEBUG_EXCEPTION("account_id[%d], mail_id[%d], atch_id[%d]", account_id, mail_id, atch_id);
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               SNPRINTF(buf+EM_SAFE_STRLEN(buf), sizeof(buf), "%s%d", DIR_SEPERATOR, mail_id);
+
+               if (stat(buf, &sbuf) == 0) {
+                       if ((sbuf.st_mode & S_IFMT) != S_IFDIR)  {
+                               EM_DEBUG_EXCEPTION(" a object which isn't directory aleady exists");
+
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+               else  {
+                       if (mkdir(buf, DIRECTORY_PERMISSION) != 0) {
+                               EM_DEBUG_EXCEPTION(" mkdir failed [%s]", buf);
+                               EM_DEBUG_EXCEPTION("mkdir failed l (Errno=%d)][ErrStr=%s]", errno, strerror(errno));
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       if (atch_id > 0)  {
+               if (account_id < FIRST_ACCOUNT_ID || mail_id <= 0)  {
+                       EM_DEBUG_EXCEPTION(" account_id[%d], mail_id[%d], atch_id[%d]", account_id, mail_id, atch_id);
+
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               SNPRINTF(buf+EM_SAFE_STRLEN(buf), sizeof(buf)-(EM_SAFE_STRLEN(buf)+1), "%s%d", DIR_SEPERATOR, atch_id);
+
+               if (stat(buf, &sbuf) == 0) {
+                       if ((sbuf.st_mode & S_IFMT) != S_IFDIR)  {
+                               EM_DEBUG_EXCEPTION(" a object which isn't directory aleady exists");
+
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+               else  {
+                       if (mkdir(buf, DIRECTORY_PERMISSION) != 0) {
+                               EM_DEBUG_EXCEPTION(" mkdir failed [%s]", buf);
+                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(profile_emcore_save_create_dir);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_copy_file(char *src_file, char *dst_file, int sync_status, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("src_file[%s], dst_file[%s], err_code[%p]", src_file, dst_file, err_code);
+       EM_DEBUG_LOG("Using the fsync function");
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       struct stat st_buf;
+
+       int fp_src = 0;
+       int fp_dst = 0;
+       int nread = 0;
+       int nwritten = 0;
+       char *buf =  NULL;
+       int buf_size = 0;
+
+       if (!src_file || !dst_file)  {
+               EM_DEBUG_EXCEPTION("src_file[%p], dst_file[%p]", src_file, dst_file);
+
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (stat(src_file, &st_buf) < 0) {
+               EM_DEBUG_EXCEPTION("stat(\"%s\") failed...", src_file);
+
+               error = EMAIL_ERROR_SYSTEM_FAILURE;             /* EMAIL_ERROR_INVALID_PATH; */
+               goto FINISH_OFF;
+       }
+
+       buf_size =  st_buf.st_size;
+       EM_DEBUG_LOG(">>>> File Size [ %d ]", buf_size);
+       buf = (char *)calloc(1, buf_size+1);
+
+       if (!buf) {
+               EM_DEBUG_EXCEPTION(">>> Memory cannot be allocated");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if (buf) {
+               if ((fp_src = open(src_file, O_RDONLY))<0) { /*prevent 24474*/
+                       EM_DEBUG_EXCEPTION(">>>> Source Fail open %s Failed [ %d ] - Error [ %s ]", src_file, errno, strerror(errno));
+                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if ((fp_dst = open(dst_file, O_CREAT | O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH))<0) { /*prevent 24474*/
+                       EM_DEBUG_EXCEPTION(">>>> Destination Fail open %s Failed [ %d ] - Error [ %s ]", dst_file, errno, strerror(errno));
+                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               while ((nread = read(fp_src, buf, buf_size)) > 0) {
+                       if (nread > 0 && nread <= buf_size)  {
+                               EM_DEBUG_LOG("Nread Value [%d]", nread);
+                               if ((nwritten = write(fp_dst, buf, nread)) != nread) {
+                                       EM_DEBUG_EXCEPTION("fwrite failed...[%d] : [%s]", errno, strerror(errno));
+                                       error = EMAIL_ERROR_UNKNOWN;
+                                       goto FINISH_OFF;
+                               }
+                               EM_DEBUG_LOG("NWRITTEN [%d]", nwritten);
+                       }
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (fp_src>0) /*prevent 24474*/
+               close(fp_src);
+
+       if (fp_dst>0) { /*prevent 24474*/
+               if (sync_status) {
+                       EM_DEBUG_LOG("Before fsync");
+                       fsync(fp_dst);
+               }
+               close(fp_dst);
+       }
+       EM_SAFE_FREE(buf);
+       if (nread < 0 || error == EMAIL_ERROR_UNKNOWN)
+               remove(dst_file);
+
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+/* create Directory if user has deleted [deepam.p@samsung.com] */
+INTERNAL_FUNC void emstorage_create_dir_if_delete()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       mkdir(EMAILPATH, DIRECTORY_PERMISSION);
+       mkdir(DATA_PATH, DIRECTORY_PERMISSION);
+       mkdir(MAILHOME, DIRECTORY_PERMISSION);
+       mkdir(MAILTEMP, DIRECTORY_PERMISSION);
+
+       EM_DEBUG_FUNC_END();
+}
+static int _get_temp_file_name(char **filename, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filename[%p], err_code[%p]", filename, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (filename == NULL) {
+               EM_DEBUG_EXCEPTION(" filename[%p]", filename);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       char tempname[512] = {0x00, };
+       struct timeval tv;
+
+       gettimeofday(&tv, NULL);
+       srand(tv.tv_usec);
+
+       SNPRINTF(tempname, sizeof(tempname), "%s%c%d", MAILTEMP, '/', rand());
+
+       char *p = EM_SAFE_STRDUP(tempname);
+       if (p == NULL)  {
+               EM_DEBUG_EXCEPTION(" strdup failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       *filename = p;
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_add_content_type(char *file_path, char *char_set, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("File path [ %p ]  Character Set [ %p ] err_code [ %p]", file_path, char_set, err_code);
+
+       EM_IF_NULL_RETURN_VALUE(file_path, false);
+       EM_IF_NULL_RETURN_VALUE(char_set, false);
+       EM_IF_NULL_RETURN_VALUE(err_code, false);
+
+       char *buf =  NULL;
+       char *buf1 = NULL;
+       struct stat st_buf;
+       int buf_size = 0;
+       char *low_char_set = NULL;
+       char *match_str = NULL;
+       int nwritten = 0;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int data_count_to_written = 0;
+       char *temp_file_name = NULL;
+       int err = 0;
+
+       FILE* fp_src = NULL;
+       FILE* fp_dest = NULL;
+       int nread = 0;
+
+
+       if (stat(file_path, &st_buf) < 0) {
+               EM_DEBUG_EXCEPTION(" stat(\"%s\") failed...", file_path);
+
+               error = EMAIL_ERROR_SYSTEM_FAILURE;             /* EMAIL_ERROR_INVALID_PATH; */
+               goto FINISH_OFF;
+       }
+
+       buf_size =  st_buf.st_size;
+
+       EM_DEBUG_LOG(">>>> File Size [ %d ] ", buf_size);
+
+       buf = (char *)calloc(1, buf_size+1);
+
+       if (!buf) {
+               EM_DEBUG_LOG(">>> Memory cannot be allocated ");
+               goto FINISH_OFF;
+       }
+
+       if (!(fp_src = fopen(file_path, "rb"))) {
+               EM_DEBUG_EXCEPTION(" file_path fopen failed - %s", file_path);
+
+                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               if ((nread = fread(buf, 1, buf_size, fp_src)) > 0) {
+                       if (nread > 0 && nread <= buf_size)  {
+                               EM_DEBUG_LOG(">>>> Nread Value [ %d ] ", nread);
+
+                               /**
+                                 *   1.Add check for whether content type is there.
+                                 *   2. If not based on the character set, Append it in File
+                                 **/
+
+                               low_char_set = calloc(1, EM_SAFE_STRLEN(char_set) + strlen(" \" /></head>") +1); /*prevent 34359*/
+
+                               strncat(low_char_set, char_set, EM_SAFE_STRLEN(char_set));
+
+                               EM_DEBUG_LOG(">>>> CHAR SET [ %s ] ", low_char_set);
+
+                               strncat(low_char_set, " \" /></head>", strlen(" \" /></head>")); /*prevent 34359*/
+
+                               EM_DEBUG_LOG(">>> CHARSET [ %s ] ", low_char_set);
+
+                               EM_DEBUG_LOG(">>>>emstorage_add_content_type 1 ");
+
+                               match_str = strstr(buf, CONTENT_TYPE_DATA);
+                               EM_DEBUG_LOG(">>>>emstorage_add_content_type 2 ");
+
+                               if (match_str == NULL) {
+                                       EM_DEBUG_LOG(">>>>emstorage_add_content_type 3 ");
+                                       if (fp_src !=NULL) {
+                                               fclose(fp_src);fp_src = NULL;
+                                       }
+                               data_count_to_written = EM_SAFE_STRLEN(low_char_set)+strlen(CONTENT_DATA)+1; /*prevent 34359*/
+                                       EM_DEBUG_LOG(">>>>emstorage_add_content_type 4 ");
+                               buf1 = (char *)calloc(1, data_count_to_written);
+                                       EM_DEBUG_LOG(">>>>emstorage_add_content_type 5 ");
+
+                                       if (buf1) {
+                                               EM_DEBUG_LOG(">>>>emstorage_add_content_type 6 ");
+                                               strncat(buf1, CONTENT_DATA, strlen(CONTENT_DATA)); /*prevent 34359*/
+
+                                               EM_DEBUG_LOG(">>>>> BUF 1 [ %s ] ", buf1);
+
+                                               strncat(buf1, low_char_set, EM_SAFE_STRLEN(low_char_set));
+
+                                               EM_DEBUG_LOG(">>>> HTML TAG DATA  [ %s ] ", buf1);
+
+
+                                       /* 1. Create a temporary file name */
+                                       if (!_get_temp_file_name(&temp_file_name, &err)) {
+                                                       EM_DEBUG_EXCEPTION(" emcore_get_temp_file_name failed - %d", err);
+                                                       if (err_code != NULL) *err_code = err;
+                                                       EM_SAFE_FREE(temp_file_name);
+                                                       goto FINISH_OFF;
+                                       }
+                                       EM_DEBUG_LOG(">>>>>>> TEMP APPEND FILE PATH [ %s ] ", temp_file_name);
+
+                                       /* Open the Temp file in Append mode */
+                                       if (!(fp_dest = fopen(temp_file_name, "ab"))) {
+                                               EM_DEBUG_EXCEPTION(" fopen failed - %s", temp_file_name);
+                                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       /* 2. write the Latest data */
+                                       nwritten = fwrite(buf1, data_count_to_written-1, 1, fp_dest);
+
+                                       if (nwritten > 0) {
+                                               EM_DEBUG_LOG(" Latest Data  : [%d ] bytes written ", nwritten);
+                                               nwritten = 0;
+                                               /* 3. Append old data */
+                                               nwritten = fwrite(buf, nread-1, 1, fp_dest);
+
+                                               if (nwritten <= 0) {
+                                                       EM_DEBUG_EXCEPTION(" Error Occured while writing Old data : [%d ] bytes written ", nwritten);
+                                                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                                                       goto FINISH_OFF;
+                                               }
+                                               else {
+                                                       EM_DEBUG_LOG(">>>> OLD data appended [ %d ] ", nwritten);
+
+                                                       if (!emstorage_move_file(temp_file_name, file_path, false, &err)) {
+                                                               EM_DEBUG_EXCEPTION(" emstorage_move_file failed - %d", err);
+                                                               goto FINISH_OFF;
+                                                       }
+                                               }
+
+                                       }
+                                       else {
+                                               EM_DEBUG_EXCEPTION(" Error Occured while writing New data : [%d ] bytes written ", nwritten);
+                                               error = EMAIL_ERROR_SYSTEM_FAILURE;
+                                               goto FINISH_OFF;
+                                       }
+
+                                       }
+
+                               }
+                               EM_DEBUG_LOG(">>>>emstorage_add_content_type 15 ");
+
+
+                       }
+               }
+
+       ret = true;
+FINISH_OFF:
+
+       EM_SAFE_FREE(buf);
+       EM_SAFE_FREE(buf1);
+       EM_SAFE_FREE(low_char_set);
+
+       if (fp_src != NULL) {
+               fclose(fp_src);
+               fp_src = NULL;
+       }
+
+       if (fp_dest != NULL) {
+               fclose(fp_dest);
+               fp_dest = NULL;
+       }
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+
+INTERNAL_FUNC int emstorage_move_file(char *src_file, char *dst_file, int sync_status, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("src_file[%p], dst_file[%p], err_code[%p]", src_file, dst_file, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (src_file == NULL || dst_file == NULL)  {
+               EM_DEBUG_EXCEPTION("src_file[%p], dst_file[%p]", src_file, dst_file);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("src_file[%s], dst_file[%s]", src_file, dst_file);
+
+       if (strcmp(src_file, dst_file) != 0) {
+               if (rename(src_file, dst_file) != 0) {
+                       if (errno == EXDEV)  {  /* oldpath and newpath are not on the same mounted file system.  (Linux permits a file system to be mounted at multiple points,  but  rename() */
+                               /*  does not work across different mount points, even if the same file system is mounted on both.)       */
+                               EM_DEBUG_LOG("oldpath and newpath are not on the same mounted file system.");
+                               if (!emstorage_copy_file(src_file, dst_file, sync_status, &error)) {
+                                       EM_DEBUG_EXCEPTION("emstorage_copy_file failed - %d", error);
+                                       goto FINISH_OFF;
+                               }
+                               remove(src_file);
+                               EM_DEBUG_LOG("src[%s] removed", src_file);
+
+                       }
+                       else  {
+                               if (errno == ENOENT)  {
+                                       struct stat temp_file_stat;
+                                       if (stat(src_file, &temp_file_stat) < 0)
+                                               EM_DEBUG_EXCEPTION("no src file found [%s]", src_file);
+                                       if (stat(dst_file, &temp_file_stat) < 0)
+                                               EM_DEBUG_EXCEPTION("no dst file found [%s]", src_file);
+
+                                       EM_DEBUG_EXCEPTION("no file found [%d]", errno);
+                                       error = EMAIL_ERROR_FILE_NOT_FOUND;
+                                       goto FINISH_OFF;
+
+                               }
+                               else  {
+                                       EM_DEBUG_EXCEPTION("rename failed [%d]", errno);
+                                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                                       goto FINISH_OFF;
+                               }
+                       }
+               }
+       }
+       else {
+               EM_DEBUG_LOG("src[%s] = dst[%d]", src_file, dst_file);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_file(char *src_file, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("src_file[%p], err_code[%p]", src_file, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (src_file == NULL) {
+               EM_DEBUG_EXCEPTION(" src_file[%p]", src_file);
+
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (remove(src_file) != 0) {
+               if (errno != ENOENT) {
+                       EM_DEBUG_EXCEPTION(" remove failed - %d", errno);
+
+                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+                       goto FINISH_OFF;
+               }
+               else {
+                       EM_DEBUG_EXCEPTION(" no file found...");
+
+                       error = EMAIL_ERROR_FILE_NOT_FOUND;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_delete_dir(char *src_dir, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("src_dir[%p], err_code[%p]", src_dir, err_code);
+
+       if (src_dir == NULL) {
+               EM_DEBUG_EXCEPTION("src_dir[%p]", src_dir);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int error = EMAIL_ERROR_NONE;
+
+       DIR *dirp;
+       struct dirent *dp;
+       struct stat sbuf;
+       char buf[512];
+
+       dirp = opendir(src_dir);
+
+       if (dirp == NULL)  {
+               if (errno == ENOENT)  {
+                       EM_DEBUG_EXCEPTION("directory[%s] does not exist...", src_dir);
+                       if (err_code != NULL)
+                               *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
+                       return true;
+               }
+               else  {
+                       EM_DEBUG_EXCEPTION("opendir failed - %d", errno);
+                       if (err_code != NULL)
+                               *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
+                       return false;
+               }
+       }
+
+       while ((dp=readdir(dirp)))  {
+               if (strncmp(dp->d_name, ".", 1) == 0 || strncmp(dp->d_name, "..", 2) == 0) /* prevent 34360 */
+                       continue;
+
+               SNPRINTF(buf, sizeof(buf), "%s/%s", src_dir, dp->d_name);
+
+               if (lstat(buf, &sbuf) == 0 || stat(buf, &sbuf) == 0) {
+                       /*  check directory */
+                       if ((sbuf.st_mode & S_IFMT) == S_IFDIR)  {      /*  directory */
+                               /*  recursive call */
+                               if (!emstorage_delete_dir(buf, &error)) {
+                                       closedir(dirp);
+                                       if (err_code != NULL)
+                                               *err_code = error;
+                                       return false;
+                               }
+                       }
+                       else  { /*  file */
+                               if (remove(buf) < 0)  {
+                                       EM_DEBUG_EXCEPTION("remove failed - %s", buf);
+                                       closedir(dirp);
+                                       if (err_code != NULL)
+                                               *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
+                                       return false;
+                               }
+                       }
+               }
+               else
+                       EM_DEBUG_EXCEPTION("content does not exist...");
+       }
+
+       closedir(dirp);
+
+       EM_DEBUG_LOG("remove direcotory [%s]", src_dir);
+
+       /* EM_DEBUG_FUNC_BEGIN(); */
+
+       if (remove(src_dir) < 0)  {
+               EM_DEBUG_EXCEPTION("remove failed [%s]", src_dir);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_SYSTEM_FAILURE;
+               return false;
+       }
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       return true;
+}
+
+/* faizan.h@samsung.com */
+INTERNAL_FUNC int emstorage_update_server_uid(char *old_server_uid, char *new_server_uid, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("new_server_uid[%s], old_server_uid[%s]", new_server_uid, old_server_uid);
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int transaction = true;
+
+       if (!old_server_uid || !new_server_uid) {
+               EM_DEBUG_EXCEPTION("Invalid parameters");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                "UPDATE mail_tbl SET server_mail_id=\'%s\' WHERE server_mail_id=%s ", new_server_uid, old_server_uid);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+
+INTERNAL_FUNC int emstorage_update_read_mail_uid(int mail_id, char *new_server_uid, char *mbox_name, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], new_server_uid[%s], mbox_name[%s]", mail_id, new_server_uid, mbox_name);
+
+       int rc, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int transaction = true;
+
+       if (!mail_id || !new_server_uid || !mbox_name)  {
+               EM_DEBUG_EXCEPTION("Invalid parameters");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                "UPDATE mail_read_mail_uid_tbl SET s_uid=\'%s\', mailbox_id=\'%s\', mailbox_name=\'%s\' WHERE local_uid=%d ", new_server_uid, mbox_name, mbox_name, mail_id);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       ret     = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+
+
+int emstorage_get_latest_unread_mailid(int account_id, int *mail_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if ((!mail_id) ||(account_id <= 0 &&  account_id != -1)) {
+               EM_DEBUG_EXCEPTION(" mail_id[%p], account_id[%d] ", mail_id, account_id);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int rc = -1;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       int count = 0;
+       int mailid = 0;
+       int transaction = false;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       if (account_id == -1)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mail_id FROM mail_tbl WHERE flags_seen_field = 0 ORDER BY mail_id DESC");
+       else
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mail_id FROM mail_tbl WHERE account_id = %d AND flags_seen_field = 0 ORDER BY mail_id DESC", account_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("  sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       char **result;
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       sqlite3_free_table(result);
+       if (count == 0)  {
+               EM_DEBUG_EXCEPTION("no Mails found...");
+               ret = false;
+               error= EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       _get_stmt_field_data_int(hStmt, &mailid, 0);
+       EM_DEBUG_LOG("mailid [%d]", mailid);
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (mail_id != NULL)
+               *mail_id = mailid;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+int setting_system_command(const char *command)
+
+ {
+       int pid = 0, status = 0;
+       char *const environ[] = { NULL };
+
+       if (command == 0)
+               return 1;
+
+       pid = fork();
+
+       if (pid == -1)
+               return -1;
+
+       if (pid == 0) {
+               char *argv[4];
+
+               argv[0] = "sh";
+               argv[1] = "-c";
+               argv[2] = (char *)command;
+               argv[3] = 0;
+
+               execve("/bin/sh", argv, environ);
+               abort();
+       }
+       do{
+               if (waitpid(pid, &status, 0) == -1) {
+                       if (errno != EINTR)
+                               return -1;
+               }
+               else {
+                       return status;
+               }
+       } while (1);
+
+       return 0;
+}
+
+
+INTERNAL_FUNC int emstorage_mail_get_total_diskspace_usage(unsigned long *total_usage,  int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("total_usage[%p],  transaction[%d], err_code[%p]", total_usage, transaction, err_code);
+
+       if (!total_usage) {
+               EM_DEBUG_EXCEPTION("total_usage[%p]", total_usage);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int   ret = false;
+       int   error = EMAIL_ERROR_NONE;
+       char  syscmd[256] = {0, };
+       char  line[256] = {0, };
+       char *line_from_file = NULL;
+       FILE *fp = NULL;
+       unsigned long total_diskusage = 0;
+
+       SNPRINTF(syscmd, sizeof(syscmd), "touch %s", SETTING_MEMORY_TEMP_FILE_PATH);
+       if (setting_system_command(syscmd) == -1) {
+               EM_DEBUG_EXCEPTION("emstorage_mail_get_total_diskspace_usage : [Setting > Memory] System Command [%s] is failed", syscmd);
+
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(syscmd, sizeof(syscmd), "du -hsk %s > %s", EMAILPATH, SETTING_MEMORY_TEMP_FILE_PATH);
+       EM_DEBUG_LOG(" cmd : %s", syscmd);
+       if (setting_system_command(syscmd) == -1) {
+               EM_DEBUG_EXCEPTION("emstorage_mail_get_total_diskspace_usage : Setting > Memory] System Command [%s] is failed", syscmd);
+
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       fp = fopen(SETTING_MEMORY_TEMP_FILE_PATH, "r");
+       if (fp == NULL) {
+               perror(SETTING_MEMORY_TEMP_FILE_PATH);
+
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       line_from_file = fgets(line, sizeof(line), fp);
+
+       if(line_from_file == NULL) {
+               EM_DEBUG_EXCEPTION("fgets failed");
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+       total_diskusage = strtoul(line, NULL, 10);
+
+       memset(syscmd, 0, sizeof(syscmd));
+       SNPRINTF(syscmd, sizeof(syscmd), "rm -f %s", SETTING_MEMORY_TEMP_FILE_PATH);
+       if (setting_system_command(syscmd) == -1) {
+               EM_DEBUG_EXCEPTION("emstorage_mail_get_total_diskspace_usage :  [Setting > Memory] System Command [%s] is failed", syscmd);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("[Setting > Memory] @@@@@ Size of Directory [%s] is %ld KB", EMAILPATH, total_diskusage);
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       if (ret)
+               *total_usage = total_diskusage;
+       else
+               *total_usage = 0;
+
+       if(fp) fclose(fp); /* prevent 32730 */
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_test(int mail_id, int account_id, char *full_address_to, char *full_address_cc, char *full_address_bcc, int *err_code)
+{
+       DB_STMT hStmt = NULL;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int rc = 0;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_tbl VALUES "
+               "( ?" /*  mail_id */
+               ", ?" /*  account_id */
+               ", ?" /*  mailbox_name */
+               ", ?" /*  mail_size */
+               ", ?" /*  server_mail_status */
+               ", ?" /*  server_mailbox_name */
+               ", ?" /*  server_mail_id */
+               ", ?" /*  reference_mail_id */
+               ", ?" /*  full_address_from */
+               ", ?" /*  full_address_reply */
+               ", ?" /*  full_address_to */
+               ", ?" /*  full_address_cc */
+               ", ?" /*  full_address_bcc */
+               ", ?" /*  full_address_return */
+               ", ?" /*  subject */
+               ", ?" /*  body_download_status */
+               ", ?" /*  file_path_plain */
+               ", ?" /*  file_path_html */
+               ", ?" /*  date_time */
+               ", ?" /*  flags_seen_field */
+               ", ?" /*  flags_deleted_field */
+               ", ?" /*  flags_flagged_field */
+               ", ?" /*  flags_answered_field */
+               ", ?" /*  flags_recent_field */
+               ", ?" /*  flags_draft_field */
+               ", ?" /*  flags_forwarded_field */
+               ", ?" /*  DRM_status */
+               ", ?" /*  priority */
+               ", ?" /*  save_status */
+               ", ?" /*  lock_status */
+               ", ?" /*  message_id */
+               ", ?" /*  report_status */
+               ", ?" /*  email_address_sender */
+               ", ?" /*  email_address_recipient */
+               ", ?" /*  attachment_count */
+               ", ?" /*  inline_content_count */
+               ", ?" /*  preview_text */
+               ", ?" /*  thread_id */
+               ", ?" /*  mailbox_type */
+               ", ?" /*  alias_sender */
+               ", ?" /*  alias_recipient */
+               ", ?" /*  thread_item_count */
+               ", ?" /*  meeting_request_status */
+               ", ?" /*  message_class */
+               ", ?" /*  digest_type */
+               ", ?" /*  smime_type */
+               ")");
+
+       int transaction = true;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       _bind_stmt_field_data_int(hStmt, MAIL_ID_IDX_IN_MAIL_TBL, mail_id);
+       _bind_stmt_field_data_int(hStmt, ACCOUNT_ID_IDX_IN_MAIL_TBL, account_id);
+       _bind_stmt_field_data_string(hStmt, MAILBOX_NAME_IDX_IN_MAIL_TBL, "OUTBOX", 0, MAILBOX_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int(hStmt, MAILBOX_TYPE_IDX_IN_MAIL_TBL, EMAIL_MAILBOX_TYPE_OUTBOX);
+       _bind_stmt_field_data_string(hStmt, SUBJECT_IDX_IN_MAIL_TBL, "save test - long", 1, SUBJECT_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, DATETIME_IDX_IN_MAIL_TBL, "20100316052908", 0, DATETIME_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int(hStmt, SERVER_MAIL_STATUS_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_string(hStmt, SERVER_MAILBOX_NAME_IDX_IN_MAIL_TBL, "", 0, SERVER_MAILBOX_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, SERVER_MAIL_ID_IDX_IN_MAIL_TBL, "", 0, SERVER_MAIL_ID_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, MESSAGE_ID_IDX_IN_MAIL_TBL, "", 0, MESSAGE_ID_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int(hStmt, REFERENCE_ID_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_FROM_IDX_IN_MAIL_TBL, "<test08@streaming.s3glab.net>", 1, FROM_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_REPLY_IDX_IN_MAIL_TBL, "", 1, REPLY_TO_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_TO_IDX_IN_MAIL_TBL, full_address_to, 1, TO_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_CC_IDX_IN_MAIL_TBL, full_address_cc, 1, CC_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_BCC_IDX_IN_MAIL_TBL, full_address_bcc, 1, BCC_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FULL_ADDRESS_RETURN_IDX_IN_MAIL_TBL, "", 1, RETURN_PATH_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, EMAIL_ADDRESS_SENDER_IDX_IN_MAIL_TBL, "<sender_name@sender_host.com>", 1, FROM_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, EMAIL_ADDRESS_RECIPIENT_IDX_IN_MAIL_TBL, "<recipient_name@recipient_host.com>", 1, TO_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, ALIAS_SENDER_IDX_IN_MAIL_TBL, "send_alias", 1, FROM_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, ALIAS_RECIPIENT_IDX_IN_MAIL_TBL, "recipient_alias", 1, TO_EMAIL_ADDRESS_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int(hStmt, BODY_DOWNLOAD_STATUS_IDX_IN_MAIL_TBL, 1);
+       _bind_stmt_field_data_string(hStmt, FILE_PATH_PLAIN_IDX_IN_MAIL_TBL, MAILHOME"/7/348/UTF-8", 0, TEXT_1_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, FILE_PATH_HTML_IDX_IN_MAIL_TBL, "", 0, TEXT_2_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int(hStmt, MAIL_SIZE_IDX_IN_MAIL_TBL, 4);
+       _bind_stmt_field_data_char(hStmt, FLAGS_SEEN_FIELD_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_char(hStmt, FLAGS_DELETED_FIELD_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_char(hStmt, FLAGS_FLAGGED_FIELD_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_char(hStmt, FLAGS_ANSWERED_FIELD_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_char(hStmt, FLAGS_RECENT_FIELD_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_char(hStmt, FLAGS_DRAFT_FIELD_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_char(hStmt, FLAGS_FORWARDED_FIELD_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, DRM_STATUS_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, PRIORITY_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, SAVE_STATUS_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, LOCK_STATUS_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, REPORT_STATUS_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, ATTACHMENT_COUNT_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, INLINE_CONTENT_COUNT_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, ATTACHMENT_COUNT_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, THREAD_ID_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, THREAD_ITEM_COUNT_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_string(hStmt, PREVIEW_TEXT_IDX_IN_MAIL_TBL, "preview body", 1, PREVIEWBODY_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_int(hStmt, MEETING_REQUEST_STATUS_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, MESSAGE_CLASS_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, DIGEST_TYPE_IDX_IN_MAIL_TBL, 0);
+       _bind_stmt_field_data_int(hStmt, SMIME_TYPE_IDX_IN_MAIL_TBL, 0);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_max_mail_count()
+{
+       return EMAIL_MAIL_MAX_COUNT;
+}
+
+#define STRIPPED_SUBJECT_BUFFER_SIZE 4086
+
+INTERNAL_FUNC int emstorage_get_thread_id_of_thread_mails(emstorage_mail_tbl_t *mail_tbl, int *thread_id, int *result_latest_mail_id_in_thread, int *thread_item_count)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_tbl [%p], thread_id [%p], result_latest_mail_id_in_thread [%p], thread_item_count [%p]", mail_tbl, thread_id, result_latest_mail_id_in_thread, thread_item_count);
+       EM_PROFILE_BEGIN(profile_emstorage_get_thread_id_of_thread_mails);
+       int      rc = 0, query_size = 0, query_size_account = 0;
+       int      account_id = 0;
+       int      err_code = EMAIL_ERROR_NONE;
+       int      count = 0, result_thread_id = -1, latest_mail_id_in_thread = -1;
+       time_t   latest_date_time = 0;
+       time_t   date_time = 0;
+       char    *mailbox_name = NULL, *subject = NULL;
+       char    *sql_query_string = NULL, *sql_account = NULL;
+       char    *sql_format = "SELECT thread_id, date_time, mail_id FROM mail_tbl WHERE subject like \'%%%q\' AND mailbox_id = %d";
+       char    *sql_format_account = " AND account_id = %d ";
+       char    *sql_format_order_by = " ORDER BY date_time DESC ";
+       char   **result = NULL;
+       char     stripped_subject[STRIPPED_SUBJECT_BUFFER_SIZE];
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EM_IF_NULL_RETURN_VALUE(mail_tbl, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(thread_id, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(result_latest_mail_id_in_thread, EMAIL_ERROR_INVALID_PARAM);
+       EM_IF_NULL_RETURN_VALUE(thread_item_count, EMAIL_ERROR_INVALID_PARAM);
+
+       account_id   = mail_tbl->account_id;
+       mailbox_name = mail_tbl->mailbox_name;
+       subject      = mail_tbl->subject;
+       date_time    = mail_tbl->date_time;
+
+       EM_DEBUG_LOG("subject : %s", subject);
+
+       if (em_find_pos_stripped_subject_for_thread_view(subject, stripped_subject, STRIPPED_SUBJECT_BUFFER_SIZE) != EMAIL_ERROR_NONE)  {
+               EM_DEBUG_EXCEPTION("em_find_pos_stripped_subject_for_thread_view  is failed");
+               err_code =  EMAIL_ERROR_UNKNOWN;
+               result_thread_id = -1;
+               goto FINISH_OFF;
+       }
+
+       if (EM_SAFE_STRLEN(stripped_subject) < 2) {
+               result_thread_id = -1;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("em_find_pos_stripped_subject_for_thread_view returns[len = %d] = %s", EM_SAFE_STRLEN(stripped_subject), stripped_subject);
+
+       if (account_id > 0)     {
+               query_size_account = 3 + EM_SAFE_STRLEN(sql_format_account);
+               sql_account = malloc(query_size_account);
+               if (sql_account == NULL) {
+                       EM_DEBUG_EXCEPTION("malloc for sql_account  is failed %d", query_size_account);
+                       err_code =  EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+               snprintf(sql_account, query_size_account, sql_format_account, account_id);
+       }
+
+       /* prevent 34362 */
+       query_size = strlen(sql_format) + strlen(stripped_subject) + 50 + query_size_account + strlen(sql_format_order_by); /*  + query_size_mailbox; */
+
+       sql_query_string = malloc(query_size);
+
+       if (sql_query_string == NULL) {
+               EM_DEBUG_EXCEPTION("malloc for sql  is failed %d", query_size);
+               err_code =  EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       sqlite3_snprintf(query_size, sql_query_string, sql_format, stripped_subject, mail_tbl->mailbox_id);
+
+       if (account_id > 0)
+               strcat(sql_query_string, sql_account);
+
+       strcat(sql_query_string, sql_format_order_by);
+       strcat(sql_query_string, ";");
+
+       EM_DEBUG_LOG("Query : %s", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, NULL, NULL), rc);
+
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err_code = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG("Result rows count : %d", count);
+
+       if (count == 0)
+               result_thread_id = -1;
+       else {
+               _get_table_field_data_int   (result, &result_thread_id, 3);
+               _get_table_field_data_time_t(result, &latest_date_time, 4);
+               _get_table_field_data_int   (result, &latest_mail_id_in_thread, 5);
+
+               if (latest_date_time < mail_tbl->date_time)
+                       *result_latest_mail_id_in_thread = latest_mail_id_in_thread;
+               else
+                       *result_latest_mail_id_in_thread = mail_tbl->mail_id;
+               EM_DEBUG_LOG("latest_mail_id_in_thread [%d], mail_id [%d]", latest_mail_id_in_thread, mail_tbl->mail_id);
+       }
+
+FINISH_OFF:
+       *thread_id = result_thread_id;
+       *thread_item_count = count;
+
+       EM_DEBUG_LOG("Result thread id : %d", *thread_id);
+       EM_DEBUG_LOG("Result count : %d", *thread_item_count);
+       EM_DEBUG_LOG("err_code : %d", err_code);
+
+       EM_SAFE_FREE(sql_account);
+       EM_SAFE_FREE(sql_query_string);
+
+       sqlite3_free_table(result);
+
+       EM_PROFILE_END(profile_emstorage_get_thread_id_of_thread_mails);
+
+       return err_code;
+}
+
+
+INTERNAL_FUNC int emstorage_get_thread_information(int thread_id, emstorage_mail_tbl_t** mail_tbl, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int count = 0, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t *p_data_tbl = NULL;
+       char conditional_clause[QUERY_SIZE] = {0, };
+
+       EM_IF_NULL_RETURN_VALUE(mail_tbl, false);
+
+       SNPRINTF(conditional_clause, QUERY_SIZE, "WHERE thread_id = %d AND thread_item_count > 0", thread_id);
+       EM_DEBUG_LOG("conditional_clause [%s]", conditional_clause);
+
+       if(!emstorage_query_mail_tbl(conditional_clause, transaction, &p_data_tbl, &count, &error)) {
+               EM_DEBUG_EXCEPTION("emstorage_query_mail_tbl failed [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       if(p_data_tbl)
+               EM_DEBUG_LOG("thread_id : %d, thread_item_count : %d", p_data_tbl[0].thread_id, p_data_tbl[0].thread_item_count);
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *mail_tbl = p_data_tbl;
+       else if (p_data_tbl != NULL)
+               emstorage_free_mail(&p_data_tbl, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_sender_list(int account_id, const char *mailbox_name, int search_type, const char *search_value, email_sort_type_t sorting, email_sender_list_t** sender_list, int *sender_count,  int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], mailbox_name [%p], search_type [%d], search_value [%p], sorting [%d], sender_list[%p], sender_count[%p] err_code[%p]"
+               , account_id , mailbox_name , search_type , search_value , sorting , sender_list, sender_count, err_code);
+
+       if ((!sender_list) ||(!sender_count)) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int count = 0;
+       int i, col_index = 0;
+       int read_count = 0;
+       email_sender_list_t *p_sender_list = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char **result = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "SELECT email_address_sender, alias_sender, COUNT(email_address_sender), SUM(flags_seen_field = 1) "
+               "FROM mail_tbl ");
+
+       /*  mailbox_name */
+       if (mailbox_name)
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), QUERY_SIZE-(EM_SAFE_STRLEN(sql_query_string)+1), " WHERE UPPER(mailbox_name) = UPPER('%s') ", mailbox_name);
+       else    /*  NULL  means all mailbox_name. but except for trash(3), spambox(5), all emails(for GMail, 7) */
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), QUERY_SIZE-(EM_SAFE_STRLEN(sql_query_string)+1), " WHERE mailbox_type not in (3, 5, 7, 8) ");
+
+       /*  account id */
+       /*  '0' (ALL_ACCOUNT) means all account */
+       if (account_id > ALL_ACCOUNT)
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), QUERY_SIZE-(EM_SAFE_STRLEN(sql_query_string)+1), " AND account_id = %d ", account_id);
+
+       if (search_value) {
+               switch (search_type) {
+                       case EMAIL_SEARCH_FILTER_SUBJECT:
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), QUERY_SIZE-(EM_SAFE_STRLEN(sql_query_string)+1),
+                                       " AND (UPPER(subject) LIKE UPPER(\'%%%%%s%%%%\')) ", search_value);
+                               break;
+                       case EMAIL_SEARCH_FILTER_SENDER:
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), QUERY_SIZE-(EM_SAFE_STRLEN(sql_query_string)+1),
+                                       " AND  ((UPPER(full_address_from) LIKE UPPER(\'%%%%%s%%%%\')) "
+                                       ") ", search_value);
+                               break;
+                       case EMAIL_SEARCH_FILTER_RECIPIENT:
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), QUERY_SIZE-(EM_SAFE_STRLEN(sql_query_string)+1),
+                                       " AND ((UPPER(full_address_to) LIKE UPPER(\'%%%%%s%%%%\')) "
+                                       "       OR (UPPER(full_address_cc) LIKE UPPER(\'%%%%%s%%%%\')) "
+                                       "       OR (UPPER(full_address_bcc) LIKE UPPER(\'%%%%%s%%%%\')) "
+                                       ") ", search_value, search_value, search_value);
+                               break;
+                       case EMAIL_SEARCH_FILTER_ALL:
+                               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), QUERY_SIZE-(EM_SAFE_STRLEN(sql_query_string)+1),
+                                       " AND (UPPER(subject) LIKE UPPER(\'%%%%%s%%%%\') "
+                                       "       OR (((UPPER(full_address_from) LIKE UPPER(\'%%%%%s%%%%\')) "
+                                       "                       OR (UPPER(full_address_to) LIKE UPPER(\'%%%%%s%%%%\')) "
+                                       "                       OR (UPPER(full_address_cc) LIKE UPPER(\'%%%%%s%%%%\')) "
+                                       "                       OR (UPPER(full_address_bcc) LIKE UPPER(\'%%%%%s%%%%\')) "
+                                       "               ) "
+                                       "       )"
+                                       ")", search_value, search_value, search_value, search_value, search_value);
+                               break;
+               }
+       }
+
+
+       /*  sorting option is not available now. The order of sender list is ascending order by display name */
+       SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1),
+               "GROUP BY email_address_sender "
+               "ORDER BY UPPER(alias_sender) ");
+
+       EM_DEBUG_LOG("query[%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG("Count of Sender [%d]", count);
+
+       if (!(p_sender_list = (email_sender_list_t*)em_malloc(sizeof(email_sender_list_t) * count))) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       col_index = 4;
+
+       EM_DEBUG_LOG(">>>> DATA ASSIGN START >>");
+       for (i = 0; i < count; i++)  {
+               _get_table_field_data_string(result, &(p_sender_list[i].address), 1, col_index++);
+               _get_table_field_data_string(result, &(p_sender_list[i].display_name), 1, col_index++);
+               _get_table_field_data_int(result, &(p_sender_list[i].total_count), col_index++);
+               _get_table_field_data_int(result, &(read_count), col_index++);
+               p_sender_list[i].unread_count = p_sender_list[i].total_count - read_count;              /*  unread count = total - read          */
+       }
+       EM_DEBUG_LOG(">>>> DATA ASSIGN END [count : %d] >>", count);
+
+       sqlite3_free_table(result);
+       result = NULL;
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)  {
+               *sender_list = p_sender_list;
+               *sender_count = count;
+               EM_DEBUG_LOG(">>>> COUNT : %d >>", count);
+       }
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_sender_list(email_sender_list_t **sender_list, int count)
+{
+       EM_DEBUG_FUNC_BEGIN("sender_list[%p], count[%d]", sender_list, count);
+
+       int err = EMAIL_ERROR_NONE;
+
+       if (count > 0)  {
+               if (!sender_list || !*sender_list)  {
+                       EM_DEBUG_EXCEPTION("sender_list[%p], count[%d]", sender_list, count);
+                       err = EMAIL_ERROR_INVALID_PARAM;
+                       return err;
+               }
+
+               email_sender_list_t* p = *sender_list;
+               int i = 0;
+
+               for (; i < count; i++)  {
+                       EM_SAFE_FREE(p[i].address);
+                       EM_SAFE_FREE(p[i].display_name);
+               }
+
+               EM_SAFE_FREE(p);
+               *sender_list = NULL;
+       }
+
+       return err;
+}
+
+
+INTERNAL_FUNC int emstorage_free_address_info_list(email_address_info_list_t **address_info_list)
+{
+       EM_DEBUG_FUNC_BEGIN("address_info_list[%p]", address_info_list);
+
+       int err = EMAIL_ERROR_NONE;
+       email_address_info_t *p_address_info = NULL;
+       GList *list = NULL;
+       GList *node = NULL;
+       int i = 0;
+
+       if (!address_info_list || !*address_info_list)  {
+               EM_DEBUG_EXCEPTION("address_info_list[%p]", address_info_list);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               return err;
+       }
+
+       /*  delete GLists */
+       for (i = EMAIL_ADDRESS_TYPE_FROM; i <= EMAIL_ADDRESS_TYPE_BCC; i++) {
+               switch (i) {
+                       case EMAIL_ADDRESS_TYPE_FROM:
+                               list = (*address_info_list)->from;
+                               break;
+                       case EMAIL_ADDRESS_TYPE_TO:
+                               list = (*address_info_list)->to;
+                               break;
+                       case EMAIL_ADDRESS_TYPE_CC:
+                               list = (*address_info_list)->cc;
+                               break;
+                       case EMAIL_ADDRESS_TYPE_BCC:
+                               list = (*address_info_list)->bcc;
+                               break;
+               }
+
+               /*  delete dynamic-allocated memory for each item */
+               node = g_list_first(list);
+               while (node != NULL) {
+                       p_address_info = (email_address_info_t*)node->data;
+                       EM_SAFE_FREE(p_address_info->address);
+                       EM_SAFE_FREE(p_address_info->display_name);
+                       EM_SAFE_FREE(node->data);
+
+                       node = g_list_next(node);
+               }
+       }
+
+       EM_SAFE_FREE(*address_info_list);
+       *address_info_list = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+INTERNAL_FUNC int emstorage_add_pbd_activity(email_event_partial_body_thd* local_activity, int *activity_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("local_activity[%p], activity_id[%p], transaction[%d], err_code[%p]", local_activity, activity_id, transaction, err_code);
+
+       if (!local_activity || !activity_id) {
+               EM_DEBUG_EXCEPTION("local_activity[%p], transaction[%d], activity_id[%p], err_code[%p]", local_activity, activity_id, transaction, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int i = 0;
+
+       char sql_query_string[QUERY_SIZE] = {0, };
+       DB_STMT hStmt = NULL;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_partial_body_activity_tbl VALUES "
+               "( "
+               "? "  /* Account ID */
+               ",?"  /* Local Mail ID */
+               ",?"  /* Server mail ID */
+               ",?"  /* Activity ID */
+               ",?"  /* Activity type*/
+               ",?"  /* Mailbox ID*/
+               ",?"  /* Mailbox name*/
+               ") ");
+
+       char *sql = "SELECT max(rowid) FROM mail_partial_body_activity_tbl;";
+       char **result = NULL;
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL==result[1]) rc = 1;
+       else rc = atoi(result[1])+1;
+       sqlite3_free_table(result);
+       result = NULL;
+
+       *activity_id = local_activity->activity_id = rc;
+
+       EM_DEBUG_LOG(">>>>> ACTIVITY ID [ %d ], MAIL ID [ %d ], ACTIVITY TYPE [ %d ], SERVER MAIL ID [ %lu ]", \
+               local_activity->activity_id, local_activity->mail_id, local_activity->activity_type, local_activity->server_mail_id);
+
+       if (local_activity->mailbox_id)
+               EM_DEBUG_LOG(" MAILBOX ID [ %d ]", local_activity->mailbox_id);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG(">>>> SQL STMT [ %s ]", sql_query_string);
+
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->account_id);
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->mail_id);
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->server_mail_id);
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->activity_id);
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->activity_type);
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->mailbox_id);
+       _bind_stmt_field_data_string(hStmt, i++ , (char *)local_activity->mailbox_name, 0, 3999);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d, errmsg = %s.", rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL) {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt = NULL;
+               if (rc != SQLITE_OK) {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+        EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+        if (err_code != NULL)
+                *err_code = error;
+
+        EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_pbd_mailbox_list(int account_id, int **mailbox_list, int *count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_list[%p], count[%p] err_code[%p]", account_id, mailbox_list, count, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || NULL == &mailbox_list || NULL == count) {
+               EM_DEBUG_EXCEPTION("account_id[%d], mailbox_list[%p], count[%p] err_code[%p]", account_id, mailbox_list, count, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char **result;
+       int i = 0, rc = -1;
+       int *mbox_list = NULL;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT count(distinct mailbox_id) FROM mail_partial_body_activity_tbl WHERE account_id = %d order by mailbox_id", account_id);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       *count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       if (!*count) {
+               EM_DEBUG_EXCEPTION(" no mailbox_name found...");
+               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+               ret = true;
+               goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG("Mailbox count = %d", *count);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       /* SNPRINTF(g_sql_query, sizeof(g_sql_query), "SELECT distinct mailbox_name FROM mail_partial_body_activity_tbl WHERE account_id = %d order by activity_id", account_id); */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT distinct mailbox_id FROM mail_partial_body_activity_tbl WHERE account_id = %d order by mailbox_id", account_id);
+
+       EM_DEBUG_LOG(" Query [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_LOG(" Bbefore sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (NULL == (mbox_list = (int *)em_malloc(sizeof(int *) * (*count)))) {
+               EM_DEBUG_EXCEPTION(" em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(mbox_list, 0x00, sizeof(int) * (*count));
+
+       for (i = 0; i < (*count); i++) {
+               _get_stmt_field_data_int(hStmt, mbox_list + i, 0);
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               /* EM_DEBUG_LOG("In emstorage_get_pdb_mailbox_list() loop, After sqlite3_step(), , i = %d, rc = %d.", i,  rc); */
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+               EM_DEBUG_LOG("mbox_list %d", mbox_list + i);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *mailbox_list = mbox_list;
+       else
+               EM_SAFE_FREE(mbox_list);
+
+       if (hStmt != NULL) {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt = NULL;
+               if (rc != SQLITE_OK) {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_pbd_account_list(int **account_list, int *count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_list[%p], count[%p] err_code[%p]", account_list, count, err_code);
+
+       if (NULL == &account_list || NULL == count) {
+               EM_DEBUG_EXCEPTION("mailbox_list[%p], count[%p] err_code[%p]", account_list, count, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char *sql;
+       char **result;
+       int i = 0, rc = -1;
+       int *result_account_list = NULL;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+
+       sql = "SELECT count(distinct account_id) FROM mail_partial_body_activity_tbl";
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       *count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       if (!*count) {
+               EM_DEBUG_EXCEPTION("no account found...");
+               error = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+               ret = true;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("Account count [%d]", *count);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT distinct account_id FROM mail_partial_body_activity_tbl");
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_LOG("Before sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (NULL == (result_account_list = (int *)em_malloc(sizeof(int) * (*count)))) {
+               EM_DEBUG_EXCEPTION(" em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(result_account_list, 0x00, sizeof(int) * (*count));
+
+       for (i = 0; i < (*count); i++) {
+               _get_stmt_field_data_int(hStmt, result_account_list + i, 0);
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+               EM_DEBUG_LOG("account id -> %d", result_account_list[i]);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *account_list = result_account_list;
+       else
+               EM_SAFE_FREE(result_account_list);
+
+       if (hStmt != NULL) {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt = NULL;
+               if (rc != SQLITE_OK) {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+       if (err_code != NULL)
+               *err_code = error;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+
+INTERNAL_FUNC int emstorage_get_pbd_activity_data(int account_id, int input_mailbox_id, email_event_partial_body_thd** event_start, int *count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], event_start[%p], err_code[%p]", account_id, event_start, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || NULL == event_start || 0 == input_mailbox_id || NULL == count) {
+               EM_DEBUG_EXCEPTION("account_id[%d], email_event_partial_body_thd[%p], input_mailbox_id[%d], count[%p], err_code[%p]", account_id, event_start, input_mailbox_id, count, err_code);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1;
+       int ret = false;
+       char **result;
+       int error = EMAIL_ERROR_NONE;
+       int i = 0;
+       DB_STMT hStmt = NULL;
+       email_event_partial_body_thd* event_list = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT count(*) FROM mail_partial_body_activity_tbl WHERE account_id = %d AND mailbox_id = '%d' order by activity_id", account_id, input_mailbox_id);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       *count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       EM_DEBUG_LOG("Query = [%s]", sql_query_string);
+
+       if (!*count) {
+               EM_DEBUG_EXCEPTION("No matched activity found in mail_partial_body_activity_tbl");
+
+               error = EMAIL_ERROR_MAIL_NOT_FOUND;
+               ret = true;
+               goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG("Activity Count = %d", *count);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_partial_body_activity_tbl WHERE account_id = %d AND mailbox_id = '%d' order by activity_id", account_id, input_mailbox_id);
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_LOG(" Bbefore sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (!(event_list = (email_event_partial_body_thd*)em_malloc(sizeof(email_event_partial_body_thd) * (*count)))) {
+               EM_DEBUG_EXCEPTION("Malloc failed");
+
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       memset(event_list, 0x00, sizeof(email_event_partial_body_thd) * (*count));
+
+       for (i=0; i < (*count); i++) {
+               _get_stmt_field_data_int(hStmt, &(event_list[i].account_id), ACCOUNT_IDX_MAIL_PARTIAL_BODY_ACTIVITY_TBL);
+               _get_stmt_field_data_int(hStmt, &(event_list[i].mail_id), MAIL_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL);
+               _get_stmt_field_data_int(hStmt, (int *)&(event_list[i].server_mail_id), SERVER_MAIL_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL);
+               _get_stmt_field_data_int(hStmt, &(event_list[i].activity_id), ACTIVITY_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL);
+               _get_stmt_field_data_int(hStmt, &(event_list[i].activity_type), ACTIVITY_TYPE_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL);
+               _get_stmt_field_data_int(hStmt, &(event_list[i].mailbox_id), MAILBOX_ID_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL);
+               _get_stmt_field_data_string(hStmt, &(event_list[i].mailbox_name), 0, MAILBOX_NAME_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL);
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               /* EM_DEBUG_LOG("In emstorage_get_pbd_activity_data() loop, After sqlite3_step(), , i = %d, rc = %d.", i,  rc); */
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+
+               event_list[i].event_type = 0;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (true == ret)
+         *event_start = event_list;
+       else {
+               EM_SAFE_FREE(event_list);
+       }
+
+       if (hStmt != NULL) {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt = NULL;
+               if (rc != SQLITE_OK) {
+                       EM_DEBUG_LOG("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+
+INTERNAL_FUNC int emstorage_delete_pbd_activity(int account_id, int mail_id, int activity_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d] , activity_id[%d], transaction[%d], err_code[%p]", account_id, mail_id, activity_id, transaction, err_code);
+
+
+       if (account_id < FIRST_ACCOUNT_ID || activity_id < 0 || mail_id <= 0) {
+               EM_DEBUG_EXCEPTION("account_id[%d], mail_id[%d], activity_id[%d], transaction[%d], err_code[%p]", account_id, mail_id, activity_id, transaction, err_code);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       if (activity_id == 0)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_partial_body_activity_tbl WHERE account_id = %d AND mail_id = %d", account_id, mail_id);
+       else
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_partial_body_activity_tbl WHERE account_id = %d AND activity_id = %d", account_id, activity_id);
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       /*  validate activity existence */
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION("No matching activity found");
+               error = EMAIL_ERROR_DATA_NOT_FOUND;
+               ret = true;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+
+       _DISCONNECT_DB;
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_mailbox_pbd_activity_count(int account_id, int input_mailbox_id, int *activity_count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], activity_count[%p], err_code[%p]", account_id, activity_count, err_code);
+
+       if (account_id < FIRST_ACCOUNT_ID || NULL == activity_count || NULL == err_code) {
+               EM_DEBUG_EXCEPTION("account_id[%d], activity_count[%p], err_code[%p]", account_id, activity_count, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       DB_STMT hStmt = NULL;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT count(*) FROM mail_partial_body_activity_tbl WHERE account_id = %d and mailbox_id = '%d'", account_id, input_mailbox_id);
+
+       EM_DEBUG_LOG(" Query [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("before sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       _get_stmt_field_data_int(hStmt, activity_count, 0);
+
+       EM_DEBUG_LOG("No. of activities in activity table [%d]", *activity_count);
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL) {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+               rc = sqlite3_finalize(hStmt);
+               hStmt=NULL;
+               if (rc != SQLITE_OK) {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+               EM_DEBUG_LOG("sqlite3_finalize- %d", rc);
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_pbd_activity_count(int *activity_count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("activity_count[%p], err_code[%p]", activity_count, err_code);
+
+       if (NULL == activity_count || NULL == err_code) {
+               EM_DEBUG_EXCEPTION("activity_count[%p], err_code[%p]", activity_count, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT count(*) FROM mail_partial_body_activity_tbl;");
+
+       EM_DEBUG_LOG(" Query [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("  before sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       _get_stmt_field_data_int(hStmt, activity_count, 0);
+
+       EM_DEBUG_LOG("No. of activities in activity table [%d]", *activity_count);
+
+       ret = true;
+
+FINISH_OFF:
+
+
+       if (hStmt != NULL) {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt=NULL;
+               if (rc != SQLITE_OK) {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+               EM_DEBUG_LOG("sqlite3_finalize- %d", rc);
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_full_pbd_activity_data(int account_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], transaction[%d], err_code[%p]", account_id, transaction, err_code);
+       if (account_id < FIRST_ACCOUNT_ID) {
+               EM_DEBUG_EXCEPTION("account_id[%d], transaction[%d], err_code[%p]", account_id, transaction, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_partial_body_activity_tbl WHERE account_id = %d", account_id);
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0) {
+               EM_DEBUG_EXCEPTION("No matching activities found in mail_partial_body_activity_tbl");
+               error = EMAIL_ERROR_DATA_NOT_FOUND;
+               ret = true;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/*Himanshu[h.gahlaut]-> Added below API to update mail_partial_body_activity_tbl
+if a mail is moved before its partial body is downloaded.Currently not used but should be used if mail move from server is enabled*/
+
+INTERNAL_FUNC int emstorage_update_pbd_activity(char *old_server_uid, char *new_server_uid, char *mbox_name, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("old_server_uid[%s], new_server_uid[%s], mbox_name[%s]", old_server_uid, new_server_uid, mbox_name);
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int transaction = true;
+
+       if (!old_server_uid || !new_server_uid || !mbox_name)  {
+               EM_DEBUG_EXCEPTION("Invalid parameters");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                "UPDATE mail_partial_body_activity_tbl SET server_mail_id = %s , mailbox_name=\'%s\' WHERE server_mail_id = %s ", new_server_uid, mbox_name, old_server_uid);
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0) {
+               EM_DEBUG_EXCEPTION("No matching found in mail_partial_body_activity_tbl");
+               error = EMAIL_ERROR_DATA_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_create_file(char *data_string, size_t file_size, char *dst_file_name, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("file_size[%d] , dst_file_name[%s], err_code[%p]", file_size, dst_file_name, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       FILE* fp_dst = NULL;
+
+       if (!data_string || !dst_file_name)  {
+               EM_DEBUG_EXCEPTION("data_string[%p], dst_file_name[%p]", data_string, dst_file_name);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       fp_dst = fopen(dst_file_name, "w");
+
+       if (!fp_dst)  {
+               EM_DEBUG_EXCEPTION("fopen failed - %s", dst_file_name);
+               if (errno == 28)
+                       error = EMAIL_ERROR_MAIL_MEMORY_FULL;
+               else
+                       error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       if (fwrite(data_string, 1, file_size, fp_dst) == 0) {
+               EM_DEBUG_EXCEPTION("fwrite failed...");
+               error = EMAIL_ERROR_UNKNOWN;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (fp_dst != NULL)
+               fclose(fp_dst);
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+#endif /*  __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
+
+
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+
+INTERNAL_FUNC int emstorage_update_read_mail_uid_by_server_uid(char *old_server_uid, char *new_server_uid, char *mbox_name, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       int transaction = true;
+
+       if (!old_server_uid || !new_server_uid || !mbox_name)  {
+               EM_DEBUG_EXCEPTION("Invalid parameters");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       EM_DEBUG_LOG("old_server_uid[%s], new_server_uid[%s], mbox_name[%s]", old_server_uid, new_server_uid, mbox_name);
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+                "UPDATE mail_read_mail_uid_tbl SET s_uid=\'%s\' , mailbox_id=\'%s\', mailbox_name=\'%s\' WHERE s_uid=%s ", new_server_uid, mbox_name, mbox_name, old_server_uid);
+
+        EM_DEBUG_LOG(" Query [%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+        EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+                ("sqlite3_exec fail:%d", rc));
+        EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+        rc = sqlite3_changes(local_db_handle);
+        if (rc == 0)
+        {
+                EM_DEBUG_EXCEPTION("No matching found in mail_partial_body_activity_tbl");
+                error = EMAIL_ERROR_DATA_NOT_FOUND;
+                goto FINISH_OFF;
+        }
+
+
+        ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+
+
+/**
+ * @fn emstorage_get_id_set_from_mail_ids(int mail_ids[], int mail_id_count, email_id_set_t** server_uids, int *id_set_count, int *err_code);
+ * Prepare an array of mail_id and corresponding server mail id.
+ *
+ *@author                                      h.gahlaut@samsung.com
+ * @param[in] mail_ids                 Specifies the comma separated string of mail_ids. Maximaum size of string should be less than or equal to (QUERY_SIZE - 88)
+ *                                                     where 88 is the length of fixed keywords including ending null character in the QUERY to be formed
+ * @param[out] idset                   Returns the array of mail_id and corresponding server_mail_id sorted by server_mail_ids
+ * @param[out] id_set_count            Returns the no. of cells in idset array i.e. no. of sets of mail_ids and server_mail_ids
+ * @param[out] err_code                Returns the error code.
+ * @remarks                                    An Example of Query to be exexuted in this API:
+ *                                                     SELECT local_uid, s_uid from mail_read_mail_uid_tbl where local_uid in (12, 13, 56, 78);
+ * @return This function returns true on success or false on failure.
+ */
+
+INTERNAL_FUNC int emstorage_get_id_set_from_mail_ids(char *mail_ids, email_id_set_t** idset, int *id_set_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_PROFILE_BEGIN(EmStorageGetIdSetFromMailIds);
+
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+       email_id_set_t* p_id_set = NULL;
+       int count = 0;
+       const int buf_size = QUERY_SIZE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       int space_left_in_query_buffer = buf_size;
+       int i = 0;
+       int rc = -1;
+       char *server_mail_id = NULL;
+       char **result = NULL;
+       int col_index = 0;
+
+
+       if (NULL == mail_ids || NULL == idset || NULL == id_set_count) {
+               EM_DEBUG_EXCEPTION("Invalid Parameters mail_ids[%p] idset[%p]  id_set_count [%p]", mail_ids, idset, id_set_count);
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       SNPRINTF(sql_query_string, space_left_in_query_buffer, "SELECT local_uid, s_uid FROM mail_read_mail_uid_tbl WHERE local_uid in (%s) ORDER BY s_uid", mail_ids);
+
+       EM_DEBUG_LOG("SQL Query formed [%s] ", sql_query_string);
+
+       /*  rc = sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG(" Count of mails [%d ]", count);
+
+       if (count <= 0) {
+               EM_DEBUG_EXCEPTION("Can't find proper mail");
+               error = EMAIL_ERROR_DATA_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+
+       if (NULL == (p_id_set = (email_id_set_t*)em_malloc(sizeof(email_id_set_t) * count)))  {
+               EM_DEBUG_EXCEPTION(" em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       col_index = 2;
+
+       EM_PROFILE_BEGIN(EmStorageGetIdSetFromMailIds_Loop);
+       EM_DEBUG_LOG(">>>> DATA ASSIGN START");
+       for (i = 0; i < count; i++)  {
+               _get_table_field_data_int(result, &(p_id_set[i].mail_id), col_index++);
+               _get_table_field_data_string(result, &server_mail_id, 1, col_index++);
+               p_id_set[i].server_mail_id = strtoul(server_mail_id, NULL, 10);
+               EM_SAFE_FREE(server_mail_id);
+       }
+       EM_DEBUG_LOG(">>>> DATA ASSIGN END [count : %d]", count);
+       EM_PROFILE_END(EmStorageGetIdSetFromMailIds_Loop);
+
+       sqlite3_free_table(result);
+       result = NULL;
+
+       ret = true;
+
+       FINISH_OFF:
+
+       if (ret == true)  {
+               *idset = p_id_set;
+               *id_set_count = count;
+               EM_DEBUG_LOG(" idset[%p] id_set_count [%d]", *idset, *id_set_count);
+       }
+       else
+               EM_SAFE_FREE(p_id_set);
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(EmStorageGetIdSetFromMailIds);
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+
+#endif
+
+INTERNAL_FUNC int emstorage_delete_triggers_from_lucene()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int rc, ret = true, transaction = true;
+       int error = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DROP TRIGGER triggerDelete;");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DROP TRIGGER triggerInsert;");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DROP TRIGGER triggerUpdate;");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbox_id, emstorage_rule_tbl_t *rule, int ** filtered_mail_id_list, int *count_of_mails, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], dest_mailbox_id[%d] rule[%p], filtered_mail_id_list[%p], count_of_mails[%p], err_code[%p]", account_id, dest_mailbox_id, rule, filtered_mail_id_list, count_of_mails, err_code);
+
+       if ((account_id <= 0) || (dest_mailbox_id <= 0) || (!rule) || (!rule->value)|| (!filtered_mail_id_list) || (!count_of_mails)) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false, error = EMAIL_ERROR_NONE;
+       int count = 0, col_index = 0, i = 0, where_pararaph_length = 0, *mail_list = NULL;
+       char **result = NULL, *where_pararaph = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mail_id FROM mail_tbl ");
+
+       EM_DEBUG_LOG("rule->value [%s]", rule->value);
+
+       where_pararaph_length = EM_SAFE_STRLEN(rule->value) + 100;
+       where_pararaph = malloc(sizeof(char) * where_pararaph_length);
+
+       if (where_pararaph == NULL) {
+               EM_DEBUG_EXCEPTION("malloc failed for where_pararaph.");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(where_pararaph, 0, sizeof(char) * where_pararaph_length);
+
+       EM_DEBUG_LOG("rule->type [%d], rule->flag2[%d]", rule->type, rule->flag2);
+
+       if (rule->type == EMAIL_FILTER_FROM) {
+               if (rule->flag2 == RULE_TYPE_INCLUDES)
+                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5) AND full_address_from like \'%%%s%%\'", account_id, rule->value);
+               else /*  RULE_TYPE_EXACTLY */
+                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5) AND full_address_from = \'%s\'", account_id, rule->value);
+       }
+       else if (rule->type == EMAIL_FILTER_SUBJECT) {
+               if (rule->flag2 == RULE_TYPE_INCLUDES)
+                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5) AND subject like \'%%%s%%\'", account_id, rule->value);
+               else /*  RULE_TYPE_EXACTLY */
+                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d AND mailbox_type NOT in (3,5) AND subject = \'%s\'", account_id, rule->value);
+       }
+       else {
+               error = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("rule->type is invald");
+               goto FINISH_OFF;
+       }
+
+       /* prevent 34361 */
+       if (strlen(sql_query_string) + strlen(where_pararaph) < QUERY_SIZE)
+               strcat(sql_query_string, where_pararaph);
+
+       EM_DEBUG_LOG("query[%s]", sql_query_string);
+
+       /*  rc = sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG("Count of mails [%d]", count);
+
+       if (count) {
+               mail_list = malloc(sizeof(int) * count);
+               if (mail_list == NULL) {
+                       EM_DEBUG_EXCEPTION("malloc failed for mail_list.");
+                       error = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               col_index = 1;
+
+               for (i = 0; i < count; i++)
+                       _get_table_field_data_int(result, &(mail_list[i]), col_index++);
+
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET mailbox_id = %d, mailbox_type = 5 ", dest_mailbox_id);
+
+               /* prevent 34361 */
+               if(strlen(sql_query_string) + strlen(where_pararaph) < QUERY_SIZE)
+               strcat(sql_query_string, where_pararaph);
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ret)
+               *filtered_mail_id_list = mail_list;
+       else
+               EM_SAFE_FREE(mail_list);
+
+       sqlite3_free_table(result);
+       result = NULL;
+
+       _DISCONNECT_DB;
+
+       EM_SAFE_FREE(where_pararaph);
+
+       if (ret && count_of_mails)
+               *count_of_mails = count;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+#define EMAIL_SLOT_UNIT 25
+
+INTERNAL_FUNC int emstorage_set_mail_slot_size(int account_id, int mailbox_id, int new_slot_size, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_id[%p] new_slot_size[%d], err_code[%p]", account_id, mailbox_id, new_slot_size, err_code);
+       int rc = -1, ret = false, err = EMAIL_ERROR_NONE;
+       int where_pararaph_length = 0;
+       char *where_pararaph = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       int and = 0;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, err);
+
+       if (new_slot_size > 0)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_box_tbl SET mail_slot_size = %d ", new_slot_size);
+       else if (new_slot_size == 0)
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_box_tbl SET mail_slot_size = mail_slot_size + %d ", EMAIL_SLOT_UNIT);
+       else
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_box_tbl SET mail_slot_size = mail_slot_size + %d ", new_slot_size * -1);
+
+
+       if (mailbox_id)
+               where_pararaph_length = 80;
+       else
+               where_pararaph_length = 50;
+
+       if (new_slot_size == 0)
+               where_pararaph_length += 70;
+
+       where_pararaph = malloc(sizeof(char) * where_pararaph_length);
+       if (where_pararaph == NULL) {
+               EM_DEBUG_EXCEPTION("Memory allocation failed for where_pararaph");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       memset(where_pararaph, 0x00, where_pararaph_length);
+
+       if (account_id > ALL_ACCOUNT) {
+               and = 1;
+               if (mailbox_id)
+                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE mailbox_id = %d ", mailbox_id);
+               else
+                       SNPRINTF(where_pararaph, where_pararaph_length, "WHERE account_id = %d ", account_id);
+       }
+
+       if (new_slot_size == 0)
+               SNPRINTF(where_pararaph + EM_SAFE_STRLEN(where_pararaph), where_pararaph_length - EM_SAFE_STRLEN(where_pararaph), " %s total_mail_count_on_server > mail_slot_size ", (and ? "AND" : "WHERE"));
+
+       if (strlen(sql_query_string) + EM_SAFE_STRLEN(where_pararaph) < QUERY_SIZE) /* prevent 34363 */
+               strcat(sql_query_string, where_pararaph);
+       else {
+               EM_DEBUG_EXCEPTION("Query buffer overflowed !!!");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("query[%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, err);
+
+       _DISCONNECT_DB;
+
+       EM_SAFE_FREE(where_pararaph);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_add_meeting_request(int account_id, int input_mailbox_id, email_meeting_request_t* meeting_req, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], input_mailbox_id[%d], meeting_req[%p], transaction[%d], err_code[%p]", account_id, input_mailbox_id, meeting_req, transaction, err_code);
+
+       if (!meeting_req || meeting_req->mail_id <= 0) {
+               if (meeting_req)
+               EM_DEBUG_EXCEPTION("mail_id[%]d", meeting_req->mail_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+
+               return false;
+       }
+
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       int col_index = 0;
+       time_t temp_unix_time = 0;
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_meeting_tbl VALUES "
+               "( ?"           /*  mail_id */
+               ", ?"           /*  account_id */
+               ", ?"           /*  mailbox_id */
+               ", ?"           /*  meeting_response */
+               ", ?"           /*  start_time */
+               ", ?"           /*  end_time */
+               ", ?"           /*  location */
+               ", ?"           /*  global_object_id */
+               ", ?"           /*  offset */
+               ", ?"           /*  standard_name */
+               ", ?"           /*  standard_time_start_date */
+               ", ?"           /*  standard_biad */
+               ", ?"           /*  daylight_name */
+               ", ?"           /*  daylight_time_start_date */
+               ", ?"           /*  daylight_bias */
+               " )");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       if (rc != SQLITE_OK)  {
+               EM_DEBUG_LOG(" before sqlite3_prepare hStmt = %p", hStmt);
+               EM_DEBUG_EXCEPTION("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle));
+
+               error = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       col_index = 0;
+       /*
+       EM_DEBUG_LOG(">>>>> meeting_req->mail_id[%d]", meeting_req->mail_id);
+       EM_DEBUG_LOG(">>>>> account_id[%d]", account_id);
+       EM_DEBUG_LOG(">>>>> mailbox_name[%s]", mailbox_name);
+       EM_DEBUG_LOG(">>>>> meeting_req->meeting_response[%d]", meeting_req->meeting_response);
+       EM_DEBUG_LOG(">>>>> meeting_req->start_time[%s]", asctime(&(meeting_req->start_time)));
+       EM_DEBUG_LOG(">>>>> meeting_req->end_time[%s]", asctime(&(meeting_req->end_time)));
+       EM_DEBUG_LOG(">>>>> meeting_req->location[%s]", meeting_req->location);
+       EM_DEBUG_LOG(">>>>> meeting_req->global_object_id[%s]", meeting_req->global_object_id);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.offset_from_GMT[%d]", meeting_req->time_zone.offset_from_GMT);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_name[%s]", meeting_req->time_zone.standard_name);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_time_start_date[%s]", asctime(&(meeting_req->time_zone.standard_time_start_date)));
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_bias[%d]", meeting_req->time_zone.standard_bias);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_name[%s]", meeting_req->time_zone.daylight_name);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_time_start_date[%s]", asctime(&(meeting_req->time_zone.daylight_time_start_date)));
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_bias[%d]", meeting_req->time_zone.daylight_bias);
+       */
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->mail_id);
+       _bind_stmt_field_data_int(hStmt, col_index++, account_id);
+       _bind_stmt_field_data_int(hStmt, col_index++, input_mailbox_id);
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->meeting_response);
+
+       temp_unix_time = timegm(&(meeting_req->start_time));
+       _bind_stmt_field_data_int(hStmt, col_index++, temp_unix_time);
+       temp_unix_time = timegm(&(meeting_req->end_time));
+       _bind_stmt_field_data_int(hStmt, col_index++, temp_unix_time);
+
+       _bind_stmt_field_data_string(hStmt, col_index++, (char *)meeting_req->location, 0, LOCATION_LEN_IN_MAIL_MEETING_TBL);
+       _bind_stmt_field_data_string(hStmt, col_index++, (char *)meeting_req->global_object_id, 0, GLOBAL_OBJECT_ID_LEN_IN_MAIL_MEETING_TBL);
+
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->time_zone.offset_from_GMT);
+       _bind_stmt_field_data_string(hStmt, col_index++, (char *)meeting_req->time_zone.standard_name, 0, STANDARD_NAME_LEN_IN_MAIL_MEETING_TBL);
+       temp_unix_time = timegm(&(meeting_req->time_zone.standard_time_start_date));
+       _bind_stmt_field_data_int(hStmt, col_index++, temp_unix_time);
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->time_zone.standard_bias);
+
+       _bind_stmt_field_data_string(hStmt, col_index++, (char *)meeting_req->time_zone.daylight_name, 0, DAYLIGHT_NAME_LEN_IN_MAIL_MEETING_TBL);
+       temp_unix_time = timegm(&(meeting_req->time_zone.daylight_time_start_date));
+       _bind_stmt_field_data_int(hStmt, col_index++, temp_unix_time);
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->time_zone.daylight_bias);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       ret = true;
+
+FINISH_OFF:
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_meeting_request(int mail_id, email_meeting_request_t ** meeting_req, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int count = 0;
+       int rc = -1;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       email_meeting_request_t *p_temp_meeting_req = NULL;
+       int col_index = 0;
+       time_t temp_unix_time;
+
+       EM_IF_NULL_RETURN_VALUE(meeting_req, false);
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "SELECT  mail_id, meeting_response, start_time, end_time, location, global_object_id, offset, standard_name, standard_time_start_date, standard_bias, daylight_name, daylight_time_start_date, daylight_bias "
+               " FROM mail_meeting_tbl "
+               " WHERE mail_id = %d", mail_id);
+       EM_DEBUG_LOG("sql : %s ", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION(" no Meeting request found...");
+               count = 0;
+               ret = false;
+               error= EMAIL_ERROR_DATA_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (!(p_temp_meeting_req = (email_meeting_request_t*)malloc(sizeof(email_meeting_request_t)))) {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(p_temp_meeting_req, 0x00, sizeof(email_meeting_request_t));
+
+       col_index = 0;
+
+       _get_stmt_field_data_int(hStmt, &(p_temp_meeting_req->mail_id), col_index++);
+       _get_stmt_field_data_int(hStmt, (int *)&(p_temp_meeting_req->meeting_response), col_index++);
+       _get_stmt_field_data_int(hStmt, (int *)(&temp_unix_time), col_index++);
+       gmtime_r(&temp_unix_time, &(p_temp_meeting_req->start_time));
+       _get_stmt_field_data_int(hStmt, (int *)(&temp_unix_time), col_index++);
+       gmtime_r(&temp_unix_time, &(p_temp_meeting_req->end_time));
+       _get_stmt_field_data_string(hStmt, &p_temp_meeting_req->location, 1, col_index++);
+       _get_stmt_field_data_string(hStmt, &p_temp_meeting_req->global_object_id, 1, col_index++);
+       _get_stmt_field_data_int(hStmt, &(p_temp_meeting_req->time_zone.offset_from_GMT), col_index++);
+
+       _get_stmt_field_data_string_without_allocation(hStmt, p_temp_meeting_req->time_zone.standard_name, STANDARD_NAME_LEN_IN_MAIL_MEETING_TBL, 1, col_index++);
+       _get_stmt_field_data_int(hStmt, (int *)(&temp_unix_time), col_index++);
+       gmtime_r(&temp_unix_time, &(p_temp_meeting_req->time_zone.standard_time_start_date));
+       _get_stmt_field_data_int(hStmt, &(p_temp_meeting_req->time_zone.standard_bias), col_index++);
+
+       _get_stmt_field_data_string_without_allocation(hStmt, p_temp_meeting_req->time_zone.daylight_name, DAYLIGHT_NAME_LEN_IN_MAIL_MEETING_TBL, 1, col_index++);
+       _get_stmt_field_data_int(hStmt, (int *)(&temp_unix_time), col_index++);
+       gmtime_r(&temp_unix_time, &(p_temp_meeting_req->time_zone.daylight_time_start_date));
+       _get_stmt_field_data_int(hStmt, &(p_temp_meeting_req->time_zone.daylight_bias), col_index++);
+
+       /*
+       EM_DEBUG_LOG(">>>>> meeting_req->mail_id[%d]", p_temp_meeting_req->mail_id);
+       EM_DEBUG_LOG(">>>>> meeting_req->meeting_response[%d]", p_temp_meeting_req->meeting_response);
+       EM_DEBUG_LOG(">>>>> meeting_req->start_time[%s]", asctime(&(p_temp_meeting_req->start_time)));
+       EM_DEBUG_LOG(">>>>> meeting_req->end_time[%s]", asctime(&(p_temp_meeting_req->end_time)));
+       EM_DEBUG_LOG(">>>>> meeting_req->location[%s]", p_temp_meeting_req->location);
+       EM_DEBUG_LOG(">>>>> meeting_req->global_object_id[%s]", p_temp_meeting_req->global_object_id);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.offset_from_GMT[%d]", p_temp_meeting_req->time_zone.offset_from_GMT);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_name[%s]", p_temp_meeting_req->time_zone.standard_name);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_time_start_date[%s]", asctime(&(p_temp_meeting_req->time_zone.standard_time_start_date)));
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_bias[%d]", p_temp_meeting_req->time_zone.standard_bias);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_name[%s]", p_temp_meeting_req->time_zone.daylight_name);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_time_start_date[%s]", asctime(&(p_temp_meeting_req->time_zone.daylight_time_start_date)));
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_bias[%d]", p_temp_meeting_req->time_zone.daylight_bias);
+       */
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *meeting_req = p_temp_meeting_req;
+       else  {
+               EM_SAFE_FREE(p_temp_meeting_req);
+       }
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt = NULL;
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_update_meeting_request(email_meeting_request_t* meeting_req, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("meeting_req[%p], transaction[%d], err_code[%p]", meeting_req, transaction, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int rc;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       time_t temp_unix_time = 0;
+
+       if (!meeting_req) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter!");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_meeting_tbl "
+               "SET "
+               /* "  account_id = ?, "         //  not update here, this can be changed when move or copy */
+               /* "  mailbox_name = ?, "               //  not update here, this can be changed when move or copy */
+               "  meeting_response = ?, "
+               "  start_time = ?, "
+               "  end_time = ?, "
+               "  location = ?, "
+               "  global_object_id = ?, "
+               "  offset = ?, "
+               "  standard_name = ?, "
+               "  standard_time_start_date = ?, "
+               "  standard_bias = ?, "
+               "  daylight_name = ?, "
+               "  daylight_time_start_date = ?, "
+               "  daylight_bias = ? "
+               "WHERE mail_id = %d",
+               meeting_req->mail_id);
+
+       EM_DEBUG_LOG("SQL(%s)", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+/*
+       EM_DEBUG_LOG(">>>>> meeting_req->mail_id[%d]", meeting_req->mail_id);
+       EM_DEBUG_LOG(">>>>> meeting_req->meeting_response[%d]", meeting_req->meeting_response);
+       EM_DEBUG_LOG(">>>>> meeting_req->start_time[%s]", asctime(&(meeting_req->start_time)));
+       EM_DEBUG_LOG(">>>>> meeting_req->end_time[%s]", asctime(&(meeting_req->end_time)));
+       EM_DEBUG_LOG(">>>>> meeting_req->location[%s]", meeting_req->location);
+       EM_DEBUG_LOG(">>>>> meeting_req->global_object_id[%s]", meeting_req->global_object_id);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.offset_from_GMT[%d]", meeting_req->time_zone.offset_from_GMT);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_name[%s]", meeting_req->time_zone.standard_name);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_time_start_date[%s]", asctime(&(meeting_req->time_zone.standard_time_start_date)));
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.standard_bias[%d]", meeting_req->time_zone.standard_bias);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_name[%s]", meeting_req->time_zone.daylight_name);
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_time_start_date[%s]", asctime(&(meeting_req->time_zone.daylight_time_start_date)));
+       EM_DEBUG_LOG(">>>>> meeting_req->time_zone.daylight_bias[%d]", meeting_req->time_zone.daylight_bias);
+*/
+       int col_index = 0;
+
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->meeting_response);
+       temp_unix_time = timegm(&(meeting_req->start_time));
+       _bind_stmt_field_data_int(hStmt, col_index++, temp_unix_time);
+       temp_unix_time = timegm(&(meeting_req->end_time));
+       _bind_stmt_field_data_int(hStmt, col_index++, temp_unix_time);
+       _bind_stmt_field_data_string(hStmt, col_index++, meeting_req->location, 1, LOCATION_LEN_IN_MAIL_MEETING_TBL);
+       _bind_stmt_field_data_string(hStmt, col_index++, meeting_req->global_object_id, 1, GLOBAL_OBJECT_ID_LEN_IN_MAIL_MEETING_TBL);
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->time_zone.offset_from_GMT);
+       _bind_stmt_field_data_string(hStmt, col_index++, meeting_req->time_zone.standard_name, 1, STANDARD_NAME_LEN_IN_MAIL_MEETING_TBL);
+       temp_unix_time = timegm(&(meeting_req->time_zone.standard_time_start_date));
+       _bind_stmt_field_data_int(hStmt, col_index++, temp_unix_time);
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->time_zone.standard_bias);
+       _bind_stmt_field_data_string(hStmt, col_index++, meeting_req->time_zone.daylight_name, 1, DAYLIGHT_NAME_LEN_IN_MAIL_MEETING_TBL);
+       temp_unix_time = timegm(&(meeting_req->time_zone.daylight_time_start_date));
+       _bind_stmt_field_data_int(hStmt, col_index++, temp_unix_time);
+       _bind_stmt_field_data_int(hStmt, col_index++, meeting_req->time_zone.daylight_bias);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       ret = true;
+
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION(" sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_meeting_request(int account_id, int mail_id, int input_mailbox_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], input_mailbox_id[%d], transaction[%d], err_code[%p]", account_id, mail_id, input_mailbox_id, transaction, err_code);
+
+       if (account_id < ALL_ACCOUNT || mail_id < 0) {
+               EM_DEBUG_EXCEPTION(" account_id[%d], mail_id[%d]", account_id, mail_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc;
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int and = false;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_meeting_tbl ");
+
+       if (account_id != ALL_ACCOUNT) {                /*  NOT '0' means a specific account. '0' means all account */
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " WHERE account_id = %d", account_id);
+               and = true;
+       }
+       if (mail_id > 0) {
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " %s mail_id = %d", (and ? "AND" : "WHERE"), mail_id);
+               and = true;
+       }
+       if (input_mailbox_id > 0) {             /*  0 means all mailbox_id */
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1), " %s mailbox_id = '%d'",  (and ? "AND" : "WHERE"), input_mailbox_id);
+       }
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC void emstorage_free_meeting_request(email_meeting_request_t *meeting_req)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!meeting_req ) {
+               EM_DEBUG_EXCEPTION("NULL PARAM");
+               return;
+               }
+
+       EM_SAFE_FREE(meeting_req->location);
+       EM_SAFE_FREE(meeting_req->global_object_id);
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+INTERNAL_FUNC int emstorage_get_overflowed_mail_id_list(int account_id, int input_mailbox_id, int mail_slot_size, int **mail_id_list, int *mail_id_count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], input_mailbox_id [%d], mail_slot_size [%d], mail_id_list [%p], mail_id_count [%p], transaction [%d], err_code [%p]", account_id, input_mailbox_id, mail_slot_size, mail_id_list, mail_id_count, transaction, err_code);
+       EM_PROFILE_BEGIN(profile_emstorage_get_overflowed_mail_id_list);
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char **result = NULL;
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int counter = 0, col_index = 0;
+       int result_mail_id_count = 0;
+       int *result_mail_id_list = NULL;
+
+       if (input_mailbox_id <= 0 || !mail_id_list || !mail_id_count || account_id < 1) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mail_id FROM mail_tbl WHERE account_id = %d AND mailbox_id = %d ORDER BY date_time DESC LIMIT %d, 10000", account_id, input_mailbox_id, mail_slot_size);
+
+       EM_DEBUG_LOG("query[%s].", sql_query_string);
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &result_mail_id_count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (!result_mail_id_count) {
+               EM_DEBUG_LOG("No mail found...");
+               ret = false;
+               error= EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("There are [%d] overflowed mails in mailbox_id [%d]", result_mail_id_count, input_mailbox_id);
+
+       if (!(result_mail_id_list = (int *)malloc(sizeof(int) * result_mail_id_count))) {
+               EM_DEBUG_EXCEPTION("malloc for result_mail_id_list failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               sqlite3_free_table(result);
+               goto FINISH_OFF;
+       }
+
+       memset(result_mail_id_list, 0x00, sizeof(int) * result_mail_id_count);
+
+       col_index = 1;
+
+       for (counter = 0; counter < result_mail_id_count; counter++)
+               _get_table_field_data_int(result, result_mail_id_list + counter, col_index++);
+
+       ret = true;
+
+FINISH_OFF:
+       EM_DEBUG_LOG("finish off [%d]", ret);
+
+       if (result)
+               sqlite3_free_table(result);
+
+       if (ret == true)  {
+               *mail_id_list = result_mail_id_list;
+               *mail_id_count = result_mail_id_count;
+       }
+       else
+               EM_SAFE_FREE(result_mail_id_list);
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_PROFILE_END(profile_emstorage_get_overflowed_mail_id_list);
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_thread_id_by_mail_id(int mail_id, int *thread_id, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], thread_id[%p], err_code[%p]", mail_id, thread_id, err_code);
+
+       int rc = -1, ret = false;
+       int err = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char **result;
+       int result_count = 0;
+
+       if (mail_id == 0 || thread_id == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       memset(sql_query_string, 0, QUERY_SIZE);
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT thread_id FROM mail_tbl WHERE mail_id = %d", mail_id);
+
+       /*  rc = sqlite3_get_table(local_db_handle, sql_query_string, &result, &result_count, 0, NULL); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &result_count, 0, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {err = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (!result_count) {
+               EM_DEBUG_EXCEPTION("No mail found...");
+               ret = false;
+               err= EMAIL_ERROR_MAIL_NOT_FOUND;
+               /* sqlite3_free_table(result); */
+               goto FINISH_OFF;
+       }
+
+       _get_table_field_data_int(result, thread_id, 1);
+
+       sqlite3_free_table(result);
+
+       ret = true;
+
+FINISH_OFF:
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_update_latest_thread_mail(int account_id, int thread_id, int latest_mail_id, int thread_item_count, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], thread_id[%d], latest_mail_id [%d], thread_item_count[%d], err_code[%p]", account_id, thread_id, latest_mail_id, thread_item_count, err_code);
+
+       int rc = -1, ret = false;
+       int err = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char **result = NULL;
+       int result_count = 0;
+
+       if (thread_id == 0) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       if (thread_item_count == 0 || latest_mail_id == 0) {
+               memset(sql_query_string, 0, QUERY_SIZE);
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT mail_id, count(*) FROM (SELECT account_id, mail_id, thread_id, mailbox_type FROM mail_tbl ORDER BY date_time) WHERE account_id = %d AND thread_id = %d AND mailbox_type NOT in (3,5,7)", account_id, thread_id);
+
+               /*  rc = sqlite3_get_table(local_db_handle, sql_query_string, &result, &result_count, 0, NULL); */
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &result_count, 0, NULL), rc);
+               EM_DEBUG_DB_EXEC((SQLITE_OK != rc && -1 != rc), {err = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+                       ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+               EM_DEBUG_LOG("result_count[%d]", result_count);
+               if (result_count == 0) {
+                       EM_DEBUG_EXCEPTION("No mail found...");
+                       ret = false;
+                       err= EMAIL_ERROR_MAIL_NOT_FOUND;
+                       sqlite3_free_table(result);
+                       goto FINISH_OFF;
+               }
+
+               _get_table_field_data_int(result, &latest_mail_id, 2);
+               _get_table_field_data_int(result, &thread_item_count, 3);
+
+               EM_DEBUG_LOG("latest_mail_id[%d]", latest_mail_id);
+               EM_DEBUG_LOG("thread_item_count[%d]", thread_item_count);
+
+               sqlite3_free_table(result);
+       }
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, err);
+
+       /* if (thread_item_count > 1) */
+       /* { */
+               memset(sql_query_string, 0, QUERY_SIZE);
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET thread_item_count = 0 WHERE account_id = %d AND thread_id = %d", account_id, thread_id);
+               EM_DEBUG_LOG("query[%s]", sql_query_string);
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+                       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+       /* } */
+
+       memset(sql_query_string, 0, QUERY_SIZE);
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "UPDATE mail_tbl SET thread_item_count = %d WHERE account_id = %d AND mail_id = %d ", thread_item_count, account_id, latest_mail_id);
+       EM_DEBUG_LOG("query[%s]", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+               EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, err);
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC void emstorage_flush_db_cache()
+{
+       sqlite3_release_memory(-1);
+}
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+/**
+  *    emstorage_add_activity - Add Email Local activity during OFFLINE mode
+  *
+  */
+INTERNAL_FUNC int emstorage_add_activity(emstorage_activity_tbl_t* local_activity, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       EM_DEBUG_LOG(" local_activity[%p], transaction[%d], err_code[%p]", local_activity, transaction, err_code);
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[8192] = { 0x00, };
+       int i = 0;
+
+       if (!local_activity) {
+               EM_DEBUG_EXCEPTION(" local_activity[%p], transaction[%d], err_code[%p]", local_activity, transaction, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       memset(sql_query_string, 0x00 , sizeof(sql_query_string));
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "INSERT INTO mail_local_activity_tbl VALUES (?, ?, ?, ?, ?, ?, ?)");
+
+       EM_DEBUG_LOG(">>>>> ACTIVITY ID [ %d ] ", local_activity->activity_id);
+       EM_DEBUG_LOG(">>>>> MAIL ID [ %d ] ", local_activity->mail_id);
+       EM_DEBUG_LOG(">>>>> ACCOUNT ID [ %d ] ", local_activity->account_id);
+       EM_DEBUG_LOG(">>>>> ACTIVITY TYPE [ %d ] ", local_activity->activity_type);
+       EM_DEBUG_LOG(">>>>> SERVER MAIL ID [ %s ] ", local_activity->server_mailid);
+       EM_DEBUG_LOG(">>>>> SOURCE MAILBOX [ %s ] ", local_activity->src_mbox);
+       EM_DEBUG_LOG(">>>>> DEST MAILBOX   [ %s ] ", local_activity->dest_mbox);
+
+       EM_DEBUG_LOG(">>>> SQL STMT [ %s ] ", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG(">>>> SQL STMT [ %s ] ", sql_query_string);
+
+
+
+
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->activity_id);
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->account_id);
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->mail_id);
+       _bind_stmt_field_data_int(hStmt, i++, local_activity->activity_type);
+       _bind_stmt_field_data_string(hStmt, i++ , (char *)local_activity->server_mailid, 0, SERVER_MAIL_ID_LEN_IN_MAIL_TBL);
+       _bind_stmt_field_data_string(hStmt, i++ , (char *)local_activity->src_mbox, 0, MAILBOX_NAME_LEN_IN_MAIL_BOX_TBL);
+       _bind_stmt_field_data_string(hStmt, i++ , (char *)local_activity->dest_mbox, 0, MAILBOX_NAME_LEN_IN_MAIL_BOX_TBL);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d, errmsg = %s.", rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+       else {
+               EM_DEBUG_LOG(" >>>>>>>>>> hStmt is NULL!!!");
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/**
+  *    emstorage_get_activity - Get the Local activity Information
+  *
+  *
+  */
+INTERNAL_FUNC int emstorage_get_activity(int account_id, int activityid, emstorage_activity_tbl_t** activity_list, int *select_num, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int i = 0, count = 0, rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_activity_tbl_t *p_activity_tbl = NULL;
+       char sql_query_string[1024] = {0x00, };
+       char **result = NULL;
+       int col_index ;
+
+       EM_IF_NULL_RETURN_VALUE(activity_list, false);
+       EM_IF_NULL_RETURN_VALUE(select_num, false);
+
+
+       if (!select_num || !activity_list || account_id <= 0 || activityid < 0) {
+               EM_DEBUG_LOG(" select_num[%p], activity_list[%p] account_id [%d] activityid [%d] ", select_num, activity_list, account_id, activityid);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       if (activityid == ALL_ACTIVITIES) {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_local_activity_tbl WHERE account_id = %d order by activity_id", account_id);
+       }
+       else {
+               SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_local_activity_tbl WHERE account_id = %d AND activity_id = %d ", account_id, activityid);
+       }
+
+       EM_DEBUG_LOG("Query [%s]", sql_query_string);
+
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+
+
+       col_index = 7;
+
+       if (!(p_activity_tbl = (emstorage_activity_tbl_t*)em_malloc(sizeof(emstorage_activity_tbl_t) * count))) {
+               EM_DEBUG_EXCEPTION(" em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+
+       for (i = 0; i < count; i++)  {
+               EM_DEBUG_LOG("result[%d] - %s ", col_index, result[col_index]);
+               if (result[col_index])
+                       p_activity_tbl[i].activity_id = atoi(result[col_index++]);
+
+               EM_DEBUG_LOG("result[%d] - %s ", col_index, result[col_index]);
+               if (result[col_index])
+                       p_activity_tbl[i].account_id = atoi(result[col_index++]);
+
+               EM_DEBUG_LOG("result[%d] - %s ", col_index, result[col_index]);
+               if (result[col_index])
+                       p_activity_tbl[i].mail_id = atoi(result[col_index++]);
+
+               EM_DEBUG_LOG("result[%d] - %s ", col_index, result[col_index]);
+               if (result[col_index])
+                       p_activity_tbl[i].activity_type = atoi(result[col_index++]);
+
+
+               EM_DEBUG_LOG("result[%d] - %s ", col_index, result[col_index]);
+               if (result[col_index] && EM_SAFE_STRLEN(result[col_index])>0)
+                       p_activity_tbl[i].server_mailid = EM_SAFE_STRDUP(result[col_index++]);
+               else
+                       col_index++;
+
+               EM_DEBUG_LOG("result[%d] - %s ", col_index, result[col_index]);
+               if (result[col_index] && EM_SAFE_STRLEN(result[col_index])>0)
+                       p_activity_tbl[i].src_mbox = EM_SAFE_STRDUP(result[col_index++]);
+               else
+                       col_index++;
+
+               EM_DEBUG_LOG("result[%d] - %s ", col_index, result[col_index]);
+               if (result[col_index] && EM_SAFE_STRLEN(result[col_index])>0)
+                       p_activity_tbl[i].dest_mbox = EM_SAFE_STRDUP(result[col_index++]);
+               else
+                       col_index++;
+
+       }
+
+       if (result)
+               sqlite3_free_table(result);
+
+       ret = true;
+
+FINISH_OFF:
+
+
+       if (ret == true)  {
+               *activity_list = p_activity_tbl;
+               *select_num = count;
+               EM_DEBUG_LOG(">>>> COUNT : %d >> ", count);
+       }
+       else if (p_activity_tbl != NULL) {
+               emstorage_free_local_activity(&p_activity_tbl, count, NULL);
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emstorage_get_next_activity_id(int *activity_id, int *err_code)
+{
+
+       EM_DEBUG_FUNC_BEGIN();
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int rc = -1;
+       char *sql = NULL;
+       char **result = NULL;
+
+       if (NULL == activity_id)
+       {
+               EM_DEBUG_EXCEPTION(" activity_id[%p]", activity_id);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /*  increase unique id */
+
+       sql = "SELECT max(rowid) FROM mail_local_activity_tbl;";
+
+       /*  rc = sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL); n EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc); */
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL==result[1])
+               rc = 1;
+       else
+               rc = atoi(result[1])+1;
+
+       *activity_id = rc;
+
+       if (result)
+               sqlite3_free_table(result);
+
+       ret = true;
+
+       FINISH_OFF:
+
+       if (NULL != err_code) {
+               *err_code = err;
+       }
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+
+INTERNAL_FUNC int emstorage_get_activity_id_list(int account_id, int ** activity_id_list, int *activity_id_count, int lowest_activity_type, int highest_activity_type, int transaction, int *err_code)
+{
+
+       EM_DEBUG_FUNC_BEGIN();
+
+       EM_DEBUG_LOG(" account_id[%d], activity_id_list[%p], activity_id_count[%p] err_code[%p]", account_id,  activity_id_list, activity_id_count, err_code);
+
+       if (account_id <= 0|| NULL == activity_id_list || NULL == activity_id_count ||lowest_activity_type <=0 || highest_activity_type <= 0)  {
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       int i = 0, rc = -1, count = 0;
+       char sql_query_string[1024] = {0x00, };
+       int *activity_ids = NULL;
+       int col_index = 0;
+       char **result = NULL;
+
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT distinct activity_id FROM mail_local_activity_tbl WHERE account_id = %d AND activity_type >= %d AND activity_type <= %d order by activity_id", account_id, lowest_activity_type, highest_activity_type);
+
+       EM_DEBUG_LOG(" Query [%s]", sql_query_string);
+
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, &count, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       col_index = 1;
+
+       EM_DEBUG_LOG(" Activity COUNT : %d ... ", count);
+
+       if (NULL == (activity_ids = (int *)em_malloc(sizeof(int) * count))) {
+               EM_DEBUG_EXCEPTION(" em_malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < count; i++)  {
+               activity_ids[i] = atoi(result[col_index]);
+               col_index++;
+               EM_DEBUG_LOG("activity_id %d", activity_ids[i]);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+
+       if (ret == true)  {
+               *activity_id_count = count;
+               *activity_id_list = activity_ids;
+
+       }
+       else if (activity_ids != NULL) /* Prevent defect - 216566 */
+               EM_SAFE_FREE(activity_ids);
+
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       if (err_code != NULL) {
+               *err_code = error;
+       }
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_activity_id_list(int *activity_id_list, int *error_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+
+       EM_DEBUG_LOG(" activity_id_list [%p]", activity_id_list);
+
+       if (NULL == activity_id_list) {
+               error = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       else {
+               free(activity_id_list);
+               activity_id_list = NULL;
+       }
+
+
+       ret= true;
+
+       FINISH_OFF:
+
+       if (NULL != error_code) {
+               *error_code = error;
+       }
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/**
+ * emstorage_delete_local_activity - Deletes the Local acitivity Generated based on activity_type
+ * or based on server mail id
+ *
+ */
+INTERNAL_FUNC int emstorage_delete_local_activity(emstorage_activity_tbl_t* local_activity, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+
+       EM_DEBUG_LOG(" local_activity[%p] ", local_activity);
+
+       if (!local_activity)  {
+               EM_DEBUG_EXCEPTION(" local_activity[%p] ", local_activity);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;                       /* Prevent_FIX  */
+       int err = EMAIL_ERROR_NONE;
+       int query_and = 0;
+       int query_where = 0;
+       char sql_query_string[8192] = { 0x00, };
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_local_activity_tbl ");
+
+       EM_DEBUG_LOG(">>> Query [ %s ] ", sql_query_string);
+
+       if (local_activity->account_id) {
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1),
+               " WHERE account_id = %d ", local_activity->account_id);
+               query_and = 1;
+               query_where = 1;
+       }
+
+       if (local_activity->server_mailid) {
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1),
+               " %s %s server_mailid = '%s' ", query_where? "": "WHERE", query_and? "AND":"", local_activity->server_mailid);
+               query_and = 1;
+               query_where = 1;
+       }
+
+
+       if (local_activity->mail_id) {
+               EM_DEBUG_LOG(">>>> MAIL ID [ %d ] , ACTIVITY TYPE [%d ]", local_activity->mail_id, local_activity->activity_type);
+
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1),
+               " %s %s mail_id = %d  ", query_where? "": "WHERE", query_and? "AND":"", local_activity->mail_id);
+
+               query_and = 1;
+               query_where = 1;
+
+       }
+
+       if (local_activity->activity_type > 0) {
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1),
+               " %s %s activity_type = %d ", query_where? "": "WHERE", query_and? "AND" : "" , local_activity->activity_type);
+       }
+
+       if (local_activity->activity_id > 0) {
+               SNPRINTF(sql_query_string + EM_SAFE_STRLEN(sql_query_string), sizeof(sql_query_string)-(EM_SAFE_STRLEN(sql_query_string)+1),
+               " %s %s activity_id = %d ", query_where? "": "WHERE", query_and? "AND" : "" , local_activity->activity_id);
+
+       }
+
+       EM_DEBUG_LOG(">>>>> Query [ %s ] ", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no (matched) mailbox_name found...");
+               err = EMAIL_ERROR_MAILBOX_NOT_FOUND;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/**
+*      emstorage_free_local_activity - Free the Local Activity data
+*/
+INTERNAL_FUNC int emstorage_free_local_activity(emstorage_activity_tbl_t **local_activity_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       EM_DEBUG_LOG(" local_activity_list[%p], count[%d], err_code[%p]", local_activity_list, count, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_INVALID_PARAM;
+
+       if (count > 0) {
+               if (!local_activity_list || !*local_activity_list) {
+                       EM_DEBUG_EXCEPTION(" local_activity_list[%p], count[%d]", local_activity_list, count);
+
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               emstorage_activity_tbl_t* p = *local_activity_list;
+               int i = 0;
+               if (p) {
+                       for (; i < count; i++)  {
+                               EM_SAFE_FREE(p[i].dest_mbox);
+                               EM_SAFE_FREE(p[i].src_mbox);
+                               EM_SAFE_FREE(p[i].server_mailid);
+                       }
+
+                       free(p);        *local_activity_list = NULL;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+
+}
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+
+static char *_mail_field_name_list[] = {
+               "mail_id",
+               "account_id",
+               "mailbox_id",
+               "mailbox_name",
+               "mailbox_type",
+               "subject",
+               "date_time",
+               "server_mail_status",
+               "server_mailbox_name",
+               "server_mail_id",
+               "message_id",
+               "reference_mail_id",
+               "full_address_from",
+               "full_address_to",
+               "full_address_cc",
+               "full_address_bcc",
+               "body_download_status",
+               "file_path_plain",
+               "file_path_html",
+               "file_size",
+               "flags_seen_field",
+               "flags_deleted_field",
+               "flags_flagged_field",
+               "flags_answered_field",
+               "flags_recent_field",
+               "flags_draft_field",
+               "flags_forwarded_field",
+               "drm_status",
+               "priority",
+               "save_status",
+               "lock_status",
+               "report_status",
+               "attachment_count",
+               "inline_content_count",
+               "thread_id",
+               "thread_item_count",
+               "preview_text",
+               "meeting_request_status",
+               "message_class",
+               "digest_type",
+               "smime_type"
+};
+
+static char*_get_mail_field_name_by_attribute_type(email_mail_attribute_type input_attribute_type)
+{
+       EM_DEBUG_FUNC_BEGIN("input_attribute_type [%d]", input_attribute_type);
+
+       if(input_attribute_type > EMAIL_MAIL_ATTRIBUTE_MEETING_REQUEST_STATUS || input_attribute_type < 0) {
+               EM_DEBUG_EXCEPTION("Invalid input_attribute_type [%d]", input_attribute_type);
+               return NULL;
+       }
+
+       EM_DEBUG_FUNC_END("return [%s]", _mail_field_name_list[input_attribute_type]);
+       return _mail_field_name_list[input_attribute_type];
+}
+
+static int _get_attribute_type_by_mail_field_name(char *input_mail_field_name, email_mail_attribute_type *output_mail_attribute_type)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_field_name [%p], output_mail_attribute_type [%p]", input_mail_field_name, output_mail_attribute_type);
+       int i = 0;
+       int err = EMAIL_ERROR_DATA_NOT_FOUND;
+
+       if(!input_mail_field_name || !output_mail_attribute_type) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       for (i = 0; i < EMAIL_MAIL_ATTRIBUTE_END; i++) {
+               if (EM_SAFE_STRCMP(input_mail_field_name, _mail_field_name_list[i]) == 0) {
+                       *output_mail_attribute_type = i;
+                       err = EMAIL_ERROR_NONE;
+                       break;
+               }
+       }
+
+       EM_DEBUG_FUNC_END("found mail attribute type [%d]", (int)*output_mail_attribute_type);
+       return err;
+}
+
+static int _get_key_value_string_for_list_filter_rule(email_list_filter_rule_t *input_list_filter_rule,char **output_key_value_string)
+{
+       EM_DEBUG_FUNC_BEGIN("input_list_filter_rule [%p], output_key_value_string [%p]", input_list_filter_rule, output_key_value_string);
+
+       int  ret = EMAIL_ERROR_NONE;
+       char key_value_string[QUERY_SIZE] = { 0, };
+       char *temp_key_value_1 = NULL;
+       char *temp_key_value_2 = NULL;
+
+       if(input_list_filter_rule == NULL || output_key_value_string == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       switch(input_list_filter_rule->target_attribute) {
+       case EMAIL_MAIL_ATTRIBUTE_MAIL_ID                 :
+       case EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID              :
+       case EMAIL_MAIL_ATTRIBUTE_MAILBOX_ID              :
+       case EMAIL_MAIL_ATTRIBUTE_MAILBOX_TYPE            :
+       case EMAIL_MAIL_ATTRIBUTE_SERVER_MAIL_STATUS      :
+       case EMAIL_MAIL_ATTRIBUTE_REFERENCE_MAIL_ID       :
+       case EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS    :
+       case EMAIL_MAIL_ATTRIBUTE_FILE_PATH_PLAIN         :
+       case EMAIL_MAIL_ATTRIBUTE_FILE_PATH_HTML          :
+       case EMAIL_MAIL_ATTRIBUTE_FILE_SIZE               :
+       case EMAIL_MAIL_ATTRIBUTE_FLAGS_SEEN_FIELD        :
+       case EMAIL_MAIL_ATTRIBUTE_FLAGS_DELETED_FIELD     :
+       case EMAIL_MAIL_ATTRIBUTE_FLAGS_FLAGGED_FIELD     :
+       case EMAIL_MAIL_ATTRIBUTE_FLAGS_ANSWERED_FIELD    :
+       case EMAIL_MAIL_ATTRIBUTE_FLAGS_RECENT_FIELD      :
+       case EMAIL_MAIL_ATTRIBUTE_FLAGS_DRAFT_FIELD       :
+       case EMAIL_MAIL_ATTRIBUTE_FLAGS_FORWARDED_FIELD   :
+       case EMAIL_MAIL_ATTRIBUTE_DRM_STATUS              :
+       case EMAIL_MAIL_ATTRIBUTE_PRIORITY                :
+       case EMAIL_MAIL_ATTRIBUTE_SAVE_STATUS             :
+       case EMAIL_MAIL_ATTRIBUTE_LOCK_STATUS             :
+       case EMAIL_MAIL_ATTRIBUTE_REPORT_STATUS           :
+       case EMAIL_MAIL_ATTRIBUTE_ATTACHMENT_COUNT        :
+       case EMAIL_MAIL_ATTRIBUTE_INLINE_CONTENT_COUNT    :
+       case EMAIL_MAIL_ATTRIBUTE_THREAD_ID               :
+       case EMAIL_MAIL_ATTRIBUTE_THREAD_ITEM_COUNT       :
+       case EMAIL_MAIL_ATTRIBUTE_MEETING_REQUEST_STATUS  :
+       case EMAIL_MAIL_ATTRIBUTE_MESSAGE_CLASS           :
+       case EMAIL_MAIL_ATTRIBUTE_DIGEST_TYPE             :
+       case EMAIL_MAIL_ATTRIBUTE_SMIME_TYPE              :
+               SNPRINTF(key_value_string, QUERY_SIZE, "%d", input_list_filter_rule->key_value.integer_type_value);
+               break;
+
+       case EMAIL_MAIL_ATTRIBUTE_MAILBOX_NAME            :
+       case EMAIL_MAIL_ATTRIBUTE_SUBJECT                 :
+       case EMAIL_MAIL_ATTRIBUTE_SERVER_MAILBOX_NAME     :
+       case EMAIL_MAIL_ATTRIBUTE_SERVER_MAIL_ID          :
+       case EMAIL_MAIL_ATTRIBUTE_MESSAGE_ID              :
+       case EMAIL_MAIL_ATTRIBUTE_FROM                    :
+       case EMAIL_MAIL_ATTRIBUTE_TO                      :
+       case EMAIL_MAIL_ATTRIBUTE_CC                      :
+       case EMAIL_MAIL_ATTRIBUTE_BCC                     :
+       case EMAIL_MAIL_ATTRIBUTE_PREVIEW_TEXT            :
+               if(input_list_filter_rule->key_value.string_type_value == NULL) {
+                       EM_DEBUG_EXCEPTION("Invalid string_type_value [%p]", input_list_filter_rule->key_value.string_type_value);
+                       ret = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               temp_key_value_1 = input_list_filter_rule->key_value.string_type_value;
+
+               temp_key_value_2 = em_replace_all_string(temp_key_value_1, "_", "\\_");
+               temp_key_value_1 = em_replace_all_string(temp_key_value_2, "%", "\\%");
+
+               if(input_list_filter_rule->rule_type == EMAIL_LIST_FILTER_RULE_INCLUDE)
+                       SNPRINTF(key_value_string, QUERY_SIZE, "\'%%%s%%\'", temp_key_value_1);
+               else
+                       SNPRINTF(key_value_string, QUERY_SIZE, "\'%s\'", temp_key_value_1);
+               break;
+
+       case EMAIL_MAIL_ATTRIBUTE_DATE_TIME               :
+               SNPRINTF(key_value_string, QUERY_SIZE, "%d", (int)input_list_filter_rule->key_value.datetime_type_value);
+               break;
+
+       default :
+               ret = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("Invalid target_attribute [%d]", input_list_filter_rule->target_attribute);
+               break;
+       }
+
+       if(ret == EMAIL_ERROR_NONE && EM_SAFE_STRLEN(key_value_string) > 0) {
+               *output_key_value_string = strdup(key_value_string);
+       }
+
+FINISH_OFF:
+
+       EM_SAFE_FREE(temp_key_value_1);
+       EM_SAFE_FREE(temp_key_value_2);
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+static int _get_cert_password_file_name(int index, char *cert_password_file_name)
+{
+       EM_DEBUG_FUNC_BEGIN("index : [%d]", index);
+
+       if (index <= 0 || !cert_password_file_name) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       sprintf(cert_password_file_name, ".email_cert_%d", index);
+
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+#endif
+
+static int _make_filter_rule_string(email_list_filter_rule_t *input_list_filter_rule, char **output_string)
+{
+       EM_DEBUG_FUNC_BEGIN("input_list_filter_rule [%p], output_string [%p]", input_list_filter_rule, output_string);
+
+       int   ret = EMAIL_ERROR_NONE;
+       int   is_alpha = 0;
+       int   length_field_name = 0;
+       int   length_value = 0;
+       char  result_rule_string[QUERY_SIZE] = { 0 , };
+       char *mod_field_name_string = NULL;
+       char *mod_value_string = NULL;
+       char *temp_field_name_string = NULL;
+       char *temp_key_value_string = NULL;
+
+       if(input_list_filter_rule == NULL || output_string == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return  EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       temp_field_name_string = _get_mail_field_name_by_attribute_type(input_list_filter_rule->target_attribute);
+
+       if(temp_field_name_string == NULL) {
+               EM_DEBUG_EXCEPTION("Invalid target_attribute [%d]", input_list_filter_rule->target_attribute);
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if( _get_key_value_string_for_list_filter_rule(input_list_filter_rule, &temp_key_value_string) != EMAIL_ERROR_NONE || temp_key_value_string == NULL) {
+               EM_DEBUG_EXCEPTION("_get_key_value_string_for_list_filter_rule failed");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       length_field_name = EM_SAFE_STRLEN(temp_field_name_string);
+       length_value      = EM_SAFE_STRLEN(temp_key_value_string);
+
+       switch(input_list_filter_rule->target_attribute) {
+       case EMAIL_MAIL_ATTRIBUTE_MAILBOX_NAME            :
+       case EMAIL_MAIL_ATTRIBUTE_SUBJECT                 :
+       case EMAIL_MAIL_ATTRIBUTE_SERVER_MAILBOX_NAME     :
+       case EMAIL_MAIL_ATTRIBUTE_SERVER_MAIL_ID          :
+       case EMAIL_MAIL_ATTRIBUTE_MESSAGE_ID              :
+       case EMAIL_MAIL_ATTRIBUTE_FROM                    :
+       case EMAIL_MAIL_ATTRIBUTE_TO                      :
+       case EMAIL_MAIL_ATTRIBUTE_CC                      :
+       case EMAIL_MAIL_ATTRIBUTE_BCC                     :
+       case EMAIL_MAIL_ATTRIBUTE_PREVIEW_TEXT            :
+               is_alpha = 1;
+               break;
+       default :
+               is_alpha = 0;
+               break;
+       }
+
+       if(is_alpha == 1 && input_list_filter_rule->case_sensitivity == false) {
+               length_field_name += strlen("UPPER() ");
+               length_value      += strlen("UPPER() ");
+               mod_field_name_string = em_malloc(sizeof(char) * length_field_name);
+               mod_value_string      = em_malloc(sizeof(char) * length_value);
+               SNPRINTF(mod_field_name_string, length_field_name, "UPPER(%s)", temp_field_name_string);
+               SNPRINTF(mod_value_string,      length_value, "UPPER(%s)", temp_key_value_string);
+               EM_SAFE_FREE(temp_key_value_string);
+       }
+       else {
+               mod_field_name_string = strdup(temp_field_name_string);
+               mod_value_string      = temp_key_value_string;
+       }
+
+       switch (input_list_filter_rule->rule_type) {
+       case EMAIL_LIST_FILTER_RULE_EQUAL     :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s = %s ", mod_field_name_string, mod_value_string);
+               break;
+       case EMAIL_LIST_FILTER_RULE_NOT_EQUAL :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s != %s ", mod_field_name_string, mod_value_string);
+               break;
+       case EMAIL_LIST_FILTER_RULE_LESS_THAN :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s < %s ", mod_field_name_string, mod_value_string);
+               break;
+       case EMAIL_LIST_FILTER_RULE_GREATER_THAN :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s > %s ", mod_field_name_string, mod_value_string);
+               break;
+       case EMAIL_LIST_FILTER_RULE_LESS_THAN_OR_EQUAL :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s <= %s ", mod_field_name_string, mod_value_string);
+               break;
+       case EMAIL_LIST_FILTER_RULE_GREATER_THAN_OR_EQUAL :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s >= %s ", mod_field_name_string, mod_value_string);
+               break;
+       case EMAIL_LIST_FILTER_RULE_INCLUDE   :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s LIKE %s ", mod_field_name_string, mod_value_string);
+               break;
+       case EMAIL_LIST_FILTER_RULE_IN        :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s IN (%s) ", mod_field_name_string, mod_value_string);
+               break;
+       case EMAIL_LIST_FILTER_RULE_NOT_IN    :
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s NOT IN (%s) ", mod_field_name_string, mod_value_string);
+               break;
+       default :
+               EM_DEBUG_EXCEPTION("Invalid rule_type [%d]", input_list_filter_rule->rule_type);
+               ret = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       *output_string = strdup(result_rule_string);
+
+FINISH_OFF:
+       EM_SAFE_FREE(mod_field_name_string);
+       EM_SAFE_FREE(mod_value_string);
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+static int _make_order_rule_string(email_list_sorting_rule_t *input_sorting_rule, char **output_string) {
+       EM_DEBUG_FUNC_BEGIN("input_sorting_rule [%p], output_string [%p]", input_sorting_rule, output_string);
+
+       char  result_rule_string[QUERY_SIZE] = { 0 , };
+       int   ret = EMAIL_ERROR_NONE;
+
+       if(input_sorting_rule->force_boolean_check) {
+               SNPRINTF(result_rule_string, QUERY_SIZE, "%s = 0 ", _get_mail_field_name_by_attribute_type(input_sorting_rule->target_attribute));
+       }
+       else
+               EM_SAFE_STRCPY(result_rule_string, _get_mail_field_name_by_attribute_type(input_sorting_rule->target_attribute));
+
+       switch (input_sorting_rule->sort_order) {
+               case EMAIL_SORT_ORDER_ASCEND     :
+                       EM_SAFE_STRCAT(result_rule_string, " ASC ");
+                       break;
+
+               case EMAIL_SORT_ORDER_DESCEND    :
+                       EM_SAFE_STRCAT(result_rule_string, " DESC ");
+                       break;
+
+               default :
+                       EM_DEBUG_EXCEPTION("Invalid sort_order [%d]", input_sorting_rule->sort_order);
+                       ret = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+       }
+
+       *output_string = strdup(result_rule_string);
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_write_conditional_clause_for_getting_mail_list(email_list_filter_t *input_filter_list, int input_filter_count, email_list_sorting_rule_t *input_sorting_rule_list, int input_sorting_rule_count, int input_start_index, int input_limit_count, char **output_conditional_clause)
+{
+       EM_DEBUG_FUNC_BEGIN("input_filter_list [%p], input_filter_count[%d], input_sorting_rule_list[%p], input_sorting_rule_count [%d], input_start_index [%d], input_limit_count [%d], output_conditional_clause [%p]", input_filter_list, input_filter_count, input_sorting_rule_list, input_sorting_rule_count, input_start_index, input_limit_count, output_conditional_clause);
+       int ret = EMAIL_ERROR_NONE;
+       int i = 0;
+       int string_offset = 0;
+       char conditional_clause_string[QUERY_SIZE] = {0, };
+       char *result_string_for_a_item = NULL;
+
+       if ( (input_filter_count > 0 && !input_filter_list) || (input_sorting_rule_count > 0 && !input_sorting_rule_list) || output_conditional_clause == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       if(input_filter_count > 0) {
+               strcpy(conditional_clause_string,  " WHERE ");
+
+               for ( i = 0; i < input_filter_count; i++) {
+                       switch (input_filter_list[i].list_filter_item_type) {
+                       case EMAIL_LIST_FILTER_ITEM_RULE :
+                               EM_DEBUG_LOG("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_RULE", i);
+                               _make_filter_rule_string(&(input_filter_list[i].list_filter_item.rule), &result_string_for_a_item);
+                               break;
+
+                       case EMAIL_LIST_FILTER_ITEM_OPERATOR :
+                               EM_DEBUG_LOG("[%d]list_filter_item_type is EMAIL_LIST_FILTER_ITEM_OPERATOR", i);
+                               switch(input_filter_list[i].list_filter_item.operator_type) {
+                               case EMAIL_LIST_FILTER_OPERATOR_AND :
+                                       result_string_for_a_item = strdup("AND ");
+                                       break;
+                               case EMAIL_LIST_FILTER_OPERATOR_OR :
+                                       result_string_for_a_item = strdup("OR ");
+                                       break;
+                               case EMAIL_LIST_FILTER_OPERATOR_LEFT_PARENTHESIS :
+                                       result_string_for_a_item = strdup(" (");
+                                       break;
+                               case EMAIL_LIST_FILTER_OPERATOR_RIGHT_PARENTHESIS :
+                                       result_string_for_a_item = strdup(") ");
+                                       break;
+                               }
+                               break;
+
+                       default :
+                               EM_DEBUG_EXCEPTION("Invalid list_filter_item_type [%d]", input_filter_list[i].list_filter_item_type);
+                               ret = EMAIL_ERROR_INVALID_PARAM;
+                               goto FINISH_OFF;
+                       }
+
+                       if(result_string_for_a_item == NULL) {
+                               EM_DEBUG_EXCEPTION("result_string_for_a_item is null");
+                               ret = EMAIL_ERROR_INVALID_PARAM;
+                               goto FINISH_OFF;
+                       }
+
+                       if(strlen(conditional_clause_string) + EM_SAFE_STRLEN(result_string_for_a_item) >= QUERY_SIZE) { /* prevent 34364 */
+                               EM_DEBUG_EXCEPTION("Query is too long");
+                               ret = EMAIL_ERROR_DATA_TOO_LONG;
+                               goto FINISH_OFF;
+                       }
+                       strcat(conditional_clause_string, result_string_for_a_item);
+                       EM_SAFE_FREE(result_string_for_a_item);
+               }
+       }
+
+       if(input_sorting_rule_count > 0) {
+               strcat(conditional_clause_string, "ORDER BY ");
+
+               for ( i = 0; i < input_sorting_rule_count; i++) {
+                       if( (ret = _make_order_rule_string(&input_sorting_rule_list[i], &result_string_for_a_item)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("_make_order_rule_string failed. [%d]", ret);
+                               goto FINISH_OFF;
+                       }
+                       if(i > 0)
+                               strcat(conditional_clause_string, ", ");
+                       strcat(conditional_clause_string, result_string_for_a_item);
+                       EM_SAFE_FREE(result_string_for_a_item);
+               }
+       }
+
+       if (input_start_index != -1 && input_limit_count != -1) {
+               string_offset = strlen(conditional_clause_string);
+               SNPRINTF_OFFSET(conditional_clause_string, string_offset, QUERY_SIZE, " LIMIT %d, %d", input_start_index, input_limit_count);
+       }
+
+       *output_conditional_clause = strdup(conditional_clause_string);
+
+FINISH_OFF:
+       EM_SAFE_FREE(result_string_for_a_item);
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_list_filter(email_list_filter_t **input_filter_list, int input_filter_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_filter_list [%p], input_filter_count[%d]", input_filter_list, input_filter_count);
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       email_list_filter_t *temp_filter_list = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(input_filter_list, EMAIL_ERROR_INVALID_PARAM);
+
+       for ( i = 0; i < input_filter_count; i++) {
+               temp_filter_list = (*input_filter_list) + i;
+               if(temp_filter_list && temp_filter_list->list_filter_item_type == EMAIL_LIST_FILTER_ITEM_RULE) {
+                       switch(temp_filter_list->list_filter_item.rule.target_attribute) {
+                       case EMAIL_MAIL_ATTRIBUTE_MAILBOX_NAME :
+                       case EMAIL_MAIL_ATTRIBUTE_SUBJECT :
+                       case EMAIL_MAIL_ATTRIBUTE_SERVER_MAILBOX_NAME :
+                       case EMAIL_MAIL_ATTRIBUTE_SERVER_MAIL_ID :
+                       case EMAIL_MAIL_ATTRIBUTE_MESSAGE_ID :
+                       case EMAIL_MAIL_ATTRIBUTE_FROM :
+                       case EMAIL_MAIL_ATTRIBUTE_TO :
+                       case EMAIL_MAIL_ATTRIBUTE_CC :
+                       case EMAIL_MAIL_ATTRIBUTE_BCC :
+                       case EMAIL_MAIL_ATTRIBUTE_FILE_PATH_PLAIN :
+                       case EMAIL_MAIL_ATTRIBUTE_FILE_PATH_HTML :
+                       case EMAIL_MAIL_ATTRIBUTE_PREVIEW_TEXT :
+                               EM_SAFE_FREE(temp_filter_list->list_filter_item.rule.key_value.string_type_value);
+                               break;
+                       default :
+                               break;
+                       }
+               }
+       }
+
+       free(*input_filter_list);
+       *input_filter_list = NULL;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emstorage_add_certificate(emstorage_certificate_tbl_t *certificate, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate:[%p], transaction:[%d], err_code:[%p]", certificate, transaction, err_code);
+
+       if (!certificate) {
+               EM_DEBUG_EXCEPTION("certificate:[%p], transaction:[%d], err_code:[%p]", certificate, transaction, err_code);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       char cert_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+#endif
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       char *sql = "SELECT max(rowid) FROM mail_certificate_tbl;";
+       char **result = NULL;
+
+       /*  rc = sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL==result[1]) rc = 1;
+       else rc = atoi(result[1])+1;
+       sqlite3_free_table(result);
+
+       certificate->certificate_id = rc;
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       if ((error = _get_cert_password_file_name(certificate->certificate_id, cert_password_file_name)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("em_storage_get_password_file_name failed.");
+               goto FINISH_OFF;
+       }
+#endif
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_certificate_tbl VALUES "
+               "(        "
+               "   ?  "                /* Index of certificate */
+               "  , ? "                /* Select the account */
+               "  , ? "                /* Year of issue */
+               "  , ? "                /* Month of issue */
+               "  , ? "                /* Day of issue */
+               "  , ? "                /* Year of expiration */
+               "  , ? "                /* Month of expiration */
+               "  , ? "                /* Day of expiration */
+               "  , ? "                /* Organization of issue */
+               "  , ? "                /* Email address */
+               "  , ? "                /* Subject of certificate */
+               "  , ? "                /* Name of saved certificate */
+               ") ");
+
+
+       /*  rc = sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG(">>>> SQL STMT [ %s ] ", sql_query_string);
+       _bind_stmt_field_data_int(hStmt, CERTFICATE_BIND_TYPE_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->certificate_id);
+       _bind_stmt_field_data_int(hStmt, ISSUE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->issue_year);
+       _bind_stmt_field_data_int(hStmt, ISSUE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->issue_month);
+       _bind_stmt_field_data_int(hStmt, ISSUE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->issue_day);
+       _bind_stmt_field_data_int(hStmt, EXPIRE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->expiration_year);
+       _bind_stmt_field_data_int(hStmt, EXPIRE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->expiration_month);
+       _bind_stmt_field_data_int(hStmt, EXPIRE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->expiration_day);
+       _bind_stmt_field_data_string(hStmt, ISSUE_ORGANIZATION_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->issue_organization_name, 0, ISSUE_ORGANIZATION_LEN_IN_MAIL_CERTIFICATE_TBL);
+       _bind_stmt_field_data_string(hStmt, EMAIL_ADDRESS_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->email_address, 0, EMAIL_ADDRESS_LEN_IN_MAIL_CERTIFICATE_TBL);
+       _bind_stmt_field_data_string(hStmt, SUBJECT_STRING_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->subject_str, 0, SUBJECT_STRING_LEN_IN_MAIL_CERTIFICATE_TBL);
+       _bind_stmt_field_data_string(hStmt, FILE_PATH_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->filepath, 0, FILE_NAME_LEN_IN_MAIL_CERTIFICATE_TBL);
+       /*  rc = sqlite3_step(hStmt); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d, errmsg = %s.", rc, sqlite3_errmsg(local_db_handle)));
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       if (ssm_write_buffer(certificate->password, EM_SAFE_STRLEN(certificate->password), cert_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+               EM_DEBUG_EXCEPTION("ssm_write_buffer failed - Private certificate password : [%s]", cert_password_file_name);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+#endif
+       ret = true;
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+
+       if (!emcore_notify_storage_event(NOTI_CERTIFICATE_ADD, certificate->certificate_id, 0, NULL, 0))
+               EM_DEBUG_EXCEPTION("emcore_notify_storage_event(NOTI_CERTIFICATE_ADD] : Notification failed");
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+       else
+               EM_DEBUG_LOG("hStmt is NULL!!!");
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_free_certificate(emstorage_certificate_tbl_t **certificate_list, int count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate_list[%p], count[%d], err_code[%p]", certificate_list, count, err_code);
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+
+       if (count > 0)  {
+               if (!certificate_list || !*certificate_list)  {
+                       EM_DEBUG_EXCEPTION("certificate_list[%p], count[%d]", certificate_list, count);
+                       error = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               emstorage_certificate_tbl_t *p = *certificate_list;
+               int i = 0;
+
+               for (; i < count; i++)  {
+                       EM_SAFE_FREE(p[i].issue_organization_name);
+                       EM_SAFE_FREE(p[i].email_address);
+                       EM_SAFE_FREE(p[i].subject_str);
+                       EM_SAFE_FREE(p[i].filepath);
+                       EM_SAFE_FREE(p[i].password);
+               }
+
+               EM_SAFE_FREE(p);
+               *certificate_list = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_certificate_list(int *select_num, emstorage_certificate_tbl_t **certificate_list, int transaction, int with_password, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int i = 0, count = 0, rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_certificate_tbl_t *p_data_tbl = NULL;
+
+       DB_STMT hStmt = NULL;
+
+       if (!select_num || !certificate_list)  {
+               EM_DEBUG_EXCEPTION("select_num[%p], account_list[%p]", select_num, certificate_list);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char *sql = "SELECT count(*) FROM mail_certificate_tbl;";
+       char **result;
+
+       /*  rc = sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       if (!count) {
+               EM_DEBUG_EXCEPTION("no account found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               ret = true;
+               goto FINISH_OFF;
+       }
+       EM_DEBUG_LOG("count = %d", rc);
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT * FROM mail_certificate_tbl ORDER BY account_id");
+
+       /*  rc = sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL);   */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_LOG("After sqlite3_prepare_v2 hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       /*  rc = sqlite3_step(hStmt); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no account found...");
+
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               count = 0;
+               ret = true;
+               goto FINISH_OFF;
+       }
+
+       if (!(p_data_tbl = (emstorage_certificate_tbl_t *)malloc(sizeof(emstorage_certificate_tbl_t) * count)))  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       memset(p_data_tbl, 0x00, sizeof(emstorage_certificate_tbl_t) * count);
+       for (i = 0; i < count; i++)  {
+               /*  get recordset */
+               _get_stmt_field_data_int(hStmt,  &(p_data_tbl[i].certificate_id), CERTFICATE_BIND_TYPE_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].issue_year), ISSUE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].issue_month), ISSUE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].issue_day), ISSUE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].expiration_year), EXPIRE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].expiration_month), EXPIRE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_int(hStmt, &(p_data_tbl[i].expiration_day), EXPIRE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].issue_organization_name), 0, ISSUE_ORGANIZATION_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].email_address), 0, EMAIL_ADDRESS_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].subject_str), 0, SUBJECT_STRING_IDX_IN_MAIL_CERTIFICATE_TBL);
+               _get_stmt_field_data_string(hStmt, &(p_data_tbl[i].filepath), 0, FILE_PATH_IDX_IN_MAIL_CERTIFICATE_TBL);
+               if (with_password == true) {
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+                       /*  get password from the secure storage */
+                       char cert_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+
+                       EM_SAFE_FREE(p_data_tbl[i].password);
+
+                       /*  get password file name */
+                       if ((error = _get_cert_password_file_name(p_data_tbl[i].certificate_id, cert_password_file_name)) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("em_storage_get_password_file_name failed.");
+                               goto FINISH_OFF;
+                       }
+
+                       /*  read password from secure storage */
+                       if ((error = _read_password_from_secure_storage(cert_password_file_name, &(p_data_tbl[i].password))) < 0) {
+                               EM_DEBUG_EXCEPTION("_read_password_from_secure_storage() failed...");
+                               goto FINISH_OFF;
+                       }
+                       EM_DEBUG_LOG("recv_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl[i].password);
+#endif
+               }
+
+               /*  rc = sqlite3_step(hStmt); */
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_LOG("after sqlite3_step(), i = %d, rc = %d.", i,  rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)  {
+               *certificate_list = p_data_tbl;
+               *select_num = count;
+               EM_DEBUG_LOG("COUNT : %d", count);
+       }
+       else if (p_data_tbl != NULL)
+               emstorage_free_certificate(&p_data_tbl, count, NULL);
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               hStmt = NULL;
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_certificate_by_email_address(char *email_address, emstorage_certificate_tbl_t **certificate, int transaction, int with_password, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("email_address[%s], certificate[%p], transaction[%d], err_code[%p]", email_address, certificate, transaction, err_code);
+
+       if (!certificate)  {
+               EM_DEBUG_EXCEPTION("email_address[%s], certificate[%p]", email_address, certificate);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_certificate_tbl_t *p_data_tbl = NULL;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       int rc = -1;
+       int sql_len = 0;
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       char cert_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+#endif
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       /*  Make query string */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT ");
+       sql_len = EM_SAFE_STRLEN(sql_query_string);
+
+       /*  dummy value, FROM WHERE clause */
+       SNPRINTF(sql_query_string + sql_len, sizeof(sql_query_string) - sql_len, "* FROM mail_certificate_tbl WHERE email_address = '%s'", email_address);
+
+       /*  FROM clause */
+       EM_DEBUG_LOG("query = [%s]", sql_query_string);
+
+       /*  execute a sql and count rows */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no matched certificate found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       /*  Assign query result to structure */
+       if (!(p_data_tbl = (emstorage_certificate_tbl_t *)malloc(sizeof(emstorage_certificate_tbl_t))))  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(p_data_tbl, 0x00, sizeof(emstorage_certificate_tbl_t));
+       _get_stmt_field_data_int(hStmt,  &(p_data_tbl->certificate_id), CERTFICATE_BIND_TYPE_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->issue_year), ISSUE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->issue_month), ISSUE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->issue_day), ISSUE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->expiration_year), EXPIRE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->expiration_month), EXPIRE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->expiration_day), EXPIRE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->issue_organization_name), 0, ISSUE_ORGANIZATION_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->email_address), 0, EMAIL_ADDRESS_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->subject_str), 0, SUBJECT_STRING_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->filepath), 0, FILE_PATH_IDX_IN_MAIL_CERTIFICATE_TBL);
+
+       if (with_password) {
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+               /*  get password file name */
+               if ((error = _get_cert_password_file_name(p_data_tbl->certificate_id, cert_password_file_name)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("em_storage_get_password_file_name failed.");
+                       goto FINISH_OFF;
+               }
+
+               /*  read password from secure storage */
+               if ((error = _read_password_from_secure_storage(cert_password_file_name, &(p_data_tbl->password))) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed...");
+                       goto FINISH_OFF;
+               }
+               EM_DEBUG_LOG("cert_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl->password);
+#endif
+       }
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *certificate = p_data_tbl;
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_get_certificate_by_index(int index, emstorage_certificate_tbl_t **certificate, int transaction, int with_password, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("index[%d], certificate[%p], transaction[%d], err_code[%p]", index, certificate, transaction, err_code);
+
+       if (!certificate)  {
+               EM_DEBUG_EXCEPTION("index[%d], account[%p]", index, certificate);
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       emstorage_certificate_tbl_t *p_data_tbl = NULL;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       int rc = -1;
+       int sql_len = 0;
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       char cert_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+#endif
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_READ_TRANSACTION(transaction);
+
+       /*  Make query string */
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "SELECT ");
+       sql_len = EM_SAFE_STRLEN(sql_query_string);
+
+       /*  dummy value, FROM WHERE clause */
+       SNPRINTF(sql_query_string + sql_len, sizeof(sql_query_string) - sql_len, "* FROM mail_certificate_tbl WHERE certificate_id = %d", index);
+
+       /*  FROM clause */
+       EM_DEBUG_LOG("query = [%s]", sql_query_string);
+
+       /*  execute a sql and count rows */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no matched certificate found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       /*  Assign query result to structure */
+       if (!(p_data_tbl = (emstorage_certificate_tbl_t *)malloc(sizeof(emstorage_certificate_tbl_t))))  {
+               EM_DEBUG_EXCEPTION("malloc failed...");
+               error = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(p_data_tbl, 0x00, sizeof(emstorage_certificate_tbl_t));
+
+       _get_stmt_field_data_int(hStmt,  &(p_data_tbl->certificate_id), CERTFICATE_BIND_TYPE_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->issue_year), ISSUE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->issue_month), ISSUE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->issue_day), ISSUE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->expiration_year), EXPIRE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->expiration_month), EXPIRE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_int(hStmt, &(p_data_tbl->expiration_day), EXPIRE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->issue_organization_name), 0, ISSUE_ORGANIZATION_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->email_address), 0, EMAIL_ADDRESS_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->subject_str), 0, SUBJECT_STRING_IDX_IN_MAIL_CERTIFICATE_TBL);
+       _get_stmt_field_data_string(hStmt, &(p_data_tbl->filepath), 0, FILE_PATH_IDX_IN_MAIL_CERTIFICATE_TBL);
+
+       if (with_password) {
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+               /*  get password file name */
+               if ((error = _get_cert_password_file_name(p_data_tbl->certificate_id, cert_password_file_name)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("em_storage_get_password_file_name failed.");
+                       goto FINISH_OFF;
+               }
+
+               /*  read password from secure storage */
+               if ((error = _read_password_from_secure_storage(cert_password_file_name, &(p_data_tbl->password))) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION(" _read_password_from_secure_storage()  failed...");
+                       goto FINISH_OFF;
+               }
+               EM_DEBUG_LOG("cert_password_file_name[%s], password[%s]", cert_password_file_name,  p_data_tbl->password);
+#endif
+       }
+       ret = true;
+
+FINISH_OFF:
+       if (ret == true)
+               *certificate = p_data_tbl;
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_READ_TRANSACTION(transaction);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_delete_certificate(int certificate_id, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate_id[%d], transaction[%d], err_code[%p]", certificate_id, transaction, err_code);
+
+       if (certificate_id < 1)  {
+               EM_DEBUG_EXCEPTION(" certificate_id[%d]", certificate_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int rc = -1, ret = false;
+       int error = EMAIL_ERROR_NONE;
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       /*  TODO : delete password files - file names can be obtained from db or a rule that makes a name */
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       char cert_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+       /*  get password file name */
+       if ((error = _get_cert_password_file_name(certificate_id, cert_password_file_name)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("em_storage_get_password_file_name failed.");
+               goto FINISH_OFF;
+       }
+#endif
+       /*  delete from db */
+       memset(sql_query_string, 0x00, sizeof(sql_query_string));
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_certificate_tbl WHERE certificate_id = %d", certificate_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_exec fail:%d", rc));
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       /*  validate account existence */
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0)  {
+               EM_DEBUG_EXCEPTION(" no matched certificate found...");
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       /*  delete from secure storage */
+       if (ssm_delete_file(cert_password_file_name,  SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+               EM_DEBUG_EXCEPTION(" ssm_delete_file failed -cert password : file[%s]", cert_password_file_name);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+#endif
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emstorage_update_certificate(int certificate_id, emstorage_certificate_tbl_t *certificate, int transaction, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("certificate_id[%d], certificate[%p], transaction[%d], err_code[%p]", certificate_id, certificate, transaction, err_code);
+
+       if (certificate_id < 1)  {
+               EM_DEBUG_EXCEPTION(" certificate_id[%d]", certificate_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int error = EMAIL_ERROR_NONE;
+       int rc, ret = false;
+
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       char cert_password_file_name[MAX_PW_FILE_NAME_LENGTH];
+#endif
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, error);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_certificate_tbl SET"
+               " issue_year = ?"
+               ", issue_month = ?"             /* Index of certificate */
+               ", issue_day = ?"               /* Select the account */
+               ", expiration_year = ?"         /* Year of issue */
+               ", expiration_month = ?"                /* Month of issue */
+               ", expiration_day = ?"          /* Day of issue */
+               ", issue_organization_name = ?"         /* Year of expiration */
+               ", email_address = ?"           /* Month of expiration */
+               ", subject_str = ?"             /* Day of expiration */
+               ", filepath = ?"                /* Organization of issue */
+               ", password = ?"
+               " WHERE certificate_id = ?");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_LOG("After sqlite3_prepare hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       _bind_stmt_field_data_int(hStmt, ISSUE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->issue_year);
+       _bind_stmt_field_data_int(hStmt, ISSUE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->issue_month);
+       _bind_stmt_field_data_int(hStmt, ISSUE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->issue_day);
+       _bind_stmt_field_data_int(hStmt, EXPIRE_YEAR_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->expiration_year);
+       _bind_stmt_field_data_int(hStmt, EXPIRE_MONTH_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->expiration_month);
+       _bind_stmt_field_data_int(hStmt, EXPIRE_DAY_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->expiration_day);
+       _bind_stmt_field_data_string(hStmt, ISSUE_ORGANIZATION_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->issue_organization_name, 0, ISSUE_ORGANIZATION_LEN_IN_MAIL_CERTIFICATE_TBL);
+       _bind_stmt_field_data_string(hStmt, EMAIL_ADDRESS_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->email_address, 0, EMAIL_ADDRESS_LEN_IN_MAIL_CERTIFICATE_TBL);
+       _bind_stmt_field_data_string(hStmt, SUBJECT_STRING_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->subject_str, 0, SUBJECT_STRING_LEN_IN_MAIL_CERTIFICATE_TBL);
+       _bind_stmt_field_data_string(hStmt, FILE_PATH_IDX_IN_MAIL_CERTIFICATE_TBL, certificate->filepath, 0, FILE_NAME_LEN_IN_MAIL_CERTIFICATE_TBL);
+
+       /*  rc = sqlite3_step(hStmt); */
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_FULL == rc), {error = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {error = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       /*  validate account existence */
+       rc = sqlite3_changes(local_db_handle);
+       if (rc == 0) {
+               EM_DEBUG_EXCEPTION(" no matched account found...");
+
+               error = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_SUPPORT_PRIVATE_CERTIFICATE__
+       /*  get password file name */
+       if ((error = _get_cert_password_file_name(certificate->certificate_id, cert_password_file_name)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("em_storage_get_password_file_name failed.");
+               goto FINISH_OFF;
+       }
+
+       /*  save passwords to the secure storage */
+       if (ssm_write_buffer(certificate->password, EM_SAFE_STRLEN(certificate->password), cert_password_file_name, SSM_FLAG_SECRET_OPERATION, NULL) < 0) {
+               EM_DEBUG_EXCEPTION("ssm_write_buffer failed - Private certificate password : [%s]", cert_password_file_name);
+               error = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+#endif
+       if (!emcore_notify_storage_event(NOTI_CERTIFICATE_UPDATE, certificate->certificate_id, 0, NULL, 0))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event[ NOTI_CERTIFICATE_UPDATE] : Notification Failed >>> ");
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG(" Before sqlite3_finalize hStmt = %p", hStmt);
+
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG(" sqlite3_finalize failed - %d", rc);
+                       error = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, error);
+
+       _DISCONNECT_DB;
+
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+/* Tasks --------------------------------------------------------------------------*/
+INTERNAL_FUNC int emstorage_add_task(email_task_type_t input_task_type, email_task_priority_t input_task_priority, char *input_task_parameter, int input_task_parameter_length, int input_transaction, int *output_task_id)
+{
+       EM_DEBUG_FUNC_BEGIN("input_task_type [%d] input_task_priority[%p], input_task_parameter[%p] input_task_parameter_length[%d] input_transaction[%d] output_task_id[%p]", input_task_type, input_task_priority, input_task_parameter, input_task_parameter_length, input_transaction, output_task_id);
+       int ret = 0;
+       int i = 0;
+       int task_id = 0;
+       int err = EMAIL_ERROR_NONE;
+       int rc = -1;
+       DB_STMT hStmt = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = NULL;
+       char *sql = "SELECT max(rowid) FROM mail_task_tbl;";
+       char **result = NULL;
+
+       if (input_task_parameter == NULL || output_task_id == NULL)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(input_transaction, err);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql, rc, sqlite3_errmsg(local_db_handle)));
+
+       if (NULL == result[1])
+               task_id = 1;
+       else
+               task_id = atoi(result[1])+1;
+
+       *output_task_id = task_id;
+
+       sqlite3_free_table(result);
+       result = NULL;
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "INSERT INTO mail_task_tbl VALUES "
+               "(        "
+               "    ? "  /*   task_id */
+               "  , ? "  /*   task_type */
+               "  , ? "  /*   task_status */
+               "  , ? "  /*   task_priority */
+               "  , ? "  /*   task_parameter_length */
+               "  , ? "  /*   task_parameter */
+               "  , ? "  /*   date_time */
+               ") ");
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EM_DEBUG_LOG(">>>> SQL STMT [%s] ", sql_query_string);
+
+
+       _bind_stmt_field_data_int(hStmt, i++, task_id);
+       _bind_stmt_field_data_int(hStmt, i++, input_task_type);
+       _bind_stmt_field_data_int(hStmt, i++, EMAIL_TASK_STATUS_WAIT);
+       _bind_stmt_field_data_int(hStmt, i++, input_task_priority);
+       _bind_stmt_field_data_int(hStmt, i++, input_task_parameter_length);
+       _bind_stmt_field_data_blob(hStmt, i++, input_task_parameter, input_task_parameter_length);
+       _bind_stmt_field_data_int(hStmt, i++, time(NULL));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+
+       EM_DEBUG_DB_EXEC((rc == SQLITE_FULL), {err = EMAIL_ERROR_MAIL_MEMORY_FULL;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d, errmsg = %s.", rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = (err == EMAIL_ERROR_NONE);
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(input_transaction, ret, err);
+
+FINISH_OFF:
+
+       if (hStmt != NULL)  {
+               rc = sqlite3_finalize(hStmt);
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_LOG("sqlite3_finalize failed [%d]", rc);
+                       err = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+       else
+               EM_DEBUG_LOG("hStmt is NULL!!!");
+
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emstorage_delete_task(int task_id, int transaction)
+{
+       EM_DEBUG_FUNC_BEGIN("task_id[%d], transaction[%d]", task_id, transaction);
+       int rc, ret = false;
+       int err = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       sqlite3 *local_db_handle = NULL;
+
+       if (task_id < 0)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, err);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string), "DELETE FROM mail_task_tbl WHERE task_id = %d", task_id);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, err);
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emstorage_update_task_status(int task_id, email_task_status_type_t task_status, int transaction)
+{
+       EM_DEBUG_FUNC_BEGIN("task_id[%d] task_status[%d] transaction[%d]", task_id, task_status, transaction);
+       int rc, ret = false;
+       int err = EMAIL_ERROR_NONE;
+       char sql_query_string[QUERY_SIZE] = {0, };
+
+       sqlite3 *local_db_handle = emstorage_get_db_connection();
+
+       EMSTORAGE_START_WRITE_TRANSACTION(transaction, err);
+
+       SNPRINTF(sql_query_string, sizeof(sql_query_string),
+               "UPDATE mail_task_tbl SET"
+               " task_status = %d"
+               " WHERE task_id = %d"
+               , task_status
+               , task_id);
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_exec(local_db_handle, sql_query_string, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) exec fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       ret = true;
+
+FINISH_OFF:
+       EMSTORAGE_FINISH_WRITE_TRANSACTION(transaction, ret, err);
+       _DISCONNECT_DB;
+
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emstorage_query_task(const char *input_conditional_clause, const char *input_ordering_clause, email_task_t **output_task_list, int *output_task_count)
+{
+       EM_DEBUG_FUNC_BEGIN("input_conditional_clause[%p], input_ordering_clause [%p], output_task_list[%p], output_task_count[%d]", input_conditional_clause, input_ordering_clause, output_task_list, output_task_count);
+       int i = 0, count = 0, rc = -1;
+       int cur_query = 0;
+       int field_index = 0;
+       int err = EMAIL_ERROR_NONE;
+       email_task_t *task_item_from_tbl = NULL;
+       char sql_query_string[QUERY_SIZE] = {0, };
+       char *field_list = "task_id, task_type, task_status, task_priority, task_parameter_length, task_parameter ";
+       char **result;
+       sqlite3 *local_db_handle = NULL;
+       DB_STMT hStmt = NULL;
+
+       EM_IF_NULL_RETURN_VALUE(input_conditional_clause, false);
+       EM_IF_NULL_RETURN_VALUE(output_task_count, false);
+
+       local_db_handle = emstorage_get_db_connection();
+
+       SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, "SELECT COUNT(*) FROM mail_task_tbl %s", input_conditional_clause);
+       EM_DEBUG_LOG("emstorage_query_mail_list : query[%s].", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_get_table(local_db_handle, sql_query_string, &result, NULL, NULL, NULL), rc);
+       EM_DEBUG_DB_EXEC(SQLITE_OK != rc, {err = EMAIL_ERROR_DB_FAILURE;sqlite3_free_table(result);goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_get_table fail:%d -%s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       count = atoi(result[1]);
+       sqlite3_free_table(result);
+
+       EM_DEBUG_LOG("count = %d", rc);
+
+       if (count == 0) {
+               EM_DEBUG_EXCEPTION("no task found...");
+               err = EMAIL_ERROR_TASK_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF_OFFSET(sql_query_string, cur_query, QUERY_SIZE, "SELECT %s FROM mail_task_tbl %s %s", field_list, input_conditional_clause, input_ordering_clause);
+       EM_DEBUG_LOG("emstorage_query_mail_list : query[%s].", sql_query_string);
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_prepare_v2(local_db_handle, sql_query_string, EM_SAFE_STRLEN(sql_query_string), &hStmt, NULL), rc);
+
+       EM_DEBUG_LOG("After sqlite3_prepare_v2 hStmt = %p", hStmt);
+       EM_DEBUG_DB_EXEC((SQLITE_OK != rc), {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("SQL(%s) sqlite3_prepare fail:(%d) %s", sql_query_string, rc, sqlite3_errmsg(local_db_handle)));
+
+       EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+       EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+               ("sqlite3_step fail:%d", rc));
+
+       if (rc == SQLITE_DONE)  {
+               EM_DEBUG_EXCEPTION("no task found...");
+               err = EMAIL_ERROR_TASK_NOT_FOUND;
+               count = 0;
+               goto FINISH_OFF;
+       }
+
+       if (!(task_item_from_tbl = (email_task_t*)em_malloc(sizeof(email_task_t) * count))) {
+               EM_DEBUG_EXCEPTION("malloc for mail_list_item_from_tbl failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < count; i++)  {
+               /*  get recordset */
+               field_index = 0;
+
+               _get_stmt_field_data_int(hStmt, (int*)&(task_item_from_tbl[i].task_id), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(task_item_from_tbl[i].task_type), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(task_item_from_tbl[i].task_status), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(task_item_from_tbl[i].task_priority), field_index++);
+               _get_stmt_field_data_int(hStmt, (int*)&(task_item_from_tbl[i].task_parameter_length), field_index++);
+               _get_stmt_field_data_blob(hStmt, (void**)&(task_item_from_tbl[i].task_parameter), field_index++);
+
+               EMSTORAGE_PROTECTED_FUNC_CALL(sqlite3_step(hStmt), rc);
+               EM_DEBUG_LOG("after sqlite3_step(), i = %d, rc = %d.", i,  rc);
+               EM_DEBUG_DB_EXEC((rc != SQLITE_ROW && rc != SQLITE_DONE), {err = EMAIL_ERROR_DB_FAILURE;goto FINISH_OFF; },
+                       ("sqlite3_step fail:%d", rc));
+       }
+
+FINISH_OFF:
+       if (err == EMAIL_ERROR_NONE)  {
+               if (output_task_list)
+                       *output_task_list = task_item_from_tbl;
+               *output_task_count = count;
+       }
+       else
+               EM_SAFE_FREE(task_item_from_tbl);
+
+       if (hStmt != NULL)  {
+               EM_DEBUG_LOG("Before sqlite3_finalize hStmt = %p", hStmt);
+               rc = sqlite3_finalize(hStmt);
+               hStmt = NULL;
+               if (rc != SQLITE_OK)  {
+                       EM_DEBUG_EXCEPTION("sqlite3_finalize failed - %d", rc);
+                       err = EMAIL_ERROR_DB_FAILURE;
+               }
+       }
+
+       _DISCONNECT_DB;
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+/* Tasks --------------------------------------------------------------------------*/
+
+/*EOF*/
diff --git a/email-core/email-storage/include/email-storage.h b/email-core/email-storage/include/email-storage.h
new file mode 100755 (executable)
index 0000000..d59f6ef
--- /dev/null
@@ -0,0 +1,1528 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-storage.h
+ * Desc :  email-core Storage Library Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.07.28  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_STORAGE_H__
+#define __EMAIL_STORAGE_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include <sqlite3.h>
+#include <time.h>
+#include "email-types.h"
+#include "email-core-tasks.h"
+#include "email-internal-types.h"
+
+#define FIRST_ACCOUNT_ID    1
+
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+#define QUERY_SIZE          8192
+#define MAX_INTEGER_LENGTH  5  /*  32767 -> 5 bytes */
+
+typedef struct 
+{
+       int mail_id;
+       unsigned long server_mail_id;
+} email_id_set_t;
+
+#endif /* __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__ */
+
+
+typedef struct 
+{
+       /* Account information */
+       int                                account_id;                               /* Account id  */
+       char                              *account_name;                             /* Account name */
+       char                              *logo_icon_path;                           /* Account logo icon path */
+       int                                account_svc_id;                           /* Specifies id from account-svc */
+       int                                sync_status;                              /* Sync Status. SYNC_STATUS_FINISHED, SYNC_STATUS_SYNCING, SYNC_STATUS_HAVE_NEW_MAILS */
+       int                                sync_disabled;                            /* If this attriube is set as true, email-service will not synchronize this account. */
+       int                                default_mail_slot_size;
+
+       void                              *user_data;                                /* binary user data */
+       int                                user_data_length;                         /* user data length */
+
+       /* User information */
+       char                              *user_display_name;                        /* User's display name */
+       char                              *user_email_address;                       /* User's email address */
+       char                              *reply_to_address;                         /* Email address for reply */
+       char                              *return_address;                           /* Email address for error from server*/
+
+       /* Configuration for incoming server */
+       email_account_server_t             incoming_server_type;                     /* Incoming server type */
+       char                              *incoming_server_address;                  /* Incoming server address */
+       int                                incoming_server_port_number;              /* Incoming server port number */
+       char                              *incoming_server_user_name;                /* Incoming server user name */
+       char                              *incoming_server_password;                 /* Incoming server password */
+       int                                incoming_server_secure_connection;        /* Does incoming server requires secured connection? */
+
+       /* Options for incoming server */
+       email_imap4_retrieval_mode_t       retrieval_mode;                           /* Retrieval mode : EMAIL_IMAP4_RETRIEVAL_MODE_NEW or EMAIL_IMAP4_RETRIEVAL_MODE_ALL */
+       int                                keep_mails_on_pop_server_after_download;  /* Keep mails on POP server after download */
+       int                                check_interval;                           /* Specifies the interval for checking new mail periodically */
+       int                                auto_download_size;                       /* Specifies the size for auto download in bytes. -1 means entire mails body */
+
+       /* Configuration for outgoing server */
+       email_account_server_t             outgoing_server_type;
+       char                              *outgoing_server_address;
+       int                                outgoing_server_port_number;
+       char                              *outgoing_server_user_name;
+       char                              *outgoing_server_password;
+       int                                outgoing_server_secure_connection;        /* Does outgoing server requires secured connection? */
+       int                                outgoing_server_need_authentication;      /* Does outgoing server requires authentication? */
+       int                                outgoing_server_use_same_authenticator;   /* Use same authenticator for outgoing server */ /* flag2 */
+
+       /* Options for outgoing server */
+       email_option_t                     options;
+
+       /* Authentication Options */
+       int                                pop_before_smtp;                          /* POP before SMTP Authentication */
+       int                                incoming_server_requires_apop;            /* APOP authentication */
+
+       /* S/MIME Options */
+       email_smime_type                   smime_type;                               /* Sepeifies the smime type 0=Normal 1=Clear signed 2=encrypted 3=Signed + encrypted */
+       char                              *certificate_path;                         /* Sepeifies the certificate path of private*/
+       email_cipher_type                  cipher_type;                              /* Sepeifies the encryption algorithm*/
+       email_digest_type                  digest_type;                              /* Sepeifies the digest algorithm*/
+} emstorage_account_tbl_t;
+
+typedef struct 
+{
+       int certificate_id;
+       int issue_year;
+       int issue_month;
+       int issue_day;
+       int expiration_year;
+       int expiration_month;
+       int expiration_day;
+       char *issue_organization_name;
+       char *email_address;
+       char *subject_str;
+       char *filepath;
+       char *password;
+} emstorage_certificate_tbl_t;
+
+typedef struct 
+{
+       int   account_id;      /*  MUST BE '0'  :  currently, only global rule supported. */
+       int   rule_id;
+       int   type;            /*  from/subject/body  */
+       char *value;
+       int   action_type;     /*  move/block/delete  */
+       int   target_mailbox_id;    /*  destination mailbox  */
+       int   flag1;           /*  for rule ON/OFF */
+       int   flag2;           /*  For rule type INCLUDE/Exactly SAME AS */
+} emstorage_rule_tbl_t;
+
+/* mail_box_tbl table entity */
+typedef struct 
+{
+       int                   mailbox_id;
+       int                   account_id;
+       int                   local_yn;
+       char                 *mailbox_name;
+       email_mailbox_type_e  mailbox_type;
+       char                 *alias;
+       int                   modifiable_yn;              /*  whether mailbox is able to be deleted/modified */
+       int                   unread_count;               /*  Removed. 16-Dec-2010, count unread mails at the moment it is required. not store in the DB */
+       int                   total_mail_count_on_local;  /*  Specifies the total number of mails in the mailbox in the local DB. count unread mails at the moment it is required. not store in the DB */
+       int                   total_mail_count_on_server; /*  Specifies the total number of mails in the mailbox in the mail server */
+       int                   has_archived_mails;
+       int                   mail_slot_size;
+       int                   no_select;
+       time_t                last_sync_time;             /*  The last synchronization time */
+       int                   deleted_flag;               /*  whether mailbox is deleted */
+} emstorage_mailbox_tbl_t;
+
+/* mail_read_uid_tbl table entity */
+typedef struct 
+{
+       int     account_id;
+       int     mailbox_id;
+       int     local_uid;
+       char   *mailbox_name;   /*  server mailbox */
+       char   *s_uid;          /*  uid on server */
+       int     data1;          /*  rfc822 size */
+       char   *data2;
+       int     flag;           /*  rule id */
+       int     reserved;
+} emstorage_read_mail_uid_tbl_t;
+
+typedef struct 
+{
+       int                    mail_id;
+       int                    account_id;
+       int                    mailbox_id;
+       char                  *mailbox_name;
+       int                    mailbox_type;
+       char                  *subject;
+       time_t                 date_time;
+       int                    server_mail_status;
+       char                  *server_mailbox_name;
+       char                  *server_mail_id;
+       char                  *message_id;
+       int                    reference_mail_id;
+       char                  *full_address_from;
+       char                  *full_address_reply;
+       char                  *full_address_to;
+       char                  *full_address_cc;
+       char                  *full_address_bcc;
+       char                  *full_address_return;
+       char                  *email_address_sender;
+       char                  *email_address_recipient;
+       char                  *alias_sender;
+       char                  *alias_recipient;
+       int                    body_download_status;
+       char                  *file_path_plain;
+       char                  *file_path_html;
+       char                  *file_path_mime_entity;
+       int                    mail_size;
+       char                   flags_seen_field;
+       char                   flags_deleted_field;
+       char                   flags_flagged_field;
+       char                   flags_answered_field;
+       char                   flags_recent_field;
+       char                   flags_draft_field;
+       char                   flags_forwarded_field;
+       int                    DRM_status;
+       email_mail_priority_t  priority;
+       email_mail_status_t    save_status;
+       int                    lock_status;
+       email_mail_report_t    report_status;
+       int                    attachment_count;
+       int                    inline_content_count;
+       int                    thread_id;
+       int                    thread_item_count;
+       char                  *preview_text;
+       email_mail_type_t      meeting_request_status;
+       email_message_class    message_class;
+       email_digest_type      digest_type;
+       email_smime_type       smime_type;
+} emstorage_mail_tbl_t;
+
+/* mail_attachment_tbl entity */
+typedef struct 
+{
+       int   attachment_id;
+       char *attachment_name;
+       char *attachment_path;
+       int   attachment_size;
+       int   mail_id;
+       int   account_id;
+       int   mailbox_id;
+       int   attachment_save_status;              /* 1 : existing, 0 : not existing */
+       int   attachment_drm_type;                 /* 0 : none, 1 : object, 2 : rights, 3 : dcf */
+       int   attachment_drm_method;               /* 0 : none, 1 : FL, 2 : CD, 3 : SSD, 4 : SD */
+       int   attachment_inline_content_status;    /* 1 : inline content , 0 : not inline content */
+       char *attachment_mime_type;
+#ifdef __ATTACHMENT_OPTI__     
+       int   encoding;
+       char *section;  
+#endif 
+} emstorage_attachment_tbl_t;
+
+
+typedef enum {
+       RETRIEVE_ALL = 1,           /*  mail */
+       RETRIEVE_ENVELOPE,          /*  mail envelope */
+       RETRIEVE_SUMMARY,           /*  mail summary */
+       RETRIEVE_FIELDS_FOR_DELETE, /*  account_id, mail_id, server_mail_yn, server_mailbox, server_mail_id */
+       RETRIEVE_ACCOUNT,           /*  account_id */
+       RETRIEVE_FLAG,              /*  mailbox, flag1, thread_id */
+       RETRIEVE_ID,                /*  mail_id */
+       RETRIEVE_ADDRESS,           /*  mail_id, contact_info */
+} emstorage_mail_field_type_t;
+
+typedef struct _emstorage_search_filter_t {
+       char *key_type;
+       char *key_value;
+       struct _emstorage_search_filter_t *next;
+} emstorage_search_filter_t;
+
+typedef enum {
+       EMAIL_CREATE_DB_NORMAL = 0, 
+       EMAIL_CREATE_DB_CHECK, 
+} emstorage_create_db_type_t;
+
+
+/*****************************************************************************
+                                                               etc
+*****************************************************************************/
+#define MAX_PW_FILE_NAME_LENGTH                   128 /*  password file name for secure storage */
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+
+typedef enum
+{
+ ACTIVITY_FETCHIMAPFOLDER = 1,  /* Fetch Mail server Activity */
+ ACTIVITY_DELETEMAIL,                  /* Delete Mail Activity */              
+ ACTIVITY_MODIFYFLAG,                  /* Modify Mail flag Activity */         
+ ACTIVITY_MODIFYSEENFLAG,              /* Modify Mail seen flag Activity */
+ ACTIVITY_MOVEMAIL,                            /* Move Mail Activity */
+ ACTIVITY_DELETEALLMAIL,               /* Delete All Mails activity */
+ ACTIVITY_COPYMAIL,                            /* Copy Mail Activity */
+ ACTIVITY_SAVEMAIL,                            /* Save Mail activity */
+ ACTIVITY_DELETEMAIL_SEND,             /* New Delete Mail Activity added to be processed by send thread */
+}eActivity_type;
+
+
+/**
+ * emstorage_activity_tbl_t - Email Local activity Structure
+ *
+ */
+typedef struct
+{
+       int activity_id;                                /* Activity ID */
+       int account_id;                          /* Account ID */
+       int mail_id;                             /* Mail ID    */
+       int activity_type;    /* Local Activity Type */
+       char *server_mailid;                 /* Server Mail ID or Mailbox name */
+       char *src_mbox;                          /* Source Mailbox in case of mail_move */      
+       char *dest_mbox;                 /* Destination Mailbox name in case of Mail move operation */
+
+} emstorage_activity_tbl_t;
+
+#endif
+
+INTERNAL_FUNC int emstorage_shm_file_init(const char *shm_file_name);
+
+
+/************** Database Management ***************/
+/*
+ * em_db_open
+ * description  :  open db and register busy handler
+ */
+INTERNAL_FUNC int em_db_open(sqlite3 **sqlite_handle, int *err_code);
+
+/*
+ * emstorage_db_open
+ *
+ * description :  open db and set global variable sqlite_emmb 
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC sqlite3* emstorage_db_open(int *err_code);
+
+/*
+ * emstorage_db_close
+ *
+ * description :  close db with global variable sqlite_emmb
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_db_close(int *err_code);
+
+/*
+ * emstorage_open
+ *
+ * description :  initialize storage manager
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_open(int *err_code);
+
+/*
+ * emstorage_close
+ *
+ * description :  cleanup storage manager
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_close(int *err_code);
+
+/*
+ * emstorage_create_table
+ *
+ * description :  create account/address table in database.
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_create_table(emstorage_create_db_type_t type, int *err_code);
+
+
+/**
+ * Check whether there is the same account information in the db
+ *
+ * @param[in] account  account that 
+ * @param[in] transaction      If the argument is true, engine commits transaction or executes rollback.
+ * @param[out] err_code        Error code.
+ * @remarks N/A
+ * @return This function returns true if there is no duplicated account. returns false and set error code if there are duplicated accounts or error 
+ */
+INTERNAL_FUNC int emstorage_check_duplicated_account(email_account_t *account, int transaction, int *err_code);
+
+
+/**
+ * Get number of accounts from account table.
+ *
+ * @param[out] count           The number of accounts is saved here.
+ * @param[in] transaction      If the argument is true, engine commits transaction or executes rollback.
+ * @remarks N/A
+ * @return This function returns 0 on success or error code on failure.
+ */
+INTERNAL_FUNC int emstorage_get_account_count(int *count, int transaction, int *err_code);
+
+/**
+ * Get account from account table.
+ *
+ * @param[in, out] select_num  Upon entry, the argument contains the number of accounts to select.
+                                   Upon exit, it is set to the number of accounts to been selected.
+ * @param[out] account_list            The selected accounts is saved here. this pointer must be freed after being used.
+ * @param[in] transaction              If the argument is true, engine commits transaction or executes rollback.
+ * @remarks N/A
+ * @return This function returns 0 on success or error code on failure.
+ */
+INTERNAL_FUNC int emstorage_get_account_list(int *select_num, emstorage_account_tbl_t **account_list, int transaction, int with_password, int *err_code);
+
+/*
+ * emstorage_get_account_by_name
+ *
+ * description :  get account from account table by account name
+ * arguments : 
+ *    db  :  database pointer
+ *    account_id  :  account id
+ *    pulloption  :  option to specify fetching full or partial data
+ *    account  :  buffer to hold selected account
+ *              this buffer must be free after it has been used.
+ * return  : 
+ */
+/* sowmya.kr, 281209 Adding signature to options in email_account_t changes */
+
+INTERNAL_FUNC int emstorage_get_account_by_id(int account_id, int pulloption, emstorage_account_tbl_t **account, int transaction, int *err_code);
+
+
+/*
+ * emstorage_get_password_length_of_account
+ *
+ * description: get password length of account.
+ * arguments:
+ *    account_id : account id
+ *    password_length : password length
+ * return :
+ */
+
+INTERNAL_FUNC int emstorage_get_password_length_of_account(int account_id, int *password_length, int* err_code);
+
+/*
+ * emstorage_update_account
+ *
+ * description :  change a account from account table
+ * arguments : 
+ *    account_id  :  account id
+ *    account  :  buffer to hold selected account
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_update_account(int account_id, emstorage_account_tbl_t *account, int transaction, int *err_code);
+
+
+INTERNAL_FUNC int emstorage_set_field_of_accounts_with_integer_value(int account_id, char *field_name, int value, int transaction);
+
+/*
+ * emstorage_get_sync_status_of_account
+ *
+ * description :  get a sync status field from account table
+ * arguments : 
+ *    account_id  :  account id
+ *    result_sync_status : sync status value
+ * return  : 
+ */
+
+INTERNAL_FUNC int emstorage_get_sync_status_of_account(int account_id, int *result_sync_status,int *err_code);
+
+/*
+ * emstorage_update_sync_status_of_account
+ *
+ * description :  update a sync status field from account table
+ * arguments : 
+ *    account_id  :  account id
+ *    set_operator  :  set operater. refer email_set_type_t
+ *    sync_status : sync status value
+ * return  : 
+ */
+
+INTERNAL_FUNC int emstorage_update_sync_status_of_account(int account_id, email_set_type_t set_operator, int sync_status, int transaction, int *err_code);
+
+/*
+ * emstorage_add_account
+ *
+ * description :  add a account to account table
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_add_account(emstorage_account_tbl_t *account, int transaction, int *err_code);
+
+/*
+ * emstorage_delete_account
+ *
+ * description :  delete a account from account table
+ * arguments : 
+ *    db  :  database pointer
+ *    account_id  :  account id to be deteted
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_account(int account_id, int transaction, int *err_code);
+
+/*
+ * emstorage_free_account
+ *
+ * description :  free local accout memory
+ * arguments : 
+ *    account_list  :  double pointer
+ *    count  :  count of local account
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_free_account(emstorage_account_tbl_t **account_list, int count, int *err_code);
+
+
+/************** Mailbox(Local box And Imap mailbox) Management ******************/
+
+/*
+ * emstorage_get_mailbox_count
+ *
+ * description :  get number of mailbox from local mailbox table
+ * arguments : 
+ *    db  :  database pointer
+ *    count  :  number of accounts
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_mailbox_count(int account_id, int local_yn, int *count, int transaction, int *err_code);
+
+/*
+ * emstorage_get_mailbox
+ *
+ * description :  get local mailbox from local mailbox table
+ * arguments : 
+ *    db  :  database pointer
+ *    sort_type         :      in - sorting type.
+ *    select_num        :      in - number of selected account
+ *                             out - number to been selected
+ *    mailbox_list      :      buffer to hold selected account
+ *                     this buffer must be free after it has been used.
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_mailbox_list(int account_id, int local_yn, email_mailbox_sort_type_t sort_type, int *select_num, emstorage_mailbox_tbl_t **mailbox_list,  int transaction, int *err_code);
+
+/*
+ * emstorage_get_child_mailbox_list
+ *
+ * description :  get child mailbox list  from given  mailbox 
+ * arguments : 
+ *    account_id  :  in - account id
+ *    parent_mailbox_name  :  in - parent_mailbox_name to fetch child list
+ *    local_yn - in - local mailbox or not
+ *    select_num - out   :  count of mailboxes
+ *    mailbox_list - out  :    list of mailboxes        
+ *    err_code - out  :  error code, if any
+ */
+
+
+INTERNAL_FUNC int emstorage_get_child_mailbox_list(int account_id, char *parent_mailbox_name, int *select_num, emstorage_mailbox_tbl_t **mailbox_list, int transaction, int *err_code);
+
+/*
+ * emstorage_get_mailbox_by_name
+ *
+ * description :  get local mailbox from local mailbox table by mailbox name
+ * arguments : 
+ *    db  :  database pointer
+ *    mailbox_name  :  mailbox name
+ *    mailbox  :  buffer to hold selected local mailbox
+ *              this buffer must be free after it has been used.
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_mailbox_by_name(int account_id, int local_yn, char *mailbox_name, emstorage_mailbox_tbl_t **mailbox, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, emstorage_mailbox_tbl_t **mailbox, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_get_mailbox_by_id(int input_mailbox_id, emstorage_mailbox_tbl_t** output_mailbox);
+INTERNAL_FUNC int emstorage_get_mailbox_list_ex(int account_id, int local_yn, int with_count, int *select_num, emstorage_mailbox_tbl_t **mailbox_list, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_get_mailbox_id_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, int *mailbox_id, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_get_mailbox_name_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type, char **mailbox_name, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_update_mailbox_modifiable_yn(int account_id, int local_yn, char *mailbox_name, int modifiable_yn, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_update_mailbox_total_count(int account_id, int input_mailbox_id, int total_count_on_server, int transaction, int *err_code);
+
+
+/*
+ * emstorage_update_mailbox
+ *
+ * description :  change a account from account table
+ * arguments : 
+ *    db  :  database pointer
+ *    mailbox_name  :  mailbox name
+ *    mailbox  :  buffer to hold selected local mailbox
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_update_mailbox(int account_id, int local_yn, int input_mailbox_id, emstorage_mailbox_tbl_t *mailbox, int transaction, int *err_code);
+
+/*
+ * emstorage_update_mailbox_type
+ *
+ * description :  change a mailbox from mailbox tbl
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_update_mailbox_type(int account_id, int local_yn, char *mailbox_name, email_mailbox_type_e new_mailbox_type, int transaction, int *err_code);
+
+/*
+ * emstorage_set_local_mailbox
+ *
+ * description :  change 'local' field on mailbox table.
+ * arguments :
+ * return  :
+ */
+INTERNAL_FUNC int emstorage_set_local_mailbox(int input_mailbox_id, int input_is_local_mailbox, int transaction);
+
+INTERNAL_FUNC int emstorage_set_field_of_mailbox_with_integer_value(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, char *input_field_name, int input_value, int transaction);
+
+/*
+ * emstorage_add_mailbox
+ *
+ * description :  add a local mailbox to local mailbox table
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_add_mailbox(emstorage_mailbox_tbl_t *mailbox, int transaction, int *err_code);
+
+/*
+ * emstorage_delete_mailbox
+ *
+ * description :  delete a local mailbox from local mailbox table
+ * arguments : 
+ *    db  :  database pointer
+ *    mailbox_name  :  mailbox name of record to be deteted
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_mailbox(int account_id, int local_yn, int input_mailbox_id, int transaction, int *err_code);
+
+INTERNAL_FUNC int emstorage_rename_mailbox(int input_mailbox_id, char *input_new_mailbox_path, char *input_new_mailbox_alias, int input_transaction);
+INTERNAL_FUNC int emstorage_get_overflowed_mail_id_list(int account_id, int input_mailbox_id, int mail_slot_size, int **mail_id_list, int *mail_id_count, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_set_mail_slot_size(int account_id, int mailbox_id, int new_slot_size, int transaction, int *err_code);
+
+INTERNAL_FUNC int emstorage_set_all_mailbox_modifiable_yn(int account_id, int modifiable_yn, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_get_mailbox_by_modifiable_yn(int account_id, int modifiable_yn, int *select_num, emstorage_mailbox_tbl_t **mailbox_list, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_stamp_last_sync_time_of_mailbox(int input_mailbox_id, int input_transaction);
+
+/*
+ * emstorage_free_mailbox
+ *
+ * description :  free local mailbox memory
+ * arguments : 
+ *    mailbox_list  :  double pointer
+ *    count  :  count of local mailbox
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_free_mailbox(emstorage_mailbox_tbl_t **mailbox_list, int count, int *err_code);
+
+
+/************** Read Mail UID Management ******************/
+
+
+
+INTERNAL_FUNC int emstorage_get_count_read_mail_uid(int account_id, char *mailbox_name, int *count, int transaction, int *err_code);
+
+
+/*
+ * emstorage_check_read_mail_uid
+ *
+ * description :  check that this uid exists in uid table
+ * arguments : 
+ *    db  :  database pointer
+ *    mailbox_name  :  mailbox name
+ *    s_uid  :  uid string to be checked
+ *    exist  :  variable to hold checking result. (0 : not exist, 1 : exist)
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_check_read_mail_uid(int account_id, char *mailbox_name, char *uid, int *exist, int transaction, int *err_code);
+
+/*
+ * emstorage_get_read_mail_size
+ *
+ * description :  get mail size from read mail uid
+ * arguments : 
+ *    db  :  database pointer
+ *    mailbox_id  :  local mailbox id
+ *    local_uid  :  mail uid of local mailbox
+ *    mailbox_name  :  server mailbox name
+ *    uid  :  mail uid string of server mail
+ *    read_mail_uid  :  variable to hold read mail uid information
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_downloaded_list(int account_id, int mailbox_id, emstorage_read_mail_uid_tbl_t **read_mail_uid, int *count, int transaction, int *err_code);
+
+INTERNAL_FUNC int emstorage_get_downloaded_mail(int mail_id, emstorage_mail_tbl_t **mail, int transaction, int *err_code);
+
+/*
+ * emstorage_get_read_mail_size
+ *
+ * description :  get mail size from read mail uid
+ * arguments : 
+ *    db  :  database pointer
+ *    mailbox_name  :  mailbox name
+ *    s_uid  :  mail uid string
+ *    size  :  variable to hold mail size
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_downloaded_mail_size(int account_id, char *local_mbox, int local_uid, char *mailbox_name, char *uid, int *mail_size, int transaction, int *err_code);
+
+/*
+ * emstorage_add_downloaded_mail
+ *
+ * description :  add read mail uid
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_add_downloaded_mail(emstorage_read_mail_uid_tbl_t *read_mail_uid, int transaction, int *err_code);
+
+/*
+ * emstorage_change_read_mail_uid
+ *
+ * description :  modify read mail uid
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_change_read_mail_uid(int account_id, int local_mailbox_id, int local_uid, char *mailbox_name, char *uid,
+                                    emstorage_read_mail_uid_tbl_t *read_mail_uid, int transaction, int *err_code);
+
+/*
+ * emstorage_remove_downloaded_mail
+ *
+ * description :  
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_remove_downloaded_mail(int account_id, char *mailbox_name, char *uid, int transaction, int *err_code);
+
+
+INTERNAL_FUNC int emstorage_update_read_mail_uid(int mail_id, char *new_server_uid, char *mbox_name, int *err_code);
+
+/*
+ *  free memroy
+ */
+INTERNAL_FUNC int emstorage_free_read_mail_uid(emstorage_read_mail_uid_tbl_t **read_mail_uid, int count, int *err_code);
+
+
+
+/************** Rules(Filtering) Management ******************/
+
+/*
+ * emstorage_get_rule_count
+ *
+ * description :  get number of rules from rule table
+ * arguments : 
+ *    db  :  database pointer
+ *    count  :  number of accounts
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_rule_count(int account_id, int *count, int transaction, int *err_code);
+
+/*
+ * emstorage_get_rule
+ *
+ * description :  get rules from rule table
+ * arguments : 
+ *    db  :  database pointer
+ *    start_idx  :  the first index to be selected (min : 0)
+ *    select_num  :  in - number of selected account
+ *                 out - number to been selected
+ *    is_completed  :  is completed ? 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_rule(int account_id, int type, int start_idx, int *select_num, int *is_completed, emstorage_rule_tbl_t **rule_list, int transaction, int *err_code);
+
+/*
+ * emstorage_get_rule
+ *
+ * description :  get rules from rule table
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_rule_by_id(int account_id, int rule_id, emstorage_rule_tbl_t **rule, int transaction, int *err_code);
+
+/*
+ * emstorage_change_rule
+ *
+ * description :  change a account from account table
+ * arguments : 
+ *    db  :  database pointer
+ *    mailbox_name  :  mailbox name
+ *    rule  :  buffer to hold selected rule
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_change_rule(int account_id, int rule_id, emstorage_rule_tbl_t *rule, int transaction, int *err_code);
+
+/*
+ * emstorage_find_rule
+ *
+ * description :  find a rule already exists
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_find_rule(emstorage_rule_tbl_t *rule, int transaction, int *err_code);
+
+/*
+ * emstorage_add_rule
+ *
+ * description :  add a rule to rule table
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_add_rule(emstorage_rule_tbl_t *rule, int transaction, int *err_code);
+
+/*
+ * emstorage_delete_rule
+ *
+ * description :  delete a rule from rule table
+ * arguments : 
+ *    db  :  database pointer
+ *    rule  :  rule to be deteted
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_rule(int account_id, int rule_id, int transaction, int *err_code);
+
+/*
+ * emstorage_free_rule
+ *
+ * description :  free rule memory
+ * arguments : 
+ *    count  :  count of rule
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_free_rule(emstorage_rule_tbl_t **rule_list, int count, int *err_code);
+
+
+/************** Mail Management ******************/
+
+/*
+ * emstorage_get_mail_count
+ *
+ * description :  get mail total and unseen count from mail table
+ * arguments : 
+ *    total  :  total count
+ *    unseen  :  unseen mail count
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_mail_count(int account_id, const char *mailbox, int *total, int *unseen, int transaction, int *err_code);
+
+/*
+ * emstorage_get_mail_by_id
+ *
+ * description :  get mail from mail table by mail id
+ * arguments : 
+ *    mail_id  :  mail id
+ *    mail  :  double pointer to hold mail
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_mail_by_id(int mail_id, emstorage_mail_tbl_t **mail, int transaction, int *err_code);
+
+/*
+ * emstorage_get_mail
+ *
+ * description :  get mail from mail table by mail sequence
+ * arguments : 
+ *    account_id  :  account id
+ *    mailbox  :  mailbox name
+ *    mail_no  :  mail sequence number (not mail id)
+ *    mail  :  double pointer to hold mail
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_mail_field_by_id(int mail_id, int type, emstorage_mail_tbl_t **mail, int transaction, int *err_code);
+
+/*
+ * emstorage_get_mail_field_by_multiple_mail_id
+ *
+ * description :  
+ * arguments : 
+ *    mail_ids  : 
+ *    number_of_mails  :  
+ *    type  :  
+ *    mail  :  
+ *    transaction :
+ *    err_code :
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_mail_field_by_multiple_mail_id(int mail_ids[], int number_of_mails, int type, emstorage_mail_tbl_t** mail, int transaction, int *err_code);
+
+/*
+ * emstorage_query_mail_count
+ *
+ * description :  query mail count
+ */
+INTERNAL_FUNC int emstorage_query_mail_count(const char *input_conditional_clause, int input_transaction, int *output_total_mail_count, int *output_unseen_mail_count);
+
+/*
+ * emstorage_query_mail_list
+ *
+ * description :  query mail id list
+ */
+INTERNAL_FUNC int emstorage_query_mail_id_list(const char *input_conditional_clause, int input_transaction, int **output_mail_id_list, int *output_mail_id_count);
+
+/*
+ * emstorage_query_mail_list
+ *
+ * description :  query mail list information
+ */
+INTERNAL_FUNC int emstorage_query_mail_list(const char *conditional_clause, int transaction, email_mail_list_item_t** result_mail_list,  int *result_count,  int *err_code);
+
+/*
+ * emstorage_query_mail_tbl
+ *
+ * description :  query mail table information
+ */
+INTERNAL_FUNC int emstorage_query_mail_tbl(const char *conditional_clause, int transaction, emstorage_mail_tbl_t** result_mail_tbl, int *result_count, int *err_code);
+
+/*
+ * emstorage_query_mailbox_tbl
+ *
+ * description :  query mail box table information
+ */
+
+INTERNAL_FUNC int emstorage_query_mailbox_tbl(const char *input_conditional_clause, const char *input_ordering_clause, int input_get_mail_count,  int input_transaction, emstorage_mailbox_tbl_t **output_mailbox_list, int *output_mailbox_count);
+
+/*
+ * emstorage_get_mail_list
+ *
+ * description :  search mail list information
+ */
+
+INTERNAL_FUNC int emstorage_get_mail_list(int account_id, int mailbox_id, email_email_address_list_t* addr_list, int thread_id, int start_index, int limit_count, int search_type, const char *search_value, email_sort_type_t sorting, int transaction, email_mail_list_item_t** mail_list,  int *result_count,  int *err_code);
+/*
+ * emstorage_get_mails
+ *
+ * description :  search mail list information
+ */
+INTERNAL_FUNC int emstorage_get_mails(int account_id, int mailbox_id, email_email_address_list_t* addr_list, int thread_id, int start_index, int limit_count, email_sort_type_t sorting,  int transaction, emstorage_mail_tbl_t** mail_list, int *result_count, int *err_code);
+INTERNAL_FUNC int emstorage_get_searched_mail_list(int account_id, int mailbox_id, int thread_id, int search_type, const char *search_value, int start_index, int limit_count, email_sort_type_t sorting, int transaction, email_mail_list_item_t **mail_list,  int *result_count,  int *err_code);
+INTERNAL_FUNC int emstorage_get_maildata_by_servermailid(int account_id, char *server_mail_id, emstorage_mail_tbl_t **mail, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_get_latest_unread_mailid(int account_id, int *mail_id, int *err_code);
+
+
+/**
+ * Prepare mail search.
+ *
+ * @param[in] search                   Specifies the searching condition.
+ * @param[in] account_id               Specifies the account id. if 0, all accounts.
+ * @param[in] mailbox                  Specifies the mailbox name. if NULL, all mailboxes.
+ * @param[in] sorting                  Specifies the sorting condition.
+ * @param[out] search_handle   the searching handle is saved here.
+ * @param[out] searched                        the result count is saved here.
+ * @remarks N/A
+ * @return This function returns 0 on success or error code on failure.
+ */
+INTERNAL_FUNC int emstorage_mail_search_start(emstorage_search_filter_t *search, int account_id, char *mailbox, int sorting, int *search_handle, int *searched, int transaction, int *err_code);
+
+/*
+ * emstorage_mail_search_result
+ *
+ * description :  retrieve mail as searching result
+ * arguments : 
+ *    search_handle  :  handle to been gotten from emstorage_mail_search_start
+ *    mail  :  double pointer to hold mail
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_mail_search_result(int search_handle, emstorage_mail_field_type_t type, void **data, int transaction, int *err_code);
+
+/*
+ * emstorage_mail_search_end
+ *
+ * description :  finish searching
+ * arguments : 
+ *    search_handle  :  handle to be finished
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_mail_search_end(int search_handle, int transaction, int *err_code);
+
+
+
+/*
+ * emstorage_set_field_of_mails_with_integer_value
+ *
+ * description       :  update a filed of mail
+ * arguments : 
+ *    account_id                :  Specifies the account id. 
+ *    mail_ids       :  mail id list to be changed
+ *    mail_ids_count :  count of mail list
+ *    field_name     :  specified field name
+ *    value          :  specified value
+ * return       : 
+ */
+INTERNAL_FUNC int emstorage_set_field_of_mails_with_integer_value(int account_id, int mail_ids[], int mail_ids_count, char *field_name, int value, int transaction, int *err_code);
+
+/*
+ * emstorage_change_mail_field
+ *
+ * description :  update partial mail data
+ * arguments : 
+ *    mail_id  :  mail id
+ *    type  :  changing type
+ *    mail  :  mail pointer
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_change_mail_field(int mail_id, email_mail_change_type_t type, emstorage_mail_tbl_t *mail, int transaction, int *err_code);
+
+/*
+ * emstorage_increase_mail_id
+ *
+ * description :  increase unique mail id
+ * arguments : 
+ *    mail_id  :  pointer to store the unique id
+ * return  : 
+ */
+
+/*
+ * emstorage_change_mail
+ *
+ * description :  update mail
+ * arguments : 
+ *    mail_id  :  mail id to be changed
+ *    mail  :  mail pointer
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_change_mail(int mail_id, emstorage_mail_tbl_t *mail, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_clean_save_status(int save_status, int  *err_code);
+INTERNAL_FUNC int emstorage_update_server_uid(char *old_server_uid, char *new_server_uid, int *err_code);
+INTERNAL_FUNC int emstorage_modify_mailbox_of_mails(char *old_mailbox_name, char *new_mailbox_name, int transaction, int *err_code);
+
+INTERNAL_FUNC int emstorage_increase_mail_id(int *mail_id, int transaction, int *err_code);
+
+/*
+ * emstorage_add_mail
+ *
+ * description :  add a mail to mail table
+ * arguments : 
+ *    mail  :  mail pointer to be inserted
+ *   get_id :  must get uinque id in function
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_add_mail(emstorage_mail_tbl_t *mail, int get_id, int transaction, int *err_code);
+
+/*
+ * emstorage_move_multiple_mails_on_db
+ *
+ * description :
+ * arguments : 
+ *    account_id  :  
+ *   input_mailbox_id :
+ *   mail_ids :
+ *   number_of_mails :
+ *   transaction :
+ *   err_code :
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_move_multiple_mails_on_db(int account_id, int input_mailbox_id, int mail_ids[], int number_of_mails, int transaction, int *err_code);
+
+/*
+ * emstorage_delete_mail
+ *
+ * description :  delete mail from mail table
+ * arguments : 
+ *    mail_id  :  mail id to be deleted. if 0, all mail will be deleted.
+ *    from_server  :  delete mail on server.
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_mail(int mail_id, int from_server, int transaction, int *err_code);
+
+/*
+ * emstorage_delete_mail_by_account
+ *
+ * description :  delete mail from mail table by account id
+ * arguments : 
+ *    account_id  :  account id.
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_mail_by_account(int account_id, int transaction, int *err_code);
+
+/*
+ * emstorage_delete_mail
+ *
+ * description :  delete mail from mail table
+ * arguments : 
+ *    account_id  :  account id.
+ *    mailbox  :  mail box
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_mail_by_mailbox(int account_id, char *mailbox, int transaction, int *err_code);
+
+/*
+ * emstorage_delete_multiple_mails
+ *
+ * description :  
+ * arguments : 
+ *    mail_ids  :
+ *    number_of_mails  :
+ *    transaction  :
+ *    err_code  :
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_multiple_mails(int mail_ids[], int number_of_mails, int transaction, int *err_code);
+
+/*
+ * emstorage_free_mail
+ *
+ * description :  free memory
+ * arguments : 
+ *    mail_list  :  mail array
+ *    count  :  the number of array element
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_free_mail(emstorage_mail_tbl_t **mail_list, int count, int *err_code);
+
+/*
+ * emstorage_get_attachment
+ *
+ * description :  get attachment from attachment table
+ * arguments : 
+ *    mail_id  :  mail id
+ *    no  :  attachment sequence
+ *    attachment  :  double pointer to hold attachment data
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_attachment_count(int mail_id, int *count, int transaction, int *err_code);
+
+/*
+ * emstorage_get_attachment_list
+ *
+ * description :  get attachment list from attachment table
+ * arguments : 
+ *    input_mail_id           : mail id
+ *    input_transaction       : transaction option
+ *    attachment_list         : result attachment list
+ *    output_attachment_count : result attachment count
+ * return  : This function returns EMAIL_ERROR_NONE on success or error code (refer to EMAIL_ERROR__XXX) on failure.
+ *    
+ */
+INTERNAL_FUNC int emstorage_get_attachment_list(int input_mail_id, int input_transaction, emstorage_attachment_tbl_t** output_attachment_list, int *output_attachment_count);
+
+
+/*
+ * emstorage_get_attachment
+ *
+ * description :  get attachment from attachment table
+ * arguments : 
+ *    attachment_id  :  attachment id
+ *    attachment  :  double pointer to hold attachment data
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_attachment(int attachment_id, emstorage_attachment_tbl_t **attachment, int transaction, int *err_code);
+
+/*
+ * emstorage_get_attachment
+ *
+ * description :  get nth-attachment from attachment table
+ * arguments : 
+ *    mail_id  :  mail id
+ *    nth  :  index of the desired attachment (min : 1)
+ *    attachment  :  double pointer to hold attachment data
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_attachment_nth(int mail_id, int nth, emstorage_attachment_tbl_t **attachment, int transaction, int *err_code);
+
+/*
+ * emstorage_change_attachment_field
+ *
+ * description :  update partial mail attachment data
+ * arguments : 
+ *    mail_id  :  mail id
+ *    type  :  changing type
+ *    mail  :  mail pointer
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_change_attachment_field(int mail_id, email_mail_change_type_t type, emstorage_attachment_tbl_t *attachment, int transaction, int *err_code);
+
+/* Get new attachment id */
+/*
+ * emstorage_get_new_attachment_no
+ *
+ * description :  Get new attachment id
+ * arguments : 
+ *    attachment_no  :  attachment id pointer
+ * return  : 
+ */
+
+INTERNAL_FUNC int emstorage_get_new_attachment_no(int *attachment_no, int *err_code);
+
+/* insert attachment to mail attachment table */
+/*
+ * emstorage_add_attachment
+ *
+ * description :  insert a attachment to attachment table
+ * arguments : 
+ *    attachment  :  attachment pointer
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_add_attachment(emstorage_attachment_tbl_t *attachment, int iscopy, int transaction, int *err_code);
+
+
+INTERNAL_FUNC int emstorage_update_attachment(emstorage_attachment_tbl_t *attachment, int transaction, int *err_code);
+
+/* delete a mail from mail table */
+/*
+ * emstorage_delete_attachment_on_db
+ *
+ * description :  delete attachment from attachment table
+ * arguments : 
+ *    attachment_id  :  attachment id
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_attachment_on_db(int attachment_id, int transaction, int *err_code);
+
+INTERNAL_FUNC int emstorage_delete_all_attachments_of_mail(int mail_id, int transaction, int *err_code);
+
+/*
+ * emstorage_delete_attachment_all_on_db
+ *
+ * description :  delete attachment from mail table
+ * arguments : 
+ *    account_id  :  account id.
+ *    mailbox  :  mail box
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_attachment_all_on_db(int account_id, char *mailbox, int transaction, int *err_code);
+
+/*
+ * emstorage_free_attachment
+ *
+ * description :  free memory
+ * arguments : 
+ *    mail_list  :  mail array
+ *    count  :  the number of array element
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_free_attachment(emstorage_attachment_tbl_t **attachment_list, int count, int *err_code);
+
+INTERNAL_FUNC int emstorage_is_mailbox_full(int account_id, email_mailbox_t *mailbox, int *result, int *err_code);
+
+INTERNAL_FUNC int emstorage_get_max_mail_count();
+
+INTERNAL_FUNC int emstorage_mail_get_total_diskspace_usage(unsigned long *total_usage,  int transaction, int *err_code);
+
+
+/**
+ * begin a transaction.
+ *
+ * @param[in] d1       Reserved.
+ * @param[in] d2       Reserved.
+ * @remarks emstorage_commit_transaction or emstorage_commit_transaction must be called after this function.
+ * @return This function returns 0 on success or error code on failure.
+ */
+
+INTERNAL_FUNC int emstorage_begin_transaction(void *d1, void *d2, int *err_code);
+
+/**
+ * commit a transaction.
+ *
+ * @param[in] d1       Reserved.
+ * @param[in] d2       Reserved.
+ * @remarks N/A
+ * @return This function returns 0 on success or error code on failure.
+ */
+INTERNAL_FUNC int emstorage_commit_transaction(void *d1, void *d2, int *err_code);
+
+/**
+ * rollback db.
+ *
+ * @param[in] d1       Reserved.
+ * @param[in] d2       Reserved.
+ * @remarks N/A
+ * @return This function returns 0 on success or error code on failure.
+ */
+INTERNAL_FUNC int emstorage_rollback_transaction(void *d1, void *d2, int *err_code);
+
+/**
+ * clear mail data from db.
+ *
+ * @param[in]  transaction     
+ * @param[out] err_code        
+ * @remarks N/A
+ * @return This function returns 0 on success or error code on failure.
+ */
+
+INTERNAL_FUNC int emstorage_clear_mail_data(int transaction, int *err_code);
+
+
+INTERNAL_FUNC char *emstorage_make_directory_path_from_file_path(char *file_name);
+
+/*
+ * emstorage_get_save_name
+ *
+ * description :  get file name for saving data
+ * arguments : 
+ *    account_id  :  account id
+ *    mail_id  :  mail id
+ *    atch_id  :  attachment id
+ *    fname  :  file name
+ *    name_buf  :  buffer to hold file name. (MAX : 512Bytes)
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_save_name(int account_id, int mail_id, int atch_id, char *fname, char *name_buf, int *err_code);
+
+/*
+ * emstorage_get_dele_name
+ *
+ * description :  get a name for deleting contents from file system.
+ * arguments : 
+ *    account_id  :  account id
+ *    mail_id  :  mail id
+ *    atch_id  :  attachment id
+ *    fname  :  reserved
+ *    name_buf  :  buffer to hold file name. (MAX : 512Bytes)
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_get_dele_name(int account_id, int mail_id, int atch_id, char *fname, char *name_buf, int *err_code);
+
+/*
+ * emstorage_create_dir
+ *
+ * description :  create directory
+ * arguments : 
+ *    name_buf  :  buffer to hold file name. (MAX : 512Bytes)
+ *    no  :  attachment no.
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_create_dir(int account_id, int mail_id, int atch_id, int *err_code);
+
+/*
+ * emstorage_copy_file
+ *
+ * description :  copy a attachment file
+ * arguments : 
+ *    src_file  :  source file
+ *    dst_file  :  destination file
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_copy_file(char *src_file, char *dst_file, int sync_file, int *err_code);
+
+/*
+ * emstorage_move_file
+ *
+ * description :  move a file
+ * arguments : 
+ *    src_file  :  source file
+ *    dst_file  :  destination file
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_move_file(char *src_file, char *dst_file, int sync_status, int *err_code);
+
+/*
+ * emstorage_move_file
+ *
+ * description :  delete a file
+ * arguments : 
+ *    src_file  :  file to be deleted
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_file(char *src_file, int *err_code);
+
+/*
+ * emstorage_delete_dir
+ *
+ * description :  delete a directory
+ * arguments : 
+ *    src_dir  :  directory to be deleted
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_delete_dir(char *src_dir, int *err_code);
+
+
+
+INTERNAL_FUNC void emstorage_flush_db_cache();
+INTERNAL_FUNC int emstorage_test(int mail_id, int account_id, char *full_address_to, char *full_address_cc, char *full_address_bcc, int *err_code);
+
+INTERNAL_FUNC int emstorage_get_sender_list(int account_id, const char *mailbox_name, int search_type, const char *search_value, email_sort_type_t sorting, email_sender_list_t** sender_list, int *sender_count,  int *err_code);
+INTERNAL_FUNC int emstorage_free_sender_list(email_sender_list_t **sender_list, int count);
+
+/* Handling Thread mail */
+INTERNAL_FUNC int emstorage_get_thread_information(int thread_id, emstorage_mail_tbl_t **mail_table_data, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_get_thread_id_of_thread_mails(emstorage_mail_tbl_t *mail_table_data, int *thread_id, int *result_latest_mail_id_in_thread, int *thread_item_count);
+INTERNAL_FUNC int emstorage_get_thread_id_by_mail_id(int mail_id, int *thread_id, int *err_code);
+INTERNAL_FUNC int emstorage_update_latest_thread_mail(int account_id, int thread_id, int latest_mail_id, int thread_item_count, int transaction, int *err_code);
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+#define BULK_PARTIAL_BODY_DOWNLOAD_COUNT 10
+enum
+{
+       ACCOUNT_IDX_MAIL_PARTIAL_BODY_ACTIVITY_TBL = 0, 
+       MAIL_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL, 
+       SERVER_MAIL_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL, 
+       ACTIVITY_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL, 
+       ACTIVITY_TYPE_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL, 
+       MAILBOX_ID_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL, 
+       MAILBOX_NAME_IDX_IN_MAIL_PARTIAL_BODY_ACTIVITY_TBL,
+};
+
+
+INTERNAL_FUNC int   emstorage_get_pbd_activity_data(int account_id, int input_mailbox_id, email_event_partial_body_thd** event_start, int *count, int transaction, int *err_code);
+INTERNAL_FUNC int   emstorage_add_pbd_activity(email_event_partial_body_thd *local_activity, int *activity_id, int transaction, int *err_code);
+INTERNAL_FUNC int   emstorage_get_pbd_mailbox_list(int account_id, int **mailbox_list, int *count, int transaction, int *err_code);
+INTERNAL_FUNC int   emstorage_get_pbd_account_list(int **account_list, int *count, int transaction, int *err_code);
+INTERNAL_FUNC int   emstorage_get_pbd_activity_count(int *activity_id_count, int transaction, int *err_code);
+INTERNAL_FUNC int   emstorage_delete_full_pbd_activity_data(int account_id, int transaction, int *err_code);
+INTERNAL_FUNC int   emstorage_delete_pbd_activity(int account_id, int mail_id, int activity_id, int transaction, int *err_code);
+INTERNAL_FUNC int   emstorage_get_mailbox_pbd_activity_count(int account_id, int input_mailbox_id, int *activity_count, int transaction, int *err_code);
+INTERNAL_FUNC int   emstorage_update_pbd_activity(char *old_server_uid, char *new_server_uid, char *mbox_name, int *err_code);
+INTERNAL_FUNC int   emstorage_create_file(char *buf, size_t file_size, char *dst_file, int *err_code);
+
+#endif  
+
+INTERNAL_FUNC int   emstorage_free_address_info_list(email_address_info_list_t **address_info_list);
+
+INTERNAL_FUNC void  emstorage_create_dir_if_delete();
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+INTERNAL_FUNC int emstorage_update_read_mail_uid_by_server_uid(char *old_server_uid, char *new_server_uid, char *mbox_name, int *err_code);
+
+/**
+ * @fn emstorage_get_id_set_from_mail_ids(int mail_ids[], int mail_id_count, email_id_set_t **server_uids, int *id_set_count, int *err_code);
+ * Prepare an array of mail_id and corresponding server mail id.
+ *
+ *@author                                      h.gahlaut@samsung.com
+ * @param[in] mail_ids                 Specifies the comma separated string of mail_ids. Maximaum size of string should be less than or equal to (QUERY_SIZE - 88)
+ *                                                     where 88 is the length of fixed keywords including ending null character in the QUERY to be formed
+ * @param[out] idset                   Returns the array of mail_id and corresponding server_mail_id sorted by server_mail_ids in ascending order
+ * @param[out] id_set_count            Returns the no. of cells in idset array i.e. no. of sets of mail_ids and server_mail_ids
+ * @param[out] err_code                Returns the error code.
+ * @remarks                                    An Example of Query to be exexuted in this API : 
+ *                                                     SELECT local_uid, s_uid from mail_read_mail_uid_tbl where local_uid in (12, 13, 56, 78);
+ * @return This function returns true on success or false on failure.
+ */
+
+INTERNAL_FUNC int emstorage_get_id_set_from_mail_ids(char *mail_ids, email_id_set_t **idset, int *id_set_count, int *err_code);
+
+#endif
+
+/**
+ * @fn emstorage_filter_mails_by_rule(int account_id, char dest_mailbox_name, email_rule_t *rule, int **filtered_mail_id_list, int *count_of_mails, int err_code)
+ * Move mails by specified rule for spam filtering. 
+ *
+ * @author                                                             kyuho.jo@samsung.com
+ * @param[in] account_id                               Account id of the mails and the mailboxes.
+ * @param[in] dest_mailbox_name                        Mailbox name of spam mailbox.
+ * @param[in] rule                                             Filtering rule.
+ * @param[out] filtered_mail_id_list   Mail id list which are filtered by the rule.
+ * @param[out] count_of_mails                  Count of mails which are filtered by the rule.
+ * @param[out] err_code                                        Returns the error code.
+
+ * @remarks                                                                    
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emstorage_filter_mails_by_rule(int account_id, int dest_mailbox_id, emstorage_rule_tbl_t *rule, int **filtered_mail_id_list, int *count_of_mails, int *err_code);
+
+INTERNAL_FUNC int emstorage_add_meeting_request(int account_id, int input_mailbox_id, email_meeting_request_t *meeting_req, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_get_meeting_request(int mail_id, email_meeting_request_t **meeting_req, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_update_meeting_request(email_meeting_request_t *meeting_req, int transaction, int *err_code);
+INTERNAL_FUNC int emstorage_delete_meeting_request(int account_id, int mail_id, int input_mailbox_id, int transaction, int *err_code);
+INTERNAL_FUNC void emstorage_free_meeting_request(email_meeting_request_t *meeting_req);
+
+INTERNAL_FUNC int emstorage_write_conditional_clause_for_getting_mail_list(email_list_filter_t *input_filter_list, int input_filter_count, email_list_sorting_rule_t *input_sorting_rule_list, int input_sorting_rule_count, int input_start_index, int input_limit_count, char **output_conditional_clause);
+INTERNAL_FUNC int emstorage_free_list_filter(email_list_filter_t **input_filter_list, int input_filter_count);
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+/*
+*emstorage_get_next_activity_id
+*
+*description :  get an activity id for a new activity
+*/
+INTERNAL_FUNC int emstorage_get_next_activity_id(int *activity_id, int *err_code);
+
+ /*
+ *emstorage_get_activity_id_list
+ *description  :  get the list of activity ids
+ *arguments  : 
+ *return  : 
+ *
+ */
+INTERNAL_FUNC int emstorage_get_activity_id_list(int account_id, int **activity_id_list, int *activity_count, int lowest_activity_type, int highest_activity_type, int transaction, int*err_code);
+ /*
+ * emstorage_add_activity
+ *
+ * description :  add an activity to activity table
+ * arguments : 
+ * return  : 
+ */
+INTERNAL_FUNC int emstorage_add_activity(emstorage_activity_tbl_t *local_activity, int transaction, int *err_code);
+
+/**
+  *    emstorage_get_activity - Get the Local activity from the Mail activity table
+  *
+  */
+INTERNAL_FUNC int emstorage_get_activity(int account_id, int activity_id, emstorage_activity_tbl_t **activity_list, int *select_num, int transaction, int *err_code);
+
+/**
+ * emstorage_delete_local_activity - Deletes the Local acitivity Generated based on activity_type
+ * or based on server mail id
+ *
+ */
+INTERNAL_FUNC int emstorage_delete_local_activity(emstorage_activity_tbl_t *local_activity, int transaction, int *err_code);
+
+/**
+ * emstorage_free_local_activity - Free the allocated Activity data
+ * 
+ *
+ */
+INTERNAL_FUNC int emstorage_free_local_activity(emstorage_activity_tbl_t **local_activity_list, int count, int *err_code);
+
+/**
+ * emstorage_free_activity_id_list - Free the allocated Activity List data
+ * 
+ *
+ */
+INTERNAL_FUNC int emstorage_free_activity_id_list(int *activity_id_list, int *error_code);
+
+#endif
+
+INTERNAL_FUNC int emstorage_add_certificate(emstorage_certificate_tbl_t *certificate, int transaction, int *err_code);
+
+INTERNAL_FUNC int emstorage_free_certificate(emstorage_certificate_tbl_t **certificate_list, int count, int *err_code);
+
+INTERNAL_FUNC int emstorage_get_certificate_list(int *select_num, emstorage_certificate_tbl_t **certificate_list, int transaction, int with_password, int *err_code);
+
+INTERNAL_FUNC int emstorage_get_certificate_by_email_address(char *email_address, emstorage_certificate_tbl_t **certificate, int transaction, int with_password, int *err_code);
+
+INTERNAL_FUNC int emstorage_get_certificate_by_index(int index, emstorage_certificate_tbl_t **certificate, int transaction, int with_password, int *err_code);
+
+INTERNAL_FUNC int emstorage_delete_certificate(int index, int transaction, int *err_code);
+
+/* task begin */
+INTERNAL_FUNC int emstorage_add_task(email_task_type_t input_task_type, email_task_priority_t input_task_priority, char *input_task_parameter, int input_task_parameter_length, int input_transaction, int *output_task_id);
+
+INTERNAL_FUNC int emstorage_delete_task(int task_id, int transaction);
+
+INTERNAL_FUNC int emstorage_update_task_status(int task_id, email_task_status_type_t task_status, int transaction);
+
+INTERNAL_FUNC int emstorage_query_task(const char *input_conditional_clause, const char *input_ordering_clause, email_task_t **output_task_list, int *output_task_count);
+/* task end*/
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* __EMAIL_STORAGE_H__ */
+/* EOF */
diff --git a/email-core/include/email-core-account.h b/email-core/include/email-core-account.h
new file mode 100755 (executable)
index 0000000..024260a
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/****************************************************************************** 
+ * File :  email-core-account.h
+ * Desc :  Account Management
+ * * Auth : 
+ * * History : 
+ *    2010.08.25  :  created
+ *****************************************************************************/
+#ifndef _EMAIL_CORE_ACCOUNT_H_
+#define _EMAIL_CORE_ACCOUNT_H_
+
+#include "email-types.h"
+#include "email-internal-types.h"
+#include "email-storage.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+INTERNAL_FUNC int emcore_validate_account(int account_id, int *err_code);
+
+INTERNAL_FUNC int emcore_validate_account_with_account_info(email_account_t *account, int *err_code);
+
+INTERNAL_FUNC int emcore_create_account(email_account_t *account, int *err_code);
+
+INTERNAL_FUNC int emcore_delete_account(int account_id, int *err_code);
+
+INTERNAL_FUNC int emcore_free_account_list(email_account_t **account_list, int count, int *err_code);
+
+INTERNAL_FUNC void emcore_free_option(email_option_t *option);
+
+INTERNAL_FUNC void emcore_free_account(email_account_t *account_list);
+
+INTERNAL_FUNC void emcore_duplicate_account(const email_account_t *account, email_account_t **account_dup, int *err_code);
+
+INTERNAL_FUNC int emcore_init_account_reference();
+
+INTERNAL_FUNC int emcore_free_account_reference();
+
+INTERNAL_FUNC email_account_t *emcore_get_account_reference(int account_id);
+
+INTERNAL_FUNC int emcore_get_account_reference_list(email_account_t **account_list, int *count, int *err_code);
+
+INTERNAL_FUNC int emcore_query_server_info(const char* domain_name, email_server_info_t **result_server_info);
+
+INTERNAL_FUNC int emcore_free_server_info(email_server_info_t **target_server_info);
+
+INTERNAL_FUNC int emcore_save_default_account_id(int input_account_id);
+
+INTERNAL_FUNC int emcore_load_default_account_id(int *output_account_id);
+
+INTERNAL_FUNC int emcore_recover_from_secured_storage_failure();
+
+INTERNAL_FUNC int emcore_update_sync_status_of_account(int input_account_id, email_set_type_t input_set_operator, int input_sync_status);
+
+
+#ifdef __FEATURE_BACKUP_ACCOUNT__
+INTERNAL_FUNC int emcore_backup_accounts(const char *file_path, int *error_code);
+
+INTERNAL_FUNC int emcore_restore_accounts(const char *file_path, int *error_code);
+#endif /*   __FEATURE_BACKUP_ACCOUNT_ */
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /*_EMAIL_CORE_ACCOUNT_H_*/
+
diff --git a/email-core/include/email-core-api.h b/email-core/include/email-core-api.h
new file mode 100755 (executable)
index 0000000..9605a72
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-api.h
+ * Desc :  email-core-api Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_API_H__
+#define __EMAIL_CORE_API_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+int emcore_init(int *err_code);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /*__EMAIL_CORE_API_H__*/
diff --git a/email-core/include/email-core-cert.h b/email-core/include/email-core-cert.h
new file mode 100644 (file)
index 0000000..12e87b1
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-cert.h
+ * Desc :  Certificate operation Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2011.04.14  :  created
+ *****************************************************************************/
+
+#ifndef EM_CORE_CERT_H_
+#define EM_CORE_CERT_H_
+
+#include <openssl/x509.h>
+#include <openssl/evp.h>
+
+#include "email-utilities.h"
+#include "email-types.h"
+
+INTERNAL_FUNC int emcore_add_public_certificate(char *public_cert_path, char *save_name, int *err_code);
+
+INTERNAL_FUNC int emcore_delete_public_certificate(char *email_address, int *err_code);
+
+INTERNAL_FUNC int emcore_verify_signature(char *p7s_file_path, char *mime_entity, int *validity, int *err_code);
+
+INTERNAL_FUNC int emcore_verify_certificate(char *certificate, int *validity, int *err_code);
+
+INTERNAL_FUNC int emcore_free_certificate(email_certificate_t **certificate, int count, int *err_code);
+/*
+INTERNAL_FUNC int emcore_load_PFX_file(char *certificate, char *password, EVP_PKEY **pri_key, X509 **cert, STACK_OF(X509) **ca, int *err_code);
+*/
+INTERNAL_FUNC int emcore_load_PFX_file(char *certificate, EVP_PKEY **pri_key, X509 **cert, STACK_OF(X509) **ca, int *err_code);
+
+#endif
diff --git a/email-core/include/email-core-event.h b/email-core/include/email-core-event.h
new file mode 100755 (executable)
index 0000000..bf1bce2
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-event.h
+ * Desc :  Mail Engine Event Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_EVNET_H__
+#define __EMAIL_CORE_EVNET_H__
+
+#include "email-types.h"
+#include "email-internal-types.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+void emcore_execute_event_callback(email_action_t action, int total, int done, int status, int account_id, int mail_id, int handle, int error);
+int  emcore_get_active_queue_idx(void);
+int  emcore_check_send_mail_thread_status();
+
+INTERNAL_FUNC int          emcore_get_current_thread_type();
+INTERNAL_FUNC int          emcore_register_event_callback(email_action_t action, email_event_callback callback, void *event_data);
+INTERNAL_FUNC int          emcore_unregister_event_callback(email_action_t action, email_event_callback callback);
+INTERNAL_FUNC int          emcore_get_pending_event(email_action_t action, int account_id, int mail_id, email_event_status_type_t *status);
+INTERNAL_FUNC int          emcore_start_event_loop(int *err_code);
+INTERNAL_FUNC int          emcore_stop_event_loop(int *err_code);
+INTERNAL_FUNC int          emcore_insert_event(email_event_t *event_data, int *handle, int *err_code);
+INTERNAL_FUNC int          emcore_cancel_thread(int handle, void *arg, int *err_code);
+INTERNAL_FUNC int          emcore_start_event_loop_for_sending_mails(int *err_code);
+INTERNAL_FUNC int          emcore_send_event_loop_stop(int *err_code);
+INTERNAL_FUNC int          emcore_cancel_send_mail_thread(int handle, void *arg, int *err_code);
+INTERNAL_FUNC int          emcore_check_thread_status(void);
+INTERNAL_FUNC void         emcore_get_event_queue_status(int *on_sending, int *on_receiving);
+INTERNAL_FUNC int          emcore_insert_event_for_sending_mails(email_event_t *event_data, int *handle, int *err_code);
+INTERNAL_FUNC int          emcore_get_receiving_event_queue(email_event_t **event_queue, int *event_count, int *err);
+INTERNAL_FUNC int          emcore_cancel_all_threads_of_an_account(int account_id);
+INTERNAL_FUNC int          emcore_free_event(email_event_t *event_data);
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+/*  Please contact -> Himanshu [h.gahlaut@samsung.com] for any explanation in code here under this MACRO */
+INTERNAL_FUNC int          emcore_insert_partial_body_thread_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code);
+INTERNAL_FUNC int          emcore_is_partial_body_thd_que_empty();
+INTERNAL_FUNC int          emcore_is_partial_body_thd_que_full();
+INTERNAL_FUNC int          emcore_start_thread_for_downloading_partial_body(int *err_code);
+INTERNAL_FUNC int          emcore_clear_partial_body_thd_event_que(int *err_code);
+INTERNAL_FUNC int          emcore_free_partial_body_thd_event(email_event_partial_body_thd *partial_body_thd_event, int *error_code);
+INTERNAL_FUNC unsigned int emcore_get_partial_body_thd_id();
+INTERNAL_FUNC int          emcore_get_pbd_thd_state();
+unsigned int emcore_get_receiving_thd_id();
+#endif
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-core/include/email-core-global.h b/email-core/include/email-core-global.h
new file mode 100755 (executable)
index 0000000..e16a770
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+/******************************************************************************
+ * File :  email-core-global.h
+ * Desc :  email-core-global Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.01  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_GLOBAL_H__
+#define __EMAIL_CORE_GLOBAL_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include "email-internal-types.h"
+
+INTERNAL_FUNC int emcore_get_account_from_unvalidated_account_list(int input_unvalidated_account_id, email_account_t **oupput_account);
+INTERNAL_FUNC int emcore_add_account_to_unvalidated_account_list(email_account_t *input_new_account);
+INTERNAL_FUNC int emcore_delete_account_from_unvalidated_account_list(int input_account_id);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-core/include/email-core-imap-idle.h b/email-core/include/email-core-imap-idle.h
new file mode 100755 (executable)
index 0000000..30fd18e
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/**
+ *
+ * This file contains functinality related to IMAP IDLE.
+ * @file               email-core-imap-idle.h
+ * @author     
+ * @version    0.1
+ * @brief              This file contains functionality to provide IMAP IDLE support in email-service. 
+ */
+
+#include "email-internal-types.h"
+
+/**
+
+
+ * @fn emcore_create_imap_idle_thread(int *err_code)
+ * @brief      Creates a thread that listens for IMAP IDLE Notifications.
+ *
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+
+INTERNAL_FUNC int emcore_create_imap_idle_thread(int accountID, int *err_code);
+
+/**
+
+
+ * @fn emcore_kill_imap_idle_thread(int *err_code)
+ * @brief      Kills IMAP IDLE thread
+ *
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emcore_kill_imap_idle_thread(int *err_code);
diff --git a/email-core/include/email-core-imap-mailbox.h b/email-core/include/email-core-imap-mailbox.h
new file mode 100755 (executable)
index 0000000..533892e
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File :  email-core-imap-mailbox.h
+ * Desc :  Mail IMAP mailbox Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.01  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_IMAP_MAILBOX_H__
+#define __EMAIL_CORE_IMAP_MAILBOX_H__
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+INTERNAL_FUNC int emcore_check_sync_imap_mailbox(email_mailbox_t *mailbox, int *synchronous, int *err_code);
+/**
+ * Get mailbox list from imap server.
+ *
+ * @param[in] account_id       Specifies the account ID.
+ * @param[in] mailbox  Specifies the target mailbox. if NULL, get all mailbox.
+ * @param[in] callback Specifies the callback function for retrieving mailbox list.
+ * @param[in] handle   Specifies the handle for stopping this job.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emcore_sync_mailbox_list(int account_id, char *mailbox, int handle, int *err_code);
+
+/**
+ * Download mailbox list from imap server.
+ *
+ * @param[in] stream   Specifies the internal mail stream.
+ * @param[in] mailbox  Specifies the target mailbox. if NULL, get all mailbox.
+ * @param[out] mailbox_list    The returned mailbox are saved here.
+ * @param[out] count   The count of mailbox is saved here.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emcore_download_mailbox_list(void *mail_stream, char *mailbox, email_internal_mailbox_t **mailbox_list, int *count, int *err_code);
+INTERNAL_FUNC int emcore_delete_imap_mailbox(int input_mailbox_id, int *err_code);
+INTERNAL_FUNC int emcore_create_imap_mailbox(email_mailbox_t *mailbox, int *err_code);
+INTERNAL_FUNC int emcore_move_mailbox_on_imap_server(int input_account_id, char *input_old_mailbox_path, char *input_new_mailbox_path);
+INTERNAL_FUNC int emcore_set_sync_imap_mailbox(email_internal_mailbox_t *mailbox, int synchronous, int *err_code);
+INTERNAL_FUNC int emcore_set_mail_slot_size(int account_id, int mailbox_id, int new_slot_size, int *err_code);
+INTERNAL_FUNC int emcore_remove_overflowed_mails(emstorage_mailbox_tbl_t *intput_mailbox_tbl, int *err_code);  
+INTERNAL_FUNC int emcore_get_default_mail_slot_count(int input_account_id, int *output_count);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-core/include/email-core-mail.h b/email-core/include/email-core-mail.h
new file mode 100755 (executable)
index 0000000..e7c0f47
--- /dev/null
@@ -0,0 +1,220 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-mail.h
+ * Desc :  Mail Operation Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_MESSAGE_H__
+#define __EMAIL_CORE_MESSAGE_H__
+
+#include "email-storage.h"
+#include <contacts.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+
+#define MAX_SUBSET_STRING_SIZE 260     
+#define MAX_IMAP_COMMAND_LENGTH 1000
+#define MAX_TAG_SIZE 16
+
+
+typedef struct _emf_uid_range_set
+{
+       char *uid_range;
+       unsigned long lowest_uid;
+       unsigned long highest_uid;
+       
+       struct _emf_uid_range_set *next;
+       
+} email_uid_range_set;
+
+#endif
+
+
+struct _m_content_info 
+{
+       int grab_type;              /*  1 :  download text and get attachment names (no saving attachment) - #define GRAB_TYPE_TEXT       retrieve text and attachment names */
+                              /*  2 :  download attachment - #define GRAB_TYPE_ATTACHMENT retrieve only attachment */
+       int file_no;                /*  attachment no to be download (min : 1) */
+       int report;                 /*  0 : Non 1 : DSN mail 2 : MDN mail 3 : mail to require MDN */
+
+       struct text_data 
+       {
+               char *plain;            /*  body plain text */
+               char *plain_charset;    /*  charset of body text */
+               char *html;             /*  body html text */
+               char *html_charset;     /*  charset of html text */
+       } text;
+
+       struct attachment_info 
+       {
+               int   type;                 /*  1 : inline 2 : attachment */
+               char *name;                 /*  attachment filename */
+               int   size;                 /*  attachment size */
+               char *save;                 /*  content saving filename */
+               int   drm;                  /*  0 : none 1 : object 2 : rights 3 : dcf */
+               int   drm2;                 /*  0 : none 1 : FL 2 : CD 3 : SSD 4 : SD */
+               char *attachment_mime_type; /*  attachment mime type */
+               char *content_id;           /*  mime content id */
+#ifdef __ATTACHMENT_OPTI__
+               int   encoding;         /*  encoding  */
+               char *section;          /*  section number */
+#endif
+               struct attachment_info *next;
+       } *file;
+};
+
+/**
+ * Download email body from server.
+ *
+ * @param[in] mail_stream      Specifies the mail_stream.
+ * @param[in] mailbox          Specifies the mailbox to contain account ID.
+ * @param[in] mail_id          Specifies the mail ID.
+ * @param[in] callback         Specifies the callback function for retrieving download status.
+ * @param[in] with_attach      Specifies the flag for downloading attachments.
+ * @param[in] limited_size     Specifies the size to be downloaded.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks In POP3 case, body and attachment are downloaded in this function.
+ *          In IMAP case, body and attachment list are downloaded and 
+ *          attachments must be downloaded in emcore_download_attachment.
+ * @return This function returns true on success or false on failure.
+ */
+
+INTERNAL_FUNC int emcore_download_body_multi_sections_bulk(void *mail_stream, int account_id, int mail_id, int verbose, int with_attach, int limited_size, int event_handle , int *err_code);
+
+
+/**
+ * Download a email nth-attachment from server.
+ *
+ * @param[in] mailbox          Specifies the mailbox to contain account ID.
+ * @param[in] mail_id                  Specifies the mail ID.
+ * @param[in] nth                              Specifies the buffer that a attachment number been saved. the minimum number is "1".
+ * @param[in] callback         Specifies the callback function for retrieving download status.
+ * @param[in] handle                   Specifies the handle for stopping downloading.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks This function is used for only IMAP mail.
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emcore_download_attachment(int acconut_id, int mail_id, int nth, int *err_code);
+INTERNAL_FUNC int emcore_mail_add_attachment(int mail_id, email_attachment_data_t *attachment, int *err_code);        /* TODO : Remove duplicated function */
+INTERNAL_FUNC int emcore_mail_add_attachment_data(int input_mail_id, email_attachment_data_t *input_attachment_data); /* TODO : Remove duplicated function */
+INTERNAL_FUNC int emcore_delete_mail_attachment(int attachment_id, int *err_code);
+INTERNAL_FUNC int emcore_get_attachment_info(int attachment_id, email_attachment_data_t **attachment, int *err_code);
+INTERNAL_FUNC int emcore_get_attachment_data_list(int input_mail_id, email_attachment_data_t **output_attachment_data, int *output_attachment_count);
+INTERNAL_FUNC int emcore_free_attachment_data(email_attachment_data_t **attachment_data_list, int attachment_data_count, int *err_code);
+
+
+INTERNAL_FUNC int emcore_move_mail(int mail_ids[], int num, int dst_mailbox_id, int noti_param_1, int noti_param_2, int *err_code);
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+INTERNAL_FUNC int emcore_insert_pbd_activity(email_event_partial_body_thd *local_activity, int *activity_id, int *err_code) ;
+INTERNAL_FUNC int emcore_delete_pbd_activity(int account_id, int mail_id, int activity_id, int *err_code);
+#endif 
+
+INTERNAL_FUNC int emcore_get_mail_contact_info(email_mail_contact_info_t *contact_info, char *full_address, int *err_code);
+INTERNAL_FUNC int emcore_get_mail_contact_info_with_update(email_mail_contact_info_t *contact_info, char *full_address, int mail_id, int *err_code);
+INTERNAL_FUNC int emcore_free_contact_info(email_mail_contact_info_t *contact_info, int *err_code);
+INTERNAL_FUNC int emcore_sync_contact_info(int mail_id, int *err_code);
+INTERNAL_FUNC GList *emcore_get_recipients_list(GList *old_recipients_list, char *full_address, int *err_code);
+INTERNAL_FUNC int emcore_get_mail_address_info_list(int mail_id, email_address_info_list_t **address_info_list, int *err_code);
+
+INTERNAL_FUNC int emcore_set_sent_contacts_log(emstorage_mail_tbl_t *input_mail_data);
+INTERNAL_FUNC int emcore_set_received_contacts_log(emstorage_mail_tbl_t *input_mail_data);
+INTERNAL_FUNC int emcore_delete_contacts_log(int input_account_id);
+
+INTERNAL_FUNC int emcore_get_mail_display_name(char *email_address, char **contact_display_name, int *err_code);
+INTERNAL_FUNC int emcore_get_mail_data(int input_mail_id, email_mail_data_t **output_mail_data);
+
+INTERNAL_FUNC int emcore_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int sync_server);
+
+INTERNAL_FUNC int emcore_delete_mails_from_local_storage(int account_id, int *mail_ids, int num, int noti_param_1, int noti_param_2, int *err_code);
+INTERNAL_FUNC int emcore_get_mail_msgno_by_uid(email_account_t *account, email_internal_mailbox_t *mailbox, char *uid, int *msgno, int *err_code);
+INTERNAL_FUNC int emcore_expunge_mails_deleted_flagged_from_local_storage(int input_mailbox_id);
+INTERNAL_FUNC int emcore_expunge_mails_deleted_flagged_from_remote_server(int input_account_id, int input_mailbox_id);
+
+/**
+ * Delete mails.
+ *
+ * @param[in] account_id      Specifies the account id.
+ * @param[in] mail_id         Specifies the array for mail id.
+ * @param[in] num             Specifies the number of id.
+ * @param[in] from_server     Specifies whether mails is deleted from server.
+ * @param[in] callback        Specifies the callback function for delivering status during deleting.
+ * @param[in] noti_param_1    Specifies the first parameter for notification.
+ * @param[in] noti_param_2    Specifies the second parameter for notification.
+ * @param[out] err_code       Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emcore_delete_mail(int account_id, int mail_id[], int num, int from_server, int noti_param_1, int noti_param_2, int *err_code);
+
+/**
+ * Delete mails.
+ *
+ * @param[in] input_mailbox_id Specifies the id of mailbox.
+ * @param[in] input_from_server        Specifies whether mails is also deleted from server.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int   emcore_delete_all_mails_of_acount(int input_account_id);
+INTERNAL_FUNC int   emcore_delete_all_mails_of_mailbox(int input_account_id, int input_mailbox_id, int input_from_server, int *err_code);
+
+INTERNAL_FUNC void  emcore_free_mail_data_list(email_mail_data_t **mail_list, int count);
+INTERNAL_FUNC void  emcore_free_mail_data(email_mail_data_t *mail);
+INTERNAL_FUNC void  emcore_free_content_info(struct _m_content_info *cnt_info);
+INTERNAL_FUNC void  emcore_free_attachment_info(struct attachment_info *attchment);
+
+INTERNAL_FUNC int   emcore_move_mail_on_server(int account_id, int src_mailbox_id,  int mail_ids[], int num, char *dest_mailbox, int *error_code);
+INTERNAL_FUNC int   emcore_move_mail_to_another_account(int input_mail_id, int input_source_mailbox_id, int input_target_mailbox_id, int input_task_id);
+INTERNAL_FUNC int   emcore_sync_flag_with_server(int mail_id, int *err_code);
+INTERNAL_FUNC int   emcore_sync_seen_flag_with_server(int mail_ids[], int num, int *err_code);
+
+INTERNAL_FUNC int   emcore_set_flags_field(int account_id, int mail_ids[], int num, email_flags_field_type field_type, int value, int *err_code);
+INTERNAL_FUNC char* emcore_convert_mutf7_to_utf8(char *mailbox_name); 
+INTERNAL_FUNC int   emcore_convert_string_to_structure(const char *encoded_string, void **struct_var, email_convert_struct_type_e type);
+INTERNAL_FUNC int   emcore_save_mail_file(int account_id, int mail_id, int attachment_id, char *src_file_path, char *file_name, char *full_path, int *err_code);
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+INTERNAL_FUNC int   emcore_sync_flags_field_with_server(int mail_ids[], int num, email_flags_field_type field_type, int value, int *err_code);
+INTERNAL_FUNC int   emcore_move_mail_on_server_ex(int account_id, int src_mailbox_id,  int mail_ids[], int num, int dest_mailbox_id, int *error_code);
+#endif
+
+#ifdef __ATTACHMENT_OPTI__
+INTERNAL_FUNC int emcore_download_attachment_bulk(/*email_mailbox_t *mailbox, */ int account_id, int mail_id, char *nth,  int *err_code);
+#endif
+INTERNAL_FUNC int   emcore_mail_filter_by_rule(email_rule_t *filter_info, int *err_code);
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
+/* EOF */
diff --git a/email-core/include/email-core-mailbox-sync.h b/email-core/include/email-core-mailbox-sync.h
new file mode 100755 (executable)
index 0000000..71848e9
--- /dev/null
@@ -0,0 +1,184 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-mailbox_sync.h
+ * Desc :  Mail Header Sync Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_MAILBOX_SYNC_H__
+#define __EMAIL_CORE_MAILBOX_SYNC_H__
+
+#include "email-types.h"
+#include "email-storage.h"
+#include "c-client.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+
+#define IMAGE_DISPLAY_PARTIAL_BODY_COUNT 30
+typedef struct 
+{
+       char  image_file_name[100];
+       char *text_image;
+       char *content_id;
+       int   dec_len;
+       char *mime_type;
+} email_image_data;
+
+typedef struct 
+{
+       char *header;
+       int header_len;
+       char *body;
+       int body_len;
+} email_partial_buffer;
+
+#endif
+
+typedef struct emcore_uid_elem {
+       int msgno;
+       char *uid;
+       email_mail_flag_t flag;
+       struct emcore_uid_elem *next;
+} emcore_uid_list; 
+
+int pop3_mail_calc_rfc822_size(MAILSTREAM *stream, int msgno, int *size, int *err_code);
+int pop3_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *err_code);
+
+int imap4_mail_calc_rfc822_size(MAILSTREAM *stream, int msgno, int *size, int *err_code);
+int imap4_mailbox_get_uids(MAILSTREAM *stream, emcore_uid_list** uid_list, int *err_code);
+
+int emcore_check_rule(const char *input_full_address_from, const char *input_subject, emstorage_rule_tbl_t *rule, int rule_len, int *matched, int *err_code);
+
+int emcore_make_mail_tbl_data_from_envelope(MAILSTREAM *mail_stream, ENVELOPE *input_envelope, emcore_uid_list *input_uid_elem, emstorage_mail_tbl_t **output_mail_tbl_data,  int *err_code);
+
+int emcore_add_mail_to_mailbox(emstorage_mailbox_tbl_t *input_maibox_data, emstorage_mail_tbl_t *input_new_mail_tbl_data, int *output_mail_id, int *output_thread_id);
+
+/**
+ * Download unread all headers from mail server.
+ *
+ * @param[in] input_mailbox_tbl        Specifies the mailbox to contain target mailbox name.
+ *                      if the mailbox name is NULL, headers are downloaded from all synchronous mailbox.
+ *                      the mailbox name is unused in POP3 case.
+ * @param[in] input_mailbox_tbl_spam   Mailbox information of Spambox for filtering blocked mails.
+ * @param[in] stream_recycle Stream to reuse.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emcore_sync_header(emstorage_mailbox_tbl_t *input_mailbox_tbl, emstorage_mailbox_tbl_t *input_mailbox_tbl_spam, void *stream_recycle, emcore_uid_list **input_uid_list, int *unread_mail, int *err_code);
+
+typedef enum
+{
+       EM_CORE_GET_UIDS_FOR_NO_DELETE = 0, 
+       EM_CORE_GET_UIDS_FOR_DELETE, 
+} emcore_get_uids_for_delete_t;
+/**
+ * Download UID list from mail server. 
+ *
+ * @param[in] mailbox    Specifies the mailbox to contain target mailbox name.
+ *                        the mailbox name is unused in POP3 case.
+ * @param[out] uid_list The returned UID list is saved in a memory. this argument points to the list.
+ * @param[out] total      Specifies the count of the uid_list.
+ * @param[in] read_mail_uids Specifies the array of the uids have the seen flag.
+ * @param[in] count              Specifies the count of read_mail_uids.
+ * @param[in] for_delete  Specifies the flag for deleting. (0 = for downloading or retrieving body, 1 = for deleting message)
+ * @param[out] err_code          Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+int emcore_download_uid_all(email_internal_mailbox_t *mailbox,
+                                                       emcore_uid_list         **uid_list,
+                                                       int                                                     *total,
+                                                       emstorage_read_mail_uid_tbl_t *read_mail_uids, 
+                                                       int                           count, 
+                                                       emcore_get_uids_for_delete_t  for_delete, 
+                                                       int                                                     *err_code);
+
+
+
+/**
+ * Search a UID from mail server. this function is supported for only IMAP account.
+ *
+ * @param[in] mailbox  Specifies the mailbox to contain target mailbox name.
+ * @param[in] uid              Specifies the mail uid.
+ * @param[out] msgno   The message number to be related to uid is saved here.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+int emcore_download_imap_msgno(email_internal_mailbox_t *mailbox, char *uid, int *msgno, int *err_code);
+
+/**
+ * Get a message number to be related to uid.
+ *
+ * @param[in] uid_list Specifies the uid list.
+ * @param[in] uid               Specifies the mail uid.
+ * @param[out] msgno    The message number to be related to uid is saved here.
+ * @param[out] err_code         Specifies the error code returned.
+ * @remarks The uid list must be already saved in fpath before this fucntion is called.
+ * @return This function returns true on success or false on failure.
+ */
+int emcore_get_msgno(emcore_uid_list *uid_list, char *uid, int *msgno, int *err_code);
+
+/**
+ * Get a uid to be related to a message number.
+ *
+ * @param[in] uid_list Specifies the uid list.
+ * @param[in] msgno             Specifies the message number.
+ * @param[out] uid              The message uid is saved here.
+ * @param[out] err_code         Specifies the error code returned.
+ * @remarks The uid list must be already saved in fpath before this fucntion is called.
+ * @return This function returns true on success or false on failure.
+ */
+int emcore_get_uid(emcore_uid_list *uid_list, int msgno, char **uid, int *err_code);
+
+/**
+ * free fetch list.
+ *
+ * @param[in] uid_list Specifies the fetch data.
+ * @param[out] err_code        Specifies the error code returned.
+ * @return This function returns true on success or false on failure.
+ */
+int emcore_free_uids(emcore_uid_list *uid_list, int *err_code);
+
+INTERNAL_FUNC int emcore_sync_mail_from_client_to_server(int mail_id);
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+INTERNAL_FUNC int emcore_download_bulk_partial_mail_body(MAILSTREAM *stream, email_event_partial_body_thd *pbd_event, int count, int *error);
+#endif /* __FEATURE_PARTIAL_BODY_DOWNLOAD__ */
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-core/include/email-core-mailbox.h b/email-core/include/email-core-mailbox.h
new file mode 100755 (executable)
index 0000000..9ea5599
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File :  email-core-mailbox.h
+ * Desc :  Local Mailbox Management Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_MAILBOX_H__
+#define __EMAIL_CORE_MAILBOX_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include "c-client.h"
+#include "email-types.h"
+#include "email-internal-types.h"
+
+typedef enum      
+{
+       EM_CORE_STREAM_TYPE_RECV = 0,   
+       EM_CORE_STREAM_TYPE_SEND,               
+} emcore_stream_type_t;
+
+#ifdef __FEATURE_KEEP_CONNECTION__
+INTERNAL_FUNC int emcore_remove_connection_info(int account_id);
+#endif /* __FEATURE_KEEP_CONNECTION__ */
+/*  in SMTP case, path argument must be (ENCODED_PATH_SMTP) */
+/*  ex) emcore_connect_to_remote_mailbox(xxx, (char *)ENCODED_PATH_SMTP, xxx, xxx); */
+INTERNAL_FUNC int  emcore_connect_to_remote_mailbox_with_account_info(email_account_t *ref_account, int input_mailbox_id, void **mail_stream, int *err_code);
+INTERNAL_FUNC int  emcore_connect_to_remote_mailbox(int account_id, int input_mailbox_id, void **mail_stream, int *err_code);
+INTERNAL_FUNC int  emcore_close_mailbox(int account_id, void *mail_stream);
+#ifdef __FEATURE_KEEP_CONNECTION__
+INTERNAL_FUNC void emcore_close_mailbox_receiving_stream();
+INTERNAL_FUNC void emcore_close_mailbox_partial_body_stream();
+INTERNAL_FUNC void emcore_reset_streams();
+#endif
+
+INTERNAL_FUNC int  emcore_get_mailbox_list_to_be_sync(int account_id, email_mailbox_t **mailbox_list, int *p_count, int *err_code);
+INTERNAL_FUNC int  emcore_get_mailbox_list(int account_id, email_mailbox_t **mailbox_list, int *p_count, int *err_code);
+INTERNAL_FUNC int  emcore_get_mail_count(email_mailbox_t *mailbox, int *total, int *unseen, int *err_code);
+INTERNAL_FUNC int  emcore_create_mailbox(email_mailbox_t *new_mailbox, int on_server, int *err_code);
+INTERNAL_FUNC int  emcore_delete_mailbox(int input_mailbox_id, int on_server, int *err_code);
+INTERNAL_FUNC int  emcore_delete_mailbox_ex(int input_account_id, int *input_mailbox_id_array, int input_mailbox_id_count, int input_on_server);
+INTERNAL_FUNC int  emcore_delete_mailbox_all(email_mailbox_t *mailbox, int *err_code);
+INTERNAL_FUNC int  emcore_update_mailbox(email_mailbox_t *old_mailbox, email_mailbox_t *new_mailbox, int *err_code);
+INTERNAL_FUNC int  emcore_save_local_activity_sync(int account_id, int *err_code);
+INTERNAL_FUNC int  emcore_send_mail_event(email_mailbox_t *mailbox, int mail_id , int *err_code);
+INTERNAL_FUNC int  emcore_partial_body_thd_local_activity_sync(int *is_event_inserted, int *err_code);
+INTERNAL_FUNC int  emcore_get_mailbox_by_type(int account_id, email_mailbox_type_e mailbox_type, email_mailbox_t *spam_mailbox, int *err_code);
+INTERNAL_FUNC void emcore_free_mailbox_list(email_mailbox_t **mailbox_list, int count);
+INTERNAL_FUNC void emcore_free_mailbox(email_mailbox_t *mailbox);
+
+INTERNAL_FUNC void emcore_bind_mailbox_type(email_internal_mailbox_t *mailbox_list);
+INTERNAL_FUNC int  emcore_free_internal_mailbox(email_internal_mailbox_t **mailbox_list, int count, int *err_code);
+
+
+
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+INTERNAL_FUNC int  emcore_local_activity_sync(int account_id, int *err_code);
+INTERNAL_FUNC int  emcore_save_local_activity_sync(int account_id, int *err_code);
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-core/include/email-core-mime.h b/email-core/include/email-core-mime.h
new file mode 100755 (executable)
index 0000000..8c110ec
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-mime.h
+ * Desc :  MIME Operation Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2011.04.14  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_MIME_H__
+#define __EMAIL_CORE_MIME_H__
+
+#include "email-internal-types.h"
+#include "c-client.h"
+#include "email-storage.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+char *emcore_get_line_from_file(void *stream, char *buf, int size, int *err_code);
+int   emcore_parse_mime(void *stream, int is_file, struct _m_content_info *cnt_info, int *err_code);
+INTERNAL_FUNC int   emcore_get_content_type_from_mime_string(char *input_mime_string, char **output_content_type);
+INTERNAL_FUNC int   emcore_get_content_type_from_mail_bodystruct(BODY *input_body, int input_buffer_length, char *output_content_type);
+INTERNAL_FUNC int   emcore_get_attribute_value_of_body_part(PARAMETER *input_param, char *atribute_name, char *output_value, int output_buffer_length, int with_rfc2047_text, int *err_code);
+INTERNAL_FUNC int   emcore_get_body_part_list_full(MAILSTREAM *stream, int msg_uid, int account_id, int mail_id, BODY *body, struct _m_content_info *cnt_info, int *err_code, PARTLIST * section_list, int event_handle);
+INTERNAL_FUNC int   emcore_get_body(MAILSTREAM *stream, int account_id, int mail_id, int msg_uid, BODY *body, struct _m_content_info *cnt_info, int *err_code);
+INTERNAL_FUNC int   emcore_get_body_structure(MAILSTREAM *stream, int msg_uid, BODY **body, int *err_code);
+INTERNAL_FUNC char *emcore_decode_rfc2047_text(char *rfc2047_text, int *err_code);
+INTERNAL_FUNC int   emcore_decode_body_text(char *enc_buf, int enc_len, int enc_type, int *dec_len, int *err_code);
+INTERNAL_FUNC int   emcore_set_fetch_body_section(BODY *body, int enable_inline_list, int *total_mail_size, int *err_code);
+INTERNAL_FUNC int   emcore_parse_mime_file_to_mail(char *eml_file_path, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data, int *output_attachment_count, int *err_code);
+INTERNAL_FUNC int   emcore_delete_parsed_data(email_mail_data_t *input_mail_data, int *err_code);
+INTERNAL_FUNC int   emcore_get_mime_entity(char *mime_path, char **mime_entity, int *err_code);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
+/* EOF */
diff --git a/email-core/include/email-core-signal.h b/email-core/include/email-core-signal.h
new file mode 100755 (executable)
index 0000000..401bce0
--- /dev/null
@@ -0,0 +1,50 @@
+/*\r
+*  email-service\r
+*\r
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
+*\r
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
+*\r
+* Licensed under the Apache License, Version 2.0 (the "License");\r
+* you may not use this file except in compliance with the License.\r
+* You may obtain a copy of the License at\r
+*\r
+* http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*\r
+*/\r
+\r
+/*\r
+ * email-core-signal.h\r
+ *\r
+ *  Created on: 2012. 11. 22.\r
+ *      Author: kyuho.jo@samsung.com\r
+ */\r
+\r
+#ifndef EMAIL_CORE_SIGNAL_H_\r
+#define EMAIL_CORE_SIGNAL_H_\r
+\r
+#include "email-internal-types.h"\r
+#include "email-core-tasks.h"\r
+\r
+INTERNAL_FUNC int emcore_initialize_signal();\r
+\r
+INTERNAL_FUNC int emcore_finalize_signal();\r
+\r
+/* emcore_notify_storage_event - Notification for storage related operations */\r
+INTERNAL_FUNC int emcore_notify_storage_event(email_noti_on_storage_event event_type, int data1, int data2 , char *data3, int data4);\r
+\r
+/* emcore_notify_network_event - Notification for network related operations */\r
+INTERNAL_FUNC int emcore_notify_network_event(email_noti_on_network_event event_type, int data1, char *data2, int data3, int data4);\r
+\r
+/* emcore_notify_response_to_api - Notification for response to API */\r
+INTERNAL_FUNC int emcore_notify_response_to_api(email_event_type_t event_type, int data1, int data2);\r
+\r
+INTERNAL_FUNC int emcore_send_task_status_signal(email_task_type_t input_task_type, int input_task_id, email_task_status_type_t input_task_status, int input_param_1, int input_param_2);\r
+\r
+#endif /* EMAIL_CORE_SIGNAL_H_ */\r
diff --git a/email-core/include/email-core-smime.h b/email-core/include/email-core-smime.h
new file mode 100755 (executable)
index 0000000..c1b84f7
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-smime.h
+ * Desc :  Mail Operation Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+
+#ifndef EM_CORE_SMIME_H_
+#define EM_CORE_SMIME_H_
+
+#include <cert-service.h>
+
+#include "email-types.h"
+
+INTERNAL_FUNC int emcore_smime_set_signed_message(char *certificate, char *mime_entity, email_digest_type digest_type, char **file_path, int *err_code);
+
+INTERNAL_FUNC int emcore_smime_set_encrypt_message(char *other_certificate_list, char *mime_entity, email_cipher_type cipher_type, char **file_path, int *err_code);
+
+INTERNAL_FUNC int emcore_smime_set_signed_and_encrypt_message(char *recipient_list, char *certificate, char *mime_entity, email_cipher_type cipher_type, email_digest_type digest_type, char **file_path, int *err_code);
+
+INTERNAL_FUNC int emcore_smime_verify_signed_message(char *signed_message, char *ca_file, char *ca_path, int *verify);
+
+INTERNAL_FUNC int emcore_smime_set_decrypt_message(char *encrypt_message, char *from_address, char **decrypt_message, int *err_code);
+
+INTERNAL_FUNC int emcore_convert_mail_data_to_smime_data(emstorage_account_tbl_t *account_tbl_item, email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_mail_data_t **output_mail_data, email_attachment_data_t **output_attachment_data_list, int *output_attachment_count);
+
+
+#endif /* EM_CORE_SMIME_H_ */
diff --git a/email-core/include/email-core-smtp.h b/email-core/include/email-core-smtp.h
new file mode 100755 (executable)
index 0000000..23b920c
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File :  email-core-smtp.h
+ * Desc :  Mail SMTP Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_SMTP_H__
+#define __EMAIL_CORE_SMTP_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include <stdio.h>
+#include "c-client.h"
+#include "email-internal-types.h"
+
+INTERNAL_FUNC int emcore_send_mail(int account_id, int input_mailbox_id, int mail_id, int *err_code);
+
+INTERNAL_FUNC int emcore_send_saved_mail(int account_id, char *mailbox, int *err_code);
+
+INTERNAL_FUNC int emcore_send_mail_with_downloading_attachment_of_original_mail(int input_mail_id);
+
+INTERNAL_FUNC int emcore_make_rfc822_file_from_mail(emstorage_mail_tbl_t *input_mail_tbl_data, emstorage_attachment_tbl_t *input_attachment_tbl_t, int input_attachment_count, ENVELOPE **env, char **file_path, email_option_t *sending_option, int *err_code);
+
+INTERNAL_FUNC int emcore_make_rfc822_file(email_mail_data_t *input_mail_tbl_data, email_attachment_data_t *input_attachment_tbl, int input_attachment_count, char **file_path, int *err_code);
+
+INTERNAL_FUNC int emcore_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas);
+
+INTERNAL_FUNC int emcore_add_read_receipt(int input_read_mail_id, int *output_receipt_mail_id);
+
+INTERNAL_FUNC int emcore_add_meeting_request(int account_id, int input_mailbox_id, email_meeting_request_t *meeting_req, int *err_code);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-core/include/email-core-sound.h b/email-core/include/email-core-sound.h
new file mode 100755 (executable)
index 0000000..f51cead
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <vconf-keys.h>
+#include <vconf.h>
+#include <mm_player.h>
+#include <mm_error.h>
+#include <mm_session_private.h>
+#include <alarm.h>
+#include <feedback.h>
+
+typedef enum
+{
+       EMAIL_SOUND_STATUS, 
+       EMAIL_VIBE_STATUS, 
+       EMAIL_ALERT_REP_TYPE, 
+       EMAIL_ALERT_VOLUME, 
+       EMAIL_ALERT_VIBE_STENGTH, 
+} EMAIL_SETTING_t;
+
+typedef enum
+{
+       EMAIL_ALERT_TYPE_MELODY, 
+       EMAIL_ALERT_TYPE_VIB, 
+       EMAIL_ALERT_TYPE_MELODY_AND_VIB, 
+       EMAIL_ALERT_TYPE_MUTE, 
+} EMAIL_ALERT_TYPE;
+
+typedef enum
+{
+       EMAIL_GCONF_VALUE_REPEAT_NONE = 0,
+       EMAIL_GCONF_VALUE_REPEAT_2MINS,
+       EMAIL_GCONF_VALUE_REPEAT_5MINS,
+       EMAIL_GCONF_VALUE_REPEAT_10MINS,
+} EMAIL_ALERT_REPEAT_ALARM;
+
+typedef enum
+{
+       SETTING_NOTI_STATUS_OFF    = 0,
+       SETTING_NOTI_STATUS_GLOBAL = 1, 
+       SETTING_NOTI_STATUS_EMAIL  = 2, 
+} EMAIL_NOTI_STATUS;
+
+#ifdef Min
+#undef Min
+#endif
+
+INTERNAL_FUNC int  emcore_start_thread_for_alerting_new_mails(int *err_code);
+INTERNAL_FUNC void emcore_start_alert();
diff --git a/email-core/include/email-core-task-manager.h b/email-core/include/email-core-task-manager.h
new file mode 100755 (executable)
index 0000000..9299cc6
--- /dev/null
@@ -0,0 +1,48 @@
+/*\r
+*  email-service\r
+*\r
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
+*\r
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
+*\r
+* Licensed under the Apache License, Version 2.0 (the "License");\r
+* you may not use this file except in compliance with the License.\r
+* You may obtain a copy of the License at\r
+*\r
+* http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*\r
+*/\r
+\r
+/*\r
+ * email-core-task-manager.h\r
+ *\r
+ *  Created on: 2012. 11. 1.\r
+ *      Author: kyuho.jo@samsung.com\r
+ */\r
+\r
+#ifndef EMAIL_CORE_TASK_MANAGER_H_\r
+#define EMAIL_CORE_TASK_MANAGER_H_\r
+\r
+#include "email-internal-types.h"\r
+#include "email-core-tasks.h"\r
+\r
+INTERNAL_FUNC int emcore_init_task_handler_array();\r
+INTERNAL_FUNC int emcore_free_task_handler_array();\r
+\r
+INTERNAL_FUNC int emcore_encode_task_parameter(email_task_type_t input_task_type, void *input_task_parameter_struct, char **output_byte_stream, int *output_stream_size);\r
+INTERNAL_FUNC int emcore_decode_task_parameter(email_task_type_t input_task_type, char *input_byte_stream, int input_stream_size, void **output_task_parameter_struct);\r
+\r
+INTERNAL_FUNC int emcore_add_task_to_task_table(email_task_type_t input_task_type, email_task_priority_t input_task_priority, char *input_task_parameter, int input_task_parameter_length, int *output_task_id);\r
+INTERNAL_FUNC int emcore_remove_task_from_task_table(int input_task_id);\r
+INTERNAL_FUNC int emcore_get_active_task_by_thread_id(thread_t input_thread_id, email_active_task_t **output_active_task);\r
+\r
+INTERNAL_FUNC int emcore_start_task_manager_loop();\r
+INTERNAL_FUNC int emcore_stop_task_manager_loop();\r
+\r
+#endif /* EMAIL_CORE_TASK_MANAGER_H_ */\r
diff --git a/email-core/include/email-core-tasks.h b/email-core/include/email-core-tasks.h
new file mode 100755 (executable)
index 0000000..033a621
--- /dev/null
@@ -0,0 +1,93 @@
+/*\r
+*  email-service\r
+*\r
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
+*\r
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
+*\r
+* Licensed under the Apache License, Version 2.0 (the "License");\r
+* you may not use this file except in compliance with the License.\r
+* You may obtain a copy of the License at\r
+*\r
+* http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*\r
+*/\r
+/*\r
+ * email-core-tasks.h\r
+ *\r
+ *  Created on: 2012. 11. 5.\r
+ *      Author: kyuho.jo@samsung.com\r
+ */\r
+\r
+#ifndef EMAIL_CORE_TASKS_H_\r
+#define EMAIL_CORE_TASKS_H_\r
+\r
+#include "email-internal-types.h"\r
+\r
+typedef struct\r
+{\r
+       email_task_type_t          task_type;\r
+       void*                    (*task_handler_function)(void*);\r
+       int                      (*task_parameter_encoder)(void*, char**, int*);\r
+       int                      (*task_parameter_decoder)(char*, int, void**);\r
+} email_task_handler_t;\r
+\r
+typedef struct\r
+{\r
+       int                       task_id;\r
+       email_task_type_t         task_type;\r
+       email_task_status_type_t  task_status;\r
+       email_task_priority_t     task_priority;\r
+       int                       task_parameter_length;\r
+       char                     *task_parameter;\r
+\r
+       /* Not be stored in DB*/\r
+       thread_t                  thread_id;\r
+       int                       active_task_id;\r
+} email_task_t;\r
+\r
+#define DECLARE_CONVERTER_FOR_TASK_PARAMETER(TASK_NAME) INTERNAL_FUNC int email_encode_task_parameter_##TASK_NAME(void *input_task_parameter_struct, char **output_byte_stream, int *output_stream_size); \\r
+               INTERNAL_FUNC int email_decode_task_parameter_##TASK_NAME(char *input_byte_stream, int input_stream_size, void **output_task_parameter_struct);\r
+\r
+/*-------------------------------------------------------------------------------------------*/\r
+/* to handle _EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT */\r
+typedef struct\r
+{\r
+       int  source_mailbox_id;\r
+       int  target_mailbox_id;\r
+       int  mail_id_count;\r
+       int *mail_id_array;\r
+} task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT;\r
+\r
+DECLARE_CONVERTER_FOR_TASK_PARAMETER(EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT);\r
+INTERNAL_FUNC void* task_handler_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT(void *param);\r
+\r
+/*-------------------------------------------------------------------------------------------*/\r
+/* to handle EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX */\r
+typedef struct\r
+{\r
+       int  account_id;\r
+       int  mailbox_id_count;\r
+       int *mailbox_id_array;\r
+       int  on_server;\r
+} task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX;\r
+\r
+DECLARE_CONVERTER_FOR_TASK_PARAMETER(EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX);\r
+INTERNAL_FUNC void* task_handler_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX(void *input_param);\r
+/*-------------------------------------------------------------------------------------------*/\r
+/* to handle EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL */\r
+typedef struct\r
+{\r
+       int  mail_id;\r
+} task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL;\r
+\r
+DECLARE_CONVERTER_FOR_TASK_PARAMETER(EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL);\r
+INTERNAL_FUNC void* task_handler_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL(void *input_param);\r
+/*-------------------------------------------------------------------------------------------*/\r
+#endif /* EMAIL_CORE_TASKS_H_ */\r
diff --git a/email-core/include/email-core-timer.h b/email-core/include/email-core-timer.h
new file mode 100755 (executable)
index 0000000..fd3f5bc
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 "email-internal-types.h"
+
+typedef void (*EMAIL_TIMER_CALLBACK)(void *a_pData);
+
+/**
+ * Callback for timeout action
+ *
+ * @param[in] a_pData                  Specifies the data passed to callback.
+ * @return This function returns true for repeat alerts or false for mail resend.
+ */
+INTERNAL_FUNC int emcore_timer_ex_callback(void *a_pData);
+
+/**
+ * Set timer
+ *
+ * @param[in] a_nSetTimeValue  Specifies the timeout value.
+ * @param[in] a_pCallBack              Specifies the Callback to be called on timeout
+ * @param[in] a_pData          Specifies the pointer to user data to be passed to Callback.
+ * @remarks N/A
+ * @return This function returns the timer id.
+ */
+INTERNAL_FUNC int emcore_set_timer_ex(long a_nSetTimeValue, EMAIL_TIMER_CALLBACK a_pCallBack, void *a_pData);
+
+/**
+ * Kill timer.
+ *
+ * @param[in] a_nTimerID               Specifies the timer id.
+ * @remarks N/A
+ * @return This function returns void.
+ */
+INTERNAL_FUNC void emcore_kill_timer_ex(int a_nTimerID);
diff --git a/email-core/include/email-core-utils.h b/email-core/include/email-core-utils.h
new file mode 100755 (executable)
index 0000000..07bf41e
--- /dev/null
@@ -0,0 +1,195 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File :  email-core-utils.h
+ * Desc :  Mail Utils Header
+ *
+ * Auth : 
+ *
+ * History : 
+ *    2006.08.16  :  created
+ *****************************************************************************/
+#ifndef __EMAIL_CORE_UTILS_H__
+#define __EMAIL_CORE_UTILS_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include "email-types.h"
+#include "email-internal-types.h"
+#include "email-storage.h"
+#include "email-core-global.h"
+#include "email-core-mail.h"
+
+/*  This is used for emcore_get_long_encoded_path */
+#define EMAIL_CONNECT_FOR_SENDING      -1
+#define        ENCODED_PATH_SMTP       "UHDF_ENCODED_PATH_SMTP_EKJD"
+
+typedef int (*email_get_unread_email_count_cb)(int unread, int *err_code);
+
+/* parse the Full mailbox Path and get the Alias Name of the Mailbox */
+char* emcore_get_alias_of_mailbox(const char *mailbox_path);
+
+/* Parse the Mailbox Path and get the Account Email address */
+int   emcore_get_temp_file_name(char **filename, int *err_code);
+int   emcore_get_long_encoded_path(int account_id, char *path, int delimiter, char **long_enc_path, int *err_code);
+int   emcore_get_encoded_mailbox_name(char *name, char **enc_name, int *err_code);
+int   emcore_get_file_name(char *path, char **filename, int *err_code);
+int   emcore_get_file_size(char *path, int *size, int *err_code);
+int   emcore_get_actual_mail_size(char *pBodyPlane, char *pBodyHtml, struct attachment_info *pAttachment, int *error_code);
+int   emcore_calc_mail_size(email_mail_data_t *mail_data_src, email_attachment_data_t *attachment_data_src, int attachment_count, int *error_code);
+int   emcore_get_address_count(char *addr_str, int *to_num, int *err_code);
+int   emcore_is_storage_full(int *error);
+int   emcore_get_long_encoded_path_with_account_info(email_account_t *account, char *path, int delimiter, char **long_enc_path, int *err_code);
+void  emcore_fill_address_information_of_mail_tbl(emstorage_mail_tbl_t *mail_data);
+
+
+INTERNAL_FUNC int   emcore_get_preview_text_from_file(const char *input_plain_path, const char *input_html_path, int input_preview_buffer_length, char **output_preview_buffer);
+int   reg_replace (char *input_source_text, char *input_old_pattern_string, char *input_new_string);
+int   emcore_strip_HTML(char *source_string);
+int   emcore_send_noti_for_new_mail(int account_id, char *mailbox_name, char *subject, char *from, char *uid, char *datetime);
+int   emcore_make_attachment_file_name_with_extension(char *source_file_name, char *sub_type, char *result_file_name, int result_file_name_buffer_length, int *err_code);
+
+/* Session Handling */
+int   emcore_get_empty_session(email_session_t **session);
+int   emcore_clear_session(email_session_t *session);
+int   emcore_get_current_session(email_session_t **session);
+
+INTERNAL_FUNC int emcore_display_unread_in_badge();
+INTERNAL_FUNC int emcore_set_network_error(int err_code);
+
+/* Transaction Handling */
+INTERNAL_FUNC int emcore_add_transaction_info(int mail_id , int handle  , int *err_code);
+INTERNAL_FUNC int emcore_get_handle_by_mailId_from_transaction_info(int mail_id , int *pHandle);
+INTERNAL_FUNC int emcore_delete_transaction_info_by_mailId(int mail_id);
+
+/* For notification bar */
+INTERNAL_FUNC int emcore_update_notification_for_unread_mail(int account_id);
+INTERNAL_FUNC int emcore_clear_all_notifications();
+//INTERNAL_FUNC int emcore_add_notification_for_unread_mail(emstorage_mail_tbl_t *input_mail_tbl_data);
+INTERNAL_FUNC int emcore_delete_notification_for_read_mail(int mail_id);
+INTERNAL_FUNC int emcore_delete_notification_by_account(int account_id);
+INTERNAL_FUNC int emcore_finalize_sync(int account_id, int *error);
+
+INTERNAL_FUNC int emcore_show_user_message(int id, email_action_t action, int error);
+
+#ifdef __FEATURE_BULK_DELETE_MOVE_UPDATE_REQUEST_OPTI__
+
+/**
+ * @fn emcore_convert_to_uid_range_set(email_id_set_t *id_set, int id_set_count, email_uid_range_set **uid_range_set, int range_len, int *err_code)
+ * Prepare a linked list of uid ranges with each node having a uid_range and lowest and highest uid in it.
+ *
+ *@author                                      h.gahlaut@samsung.com
+ * @param[in] id_set                   Specifies the array of mail_id and corresponding server_mail_id sorted by server_mail_ids in ascending order
+ * @param[in] id_set_count             Specifies the no. of cells in id_set array i.e. no. of sets of mail_ids and server_mail_ids
+ * @param[in] range_len                Specifies the maximum length of string of range allowed. 
+ * @param[out] uid_range_set   Returns the uid_ranges formed in the form of a linked list with head stored in uid_range_set pointer
+ * @param[out] err_code                Returns the error code.
+ * @remarks                                    An example of a uid_range formed is 2 : 6, 8, 10, 14 : 15, 89, 
+ *                                                     While using it the caller should remove the ending , (comma)                                    
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emcore_convert_to_uid_range_set(email_id_set_t *id_set, int id_set_count, email_uid_range_set **uid_range_set, int range_len, int *err_code);
+
+/**
+ * void emcore_free_uid_range_set(email_uid_range_set **uid_range_head)
+ * Frees the linked list of uid ranges 
+ *
+ * @author                                     h.gahlaut@samsung.com
+ * @param[in] uid_range_head   Head pointer of linked list of uid ranges               
+ * @remarks                                                                    
+ * @return This function does not return anything.
+ */
+INTERNAL_FUNC void emcore_free_uid_range_set(email_uid_range_set **uid_range_set);
+
+/**
+ * @fn emcore_append_subset_string_to_uid_range(char *subset_string, email_uid_range_set **uid_range_set, int range_len, unsigned long luid, unsigned long huid)
+ * Appends the subset_string to uid range if the uid range has not exceeded maximum length(range_len), otherwise creates a new node in linked list of uid range set 
+ * and stores the subset_string in its uid_range. Also sets the lowest and highest uids for the corresponsing uid_range
+ * 
+ * @author                                     h.gahlaut@samsung.com
+ * @param[in] subset_string            Specifies the subset string to be appended. A subset string can be like X : Y or X where X and Y are uids.
+ * @param[in] range_len                Specifies the maximum length of range string allowed. 
+ * @param[in] luid                             Specifies the lowest uid in subset string
+ * @param[in] huid                             Specifies the highest uid in subset string
+ * @param[out] uid_range_set   Returns the uid_ranges formed in the form of a linked list with head stored in uid_range_set pointer
+ * @param[out] err_code                Returns the error code.
+ * @remarks                                                                            
+ * @return This function returns true on success or false on failure.
+ */
+int emcore_append_subset_string_to_uid_range(char *subset_string, email_uid_range_set **current_node_adr, email_uid_range_set **uid_range_set, int range_len, unsigned long luid, unsigned long huid);
+
+/**
+ * @fn emcore_form_comma_separated_strings(int numbers[], int num_count, int max_string_len, char ***strings, int *string_count, int *err_code)
+ * Forms comma separated strings of a give max_string_len from an array of numbers 
+ * 
+ * @author                                     h.gahlaut@samsung.com
+ * @param[in] numbers                  Specifies the array of numbers to be converted into comma separated strings.
+ * @param[in] num_count                Specifies the count of numbers in numbers array. 
+ * @param[in] max_string_len   Specifies the maximum length of comma separated strings that are to be formed.
+ * @param[out] strings                 Returns the base address of a double dimension array which stores the strings.
+ * @param[out] string_count            Returns the number of strings formed.
+ * @param[out] err_code                Returns the error code.
+ * @remarks                                    If Input to the function is five numbers like 2755 2754 2748 2749 2750 and a given max_string_len is 20.
+ *                                                     Then this function will form two comma separated strings as follows -
+ *                                                     "2755, 2754, 2748"
+ *                                                     "2749, 2750"
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emcore_form_comma_separated_strings(int numbers[], int num_count, int max_string_len, char ***strings, int *string_count, int *err_code);
+
+/**
+ * @fn emcore_free_comma_separated_strings(char ***string_list, int *string_count)
+ * Frees the double dimensional array of strings. 
+ *
+ * @author                                     h.gahlaut@samsung.com
+ * @param[in] uid_range_head   Address of base address of double dimensional array of strings.
+ * @param[in] string_count             Address of variable holding the count of strings.
+ * @remarks                                                                    
+ * @return This function does not return anything.
+ */
+
+INTERNAL_FUNC void emcore_free_comma_separated_strings(char ***string_list, int *string_count);
+
+#endif
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+/*  Added to get next activity id sequence */
+INTERNAL_FUNC int emcore_get_next_activity_id(int *activity_id, int *err_code);
+INTERNAL_FUNC int emcore_add_activity(emstorage_activity_tbl_t *new_activity, int *err_code);
+INTERNAL_FUNC int emcore_delete_activity(emstorage_activity_tbl_t *activity, int *err_code);
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+
+INTERNAL_FUNC void emcore_free_rule(email_rule_t* rule);
+
+INTERNAL_FUNC int emcore_search_string_from_file(char *file_path, char *search_string, int *result);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* __EMAIL_CORE_UTILS_H__ */
diff --git a/email-daemon/CMakeLists.txt b/email-daemon/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..316f1f5
--- /dev/null
@@ -0,0 +1,54 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(email-service)
+
+SET(CMAKE_SKIP_BUILD_RPATH TRUE)
+
+IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+       SET(CMAKE_BUILD_TYPE "Debug")
+ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+
+MESSAGE("")
+MESSAGE(">>> current directory: ${CMAKE_CURRENT_SOURCE_DIR}")
+MESSAGE(">>> Build type: ${CMAKE_BUILD_TYPE}")
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden")
+
+##########################################################
+# Define Execute File
+##########################################################
+
+SET(MAIN-SRCS 
+       ${CMAKE_SOURCE_DIR}/email-daemon/main.c
+       ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-init.c
+       ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-account.c
+       ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-mail.c
+       ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-mailbox.c
+       ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-etc.c
+       ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-emn.c
+       ${CMAKE_SOURCE_DIR}/email-daemon/email-daemon-auto-poll.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/include
+       ${CMAKE_SOURCE_DIR}/email-api/include
+       ${CMAKE_SOURCE_DIR}/email-core/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
+       ${CMAKE_SOURCE_DIR}/email-daemon/include
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(main_pkgs REQUIRED glib-2.0 dlog dbus-1 gthread-2.0  db-util openssl uw-imap-toolkit vconf contacts-service2 alarm-service mm-player drm-client feedback)
+
+
+FOREACH(flag ${main_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_EXECUTABLE(${PROJECT_NAME} ${MAIN-SRCS})
+TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${main_pkgs_LDFLAGS} dl ssl email-core email-storage email-network email-ipc email-common-use)
+INSTALL(TARGETS ${PROJECT_NAME} DESTINATION bin)
+
diff --git a/email-daemon/email-daemon-account.c b/email-daemon/email-daemon-account.c
new file mode 100755 (executable)
index 0000000..587d884
--- /dev/null
@@ -0,0 +1,762 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File: emf-account.c
+ * Desc: email-daemon Account
+ *
+ * Auth:
+ *
+ * History:
+ *    2006.08.16 : created
+ *****************************************************************************/
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <vconf.h>
+
+#include "email-daemon.h"
+#include "email-storage.h"
+#include "c-client.h"
+#include "email-debug-log.h"
+#include "email-daemon-account.h"
+#include "email-daemon-auto-poll.h"
+#include <contacts.h>
+#include "email-types.h"
+#include "email-core-account.h"
+#include "email-core-event.h"
+#include "email-core-utils.h"
+#include "email-utilities.h"
+#include "email-convert.h"
+
+static int emdaemon_check_filter_id(int account_id, int filter_id, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], filter_id[%d], err_code[%p]", account_id, filter_id, err_code);
+
+       if (account_id != ALL_ACCOUNT) {                /*  only global rule supported. */
+               EM_DEBUG_EXCEPTION(" account_id[%d], filter_id[%d]", account_id, filter_id);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_rule_tbl_t* filter = NULL;
+
+       if (!emstorage_get_rule_by_id(account_id, filter_id, &filter, true, &err)) {
+               EM_DEBUG_EXCEPTION(" emstorage_get_rule_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (filter != NULL)
+               emstorage_free_rule(&filter, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_create_account(email_account_t* account, int* err_code)
+{
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emcore_create_account(account, &err)) {
+               EM_DEBUG_EXCEPTION(" emcore_account_add failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       emcore_init_account_reference();
+
+       ret = true;
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_delete_account(int account_id, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret;
+
+       ret = emcore_delete_account(account_id, err_code);
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+static email_account_t* duplicate_account(email_account_t *src)
+{
+       if(!src) {
+               EM_DEBUG_EXCEPTION("INVALID_PARAM");
+               return NULL;
+       }
+       email_account_t *dst = (email_account_t *)em_malloc(sizeof(email_account_t));
+       if (!dst) {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               return NULL;
+       }
+
+       /* Need deep copy */
+       memcpy(dst, src, sizeof(email_account_t));
+       dst->account_name              = EM_SAFE_STRDUP(src->account_name);
+       dst->incoming_server_address   = EM_SAFE_STRDUP(src->incoming_server_address);
+       dst->user_email_address        = EM_SAFE_STRDUP(src->user_email_address);
+       dst->incoming_server_user_name = EM_SAFE_STRDUP(src->incoming_server_user_name);
+       dst->incoming_server_password  = EM_SAFE_STRDUP(src->incoming_server_password);
+       dst->outgoing_server_address   = EM_SAFE_STRDUP(src->outgoing_server_address);
+       dst->outgoing_server_user_name = EM_SAFE_STRDUP(src->outgoing_server_user_name);
+       dst->outgoing_server_password  = EM_SAFE_STRDUP(src->outgoing_server_password);
+       dst->user_display_name         = EM_SAFE_STRDUP(src->user_display_name);
+       dst->reply_to_address          = EM_SAFE_STRDUP(src->reply_to_address);
+       dst->return_address            = EM_SAFE_STRDUP(src->return_address);
+       dst->logo_icon_path            = EM_SAFE_STRDUP(src->logo_icon_path);
+       dst->certificate_path              = EM_SAFE_STRDUP(src->certificate_path);
+       dst->options.display_name_from = EM_SAFE_STRDUP(src->options.display_name_from);
+       dst->options.signature         = EM_SAFE_STRDUP(src->options.signature);
+       dst->user_data                = (void*) em_malloc(src->user_data_length);
+       if( !dst->user_data ) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               emcore_free_account(dst);
+               EM_SAFE_FREE(dst);
+               return NULL;
+       }
+
+       memcpy(dst->user_data, src->user_data, src->user_data_length);
+
+       return dst;
+}
+
+INTERNAL_FUNC int emdaemon_validate_account(int account_id, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], handle[%p], err_code[%p]", account_id, handle, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_event_t event_data = {0};
+       email_account_t* ref_account = NULL;
+
+       if (account_id < 1)  {
+               EM_DEBUG_EXCEPTION(" account_id[%d]", account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!(ref_account = emcore_get_account_reference(account_id))) {
+               EM_DEBUG_EXCEPTION(" emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       event_data.type = EMAIL_EVENT_VALIDATE_ACCOUNT;
+       event_data.event_param_data_1 = NULL;
+       event_data.event_param_data_3 = NULL;
+       event_data.account_id = account_id;
+
+       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_insert_event falied [%d]", err);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_validate_account_and_create(email_account_t* new_account, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%p], handle[%p], err_code[%p]", new_account, handle, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_event_t event_data = {0};
+
+       event_data.type = EMAIL_EVENT_VALIDATE_AND_CREATE_ACCOUNT;
+       event_data.event_param_data_1 = (void*) new_account;
+       event_data.event_param_data_3 = NULL;
+       event_data.account_id = NEW_ACCOUNT_ID;
+
+       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_insert_event falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_update_account(int account_id, email_account_t* new_account, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], new_account[%p], err_code[%p]", account_id, new_account, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *new_account_tbl = NULL;
+       email_account_t old_account_info = {0};
+
+       if ((account_id <= 0) || !new_account)  {
+               EM_DEBUG_EXCEPTION("Invalid Parameters.");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if(!emdaemon_get_account(account_id, GET_FULL_DATA, &old_account_info, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_get_account failed ");
+               goto FINISH_OFF;
+       }
+
+       EM_DEBUG_LOG("new_account->email_addr[%s]", new_account->user_email_address);
+       if(new_account->user_email_address) {
+               if (!em_verify_email_address(new_account->user_email_address, true, &err)) {
+                       err = EMAIL_ERROR_INVALID_ADDRESS;
+                       EM_DEBUG_EXCEPTION("Invalid Email Address");
+                       goto FINISH_OFF;
+               }
+       }
+
+       new_account_tbl = em_malloc(sizeof(emstorage_account_tbl_t));
+       if(!new_account_tbl) {
+               EM_DEBUG_EXCEPTION("allocation failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       em_convert_account_to_account_tbl(new_account, new_account_tbl);
+
+       if (!emstorage_update_account(account_id, new_account_tbl, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_update_account falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       emcore_init_account_reference();
+
+#ifdef __FEATURE_AUTO_POLLING__
+       int  old_check_interval = old_account_info.check_interval;
+       if( old_check_interval < 0 && new_account->check_interval > 0) {
+               if(!emdaemon_add_polling_alarm(account_id, new_account->check_interval))
+                       EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm[ CHANGEACCOUNT] : start auto poll failed >>> ");
+
+       }
+       else if( (old_check_interval > 0) && (new_account->check_interval < 0)) {
+               if(!emdaemon_remove_polling_alarm(account_id))
+                       EM_DEBUG_EXCEPTION("emdaemon_remove_polling_alarm[ CHANGEACCOUNT] : start auto poll failed >>> ");
+       }
+       else if(old_check_interval != new_account->check_interval && new_account->check_interval > 0) {
+               if(!emdaemon_remove_polling_alarm(account_id)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_remove_polling_alarm[ CHANGEACCOUNT] : start auto poll failed >>> ");
+                       goto FINISH_OFF;
+               }
+               if(!emdaemon_add_polling_alarm(account_id, new_account->check_interval))
+                       EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm[ CHANGEACCOUNT] : start auto poll failed >>> ");
+       }
+#endif
+
+       ret = true;
+
+FINISH_OFF:
+
+       emcore_free_account(&old_account_info);
+
+       if(new_account_tbl)
+               emstorage_free_account(&new_account_tbl, 1, NULL);
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_validate_account_and_update(int old_account_id, email_account_t* new_account_info, int *handle,int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account[%d], new_account_info[%p], handle[%p], err_code[%p]", old_account_id, new_account_info, handle, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_event_t event_data = {0};
+
+       event_data.type = EMAIL_EVENT_VALIDATE_AND_UPDATE_ACCOUNT;
+       event_data.event_param_data_1 = (char *) duplicate_account(new_account_info);
+       event_data.event_param_data_3 = NULL;
+       event_data.account_id = old_account_id;
+
+#if 0
+       email_account_t *pAccount = (email_account_t *)em_malloc(sizeof(email_account_t));
+       if (pAccount == NULL) {
+               EM_DEBUG_EXCEPTION(" malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       /* Need deep copy */
+       memcpy(pAccount, new_account_info, sizeof(email_account_t));
+       pAccount->account_name              = EM_SAFE_STRDUP(new_account_info->account_name);
+       pAccount->incoming_server_address   = EM_SAFE_STRDUP(new_account_info->incoming_server_address);
+       pAccount->user_email_address        = EM_SAFE_STRDUP(new_account_info->user_email_address);
+       pAccount->incoming_server_user_name = EM_SAFE_STRDUP(new_account_info->user_email_address);
+       pAccount->incoming_server_password  = EM_SAFE_STRDUP(new_account_info->incoming_server_password);
+       pAccount->outgoing_server_address   = EM_SAFE_STRDUP(new_account_info->incoming_server_password);
+       pAccount->outgoing_server_user_name = EM_SAFE_STRDUP(new_account_info->outgoing_server_user_name);
+       pAccount->outgoing_server_password  = EM_SAFE_STRDUP(new_account_info->outgoing_server_password);
+       pAccount->user_display_name         = EM_SAFE_STRDUP(new_account_info->user_display_name);
+       pAccount->reply_to_address          = EM_SAFE_STRDUP(new_account_info->reply_to_address);
+       pAccount->return_address            = EM_SAFE_STRDUP(new_account_info->return_address);
+       pAccount->logo_icon_path            = EM_SAFE_STRDUP(new_account_info->logo_icon_path);
+       pAccount->certificate_path                      = EM_SAFE_STRDUP(new_account_info->certificate_path);
+       pAccount->options.display_name_from = EM_SAFE_STRDUP(new_account_info->options.display_name_from);
+       pAccount->options.signature             = EM_SAFE_STRDUP(new_account_info->options.signature);
+       memcpy(pAccount->user_data, new_account_info->user_data, new_account_info->user_data_length);
+#endif
+
+       if (!emcore_insert_event(&event_data, (int*)handle, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_get_account(int account_id, int pulloption, email_account_t* account, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], pulloption [%d], account[%p], err_code[%p]", account_id, pulloption, account, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *account_tbl = NULL;
+
+       if (!account)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], account[%p]", account_id, account);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_account_by_id(account_id, pulloption, &account_tbl, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       em_convert_account_tbl_to_account(account_tbl, account);
+
+       ret = true;
+
+FINISH_OFF:
+       if(account_tbl)
+               emstorage_free_account(&account_tbl, 1, NULL);
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_get_account_list(email_account_t** account_list, int* count, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_list[%p], count[%p], err_code[%p]", account_list, count, err_code);
+
+       int ret = false, err = EMAIL_ERROR_NONE, i = 0;
+       emstorage_account_tbl_t *account_tbl_array = NULL;
+
+       if (!account_list || !count)  {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       *count = 1000;
+
+       if (!emstorage_get_account_list(count, &account_tbl_array, true, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(account_tbl_array && (*count) > 0) {
+               *account_list = (email_account_t*)em_malloc(sizeof(email_account_t) * (*count));
+               if(!*account_list) {
+                       EM_DEBUG_EXCEPTION("allocation failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               for(i = 0 ; i < (*count); i++)
+                       em_convert_account_tbl_to_account(account_tbl_array + i, (*account_list) + i);
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if(account_tbl_array)
+               emstorage_free_account(&account_tbl_array, (*count), NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_free_account(email_account_t** account_list, int count, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       return emcore_free_account_list(account_list, count, err_code);
+}
+
+
+INTERNAL_FUNC int emdaemon_get_filter(int filter_id, email_rule_t** filter_info, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_id[%d], filter_info[%p], err_code[%p]", filter_id, filter_info, err_code);
+
+       if (!filter_info) {
+               EM_DEBUG_EXCEPTION("filter_id[%d], filter_info[%p]", filter_id, filter_info);
+
+               if (err_code != NULL)
+                       *err_code = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!emstorage_get_rule_by_id(ALL_ACCOUNT, filter_id, (emstorage_rule_tbl_t**)filter_info, true, &err))  {
+               EM_DEBUG_EXCEPTION(" emstorage_get_rule_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_get_filter_list(email_rule_t** filter_info, int* count, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_info[%p], count[%p], err_code[%p]", filter_info, count, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int is_completed;
+
+       if (!filter_info || !count)  {
+               EM_DEBUG_EXCEPTION(" filter_info[%p], count[%p]", filter_info, count);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       *count = 1000;
+
+       if (!emstorage_get_rule(ALL_ACCOUNT, 0, 0, count, &is_completed, (emstorage_rule_tbl_t**)filter_info, true, &err))  {
+               EM_DEBUG_EXCEPTION(" emstorage_get_rule failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_find_filter(email_rule_t* filter_info, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_info[%p], err_code[%p]", filter_info, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!filter_info)  {
+               EM_DEBUG_EXCEPTION(" filter_info[%p]", filter_info);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (filter_info->faction == EMAIL_FILTER_MOVE && !filter_info->target_mailbox_id) {
+               EM_DEBUG_EXCEPTION(" filter_info->faction[%d], filter_info->target_mailbox_id[%d]", filter_info->faction, filter_info->target_mailbox_id);
+               err = EMAIL_ERROR_INVALID_FILTER;
+               goto FINISH_OFF;
+       }
+
+       filter_info->account_id = ALL_ACCOUNT;          /*  MUST BE */
+
+       if (!emstorage_find_rule((emstorage_rule_tbl_t*)filter_info, true, &err))  {
+               EM_DEBUG_EXCEPTION(" emstorage_find_rule failed [%d]", err);
+               err = EMAIL_ERROR_FILTER_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_add_filter(email_rule_t* filter_info)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_info[%p]", filter_info);
+
+       /*  default variable */
+       int err = EMAIL_ERROR_NONE;
+       if (!filter_info || !(filter_info->value))  {
+               EM_DEBUG_EXCEPTION("filter_info[%p]", filter_info);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /*
+       if (filter_info->faction != EMAIL_FILTER_BLOCK)  {
+               EM_DEBUG_EXCEPTION("filter_info->faction[%d] is not supported", filter_info->faction);
+               err = EMAIL_ERROR_NOT_SUPPORTED;
+               goto FINISH_OFF;
+       }
+
+       if (filter_info->faction == EMAIL_FILTER_MOVE && !filter_info->mailbox)  {
+               EM_DEBUG_EXCEPTION("filter_info->faction[%d], filter_info->mailbox[%p]", filter_info->faction, filter_info->mailbox);
+               err = EMAIL_ERROR_INVALID_FILTER;
+               goto FINISH_OFF;
+       }
+       */
+
+       filter_info->account_id = ALL_ACCOUNT;
+
+       if (emstorage_find_rule((emstorage_rule_tbl_t*)filter_info, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_find_rule failed [%d]", err);
+               err = EMAIL_ERROR_ALREADY_EXISTS;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_add_rule((emstorage_rule_tbl_t*)filter_info, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_add_rule failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (filter_info->type == EMAIL_PRIORITY_SENDER) {
+               EM_DEBUG_LOG("Priority Sender add");
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_mail_filter_by_rule((email_rule_t*)filter_info, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_mail_filter_by_rule failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END();
+       return err;
+}
+
+INTERNAL_FUNC int emdaemon_update_filter(int filter_id, email_rule_t* filter_info, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_id[%d], filter_info[%p], err_code[%p]", filter_id, filter_info, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if ((filter_id <= 0) || !filter_info)  {
+               EM_DEBUG_EXCEPTION("filter_id[%d], filter_info[%p]", filter_id, filter_info);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emdaemon_check_filter_id(ALL_ACCOUNT, filter_id, &err))  {
+               EM_DEBUG_EXCEPTION("emdaemon_check_filter_id falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_change_rule(ALL_ACCOUNT, filter_id, (emstorage_rule_tbl_t*)filter_info, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_change_rule falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_delete_filter(int filter_id, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_id[%d, err_code[%p]", filter_id, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (filter_id <= 0)  {
+               EM_DEBUG_EXCEPTION(" fliter_id[%d]", filter_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emdaemon_check_filter_id(ALL_ACCOUNT, filter_id, &err))  {
+               EM_DEBUG_EXCEPTION(" emdaemon_check_filter_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_delete_rule(ALL_ACCOUNT, filter_id, true, &err))  {
+               EM_DEBUG_EXCEPTION(" emstorage_delete_rule failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_free_filter(email_rule_t** filter_info, int count, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("filter_info[%p], count[%d], err_code[%p]", filter_info, count, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (count > 0)  {
+               if (!filter_info || !*filter_info)  {
+                       EM_DEBUG_EXCEPTION(" filter_info[%p], count[%d]", filter_info, count);
+                       err = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+
+               email_rule_t* p = *filter_info;
+               int i;
+
+               for (i = 0; i < count; i++)  {
+                       EM_SAFE_FREE(p[i].value);
+               }
+
+               EM_SAFE_FREE(p); *filter_info  = NULL;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+/* ----- internal functions --------------------------------------------*/
+int emdaemon_initialize_account_reference()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+
+       if ((err = emcore_init_account_reference()) != EMAIL_ERROR_NONE) {
+               if (err == EMAIL_ERROR_SECURED_STORAGE_FAILURE) {
+                       if ((err = emcore_recover_from_secured_storage_failure()) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emcore_recover_from_secured_storage_failure failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+
+                       if ((err = emcore_init_account_reference()) != EMAIL_ERROR_NONE) {
+                               EM_DEBUG_EXCEPTION("emcore_init_account_reference failed [%d]", err);
+                               goto FINISH_OFF;
+                       }
+               }
+               else {
+                       EM_DEBUG_EXCEPTION("emcore_init_account_reference failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emdaemon_insert_accountinfo_to_contact(email_account_t* account)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if(!account)
+               return false;
+
+       int ret = false;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_update_accountinfo_to_contact(email_account_t* old_account, email_account_t* new_account)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if(!old_account || !new_account)
+               return false;
+
+       int ret = false;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+/* EOF */
diff --git a/email-daemon/email-daemon-auto-poll.c b/email-daemon/email-daemon-auto-poll.c
new file mode 100755 (executable)
index 0000000..bedd7ff
--- /dev/null
@@ -0,0 +1,474 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 "email-internal-types.h"
+
+#ifdef __FEATURE_AUTO_POLLING__
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <stdarg.h>    /*  Needed for the definition of va_list */
+#include <glib.h>
+
+#include "email-types.h"
+#include "email-daemon.h"
+#include "email-daemon-auto-poll.h"
+#include "email-core-utils.h"
+#include "email-debug-log.h"
+#include "email-storage.h"
+#include "email-utilities.h"
+
+typedef struct _emf_account_alarm_binder
+{
+           int account_id;
+           alarm_id_t  alarm_id;
+           int timer_interval;
+} email_account_alarm_binder;
+
+/*  global  list */
+typedef struct _emf_account_alarm_binder_list_t
+{
+    email_account_alarm_binder account_alarm_binder;
+    struct _emf_account_alarm_binder_list_t  *next;
+}email_account_alarm_binder_list_t;
+
+/* sowmya.kr@samsung.com, 23022010, Implementation of auto-polling feature */
+
+email_account_alarm_binder_list_t *g_account_alarm_binder_list  = NULL;
+
+static int _emdaemon_get_polling_alarm_and_timerinterval(int account_id, alarm_id_t *alarm_id, int *timer_interval);
+static int _emdaemon_get_polling_account_and_timeinterval(alarm_id_t  alarm_id, int *account_id, int *timer_interval);
+static int _emdaemon_create_alarm(int alarm_interval, alarm_id_t *p_alarm_id);
+static int _emdaemon_add_to_account_alarm_binder_list(email_account_alarm_binder_list_t *p_account_alarm_binder);
+static int _emdaemon_remove_from_account_alarm_binder_list(int account_id);
+static int _emdaemon_update_account_alarm_binder_list(int account_id, alarm_id_t  alarm_id);
+
+INTERNAL_FUNC int emdaemon_add_polling_alarm(int account_id, int alarm_interval)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if(!account_id || (alarm_interval <= 0)) {
+               EM_DEBUG_EXCEPTION("Invalid param");
+               return false;
+       }
+       EM_DEBUG_EXCEPTION(" emdaemon_add_polling_alarm : account_id [%d]",account_id);
+       if(emdaemon_check_auto_polling_started(account_id)) {
+               EM_DEBUG_EXCEPTION("auto polling already started for account : return");
+               return true;
+       }
+
+       alarm_id_t alarmID = 0;
+       email_account_alarm_binder_list_t *p_account_alarm_binder = NULL;
+
+       if(!_emdaemon_create_alarm(alarm_interval, &alarmID)) {
+               EM_DEBUG_EXCEPTION("_emdaemon_create_alarm failed");
+               return false;
+       }
+
+       p_account_alarm_binder = (email_account_alarm_binder_list_t*)em_malloc(sizeof(email_account_alarm_binder_list_t));
+       if(!p_account_alarm_binder) {
+               EM_DEBUG_EXCEPTION("malloc  Failed ");
+               return false;
+       }
+
+       p_account_alarm_binder->account_alarm_binder.account_id = account_id;
+       p_account_alarm_binder->account_alarm_binder.alarm_id = alarmID;
+       p_account_alarm_binder->account_alarm_binder.timer_interval = alarm_interval;
+
+       _emdaemon_add_to_account_alarm_binder_list(p_account_alarm_binder);
+
+       return  true;
+}
+
+
+INTERNAL_FUNC int emdaemon_remove_polling_alarm(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if(!account_id) {
+               EM_DEBUG_EXCEPTION("Invalid param ");
+               return false;
+       }
+
+       alarm_id_t  alarm_id = 0;
+       int a_nErrorCode = 0, retval =0;
+
+       if(!_emdaemon_get_polling_alarm_and_timerinterval(account_id,&alarm_id,NULL)) {
+               EM_DEBUG_EXCEPTION("_emdaemon_get_polling_alarm_and_timerinterval failed");
+               return false;
+       }
+
+       /* delete alarm */
+       if (alarm_id > 0) {
+               a_nErrorCode = alarmmgr_remove_alarm(alarm_id);
+
+               EM_DEBUG_LOG("ErrorCode :%d, Return Value:%d ",a_nErrorCode,retval);
+
+               if(!retval)
+                       return false;
+       }
+
+       /* delete from list */
+       if(!_emdaemon_remove_from_account_alarm_binder_list(account_id)) {
+               EM_DEBUG_EXCEPTION("_emdaemon_remove_from_account_alarm_binder_list  failed");
+               return false;
+       }
+
+       return true;
+}
+
+INTERNAL_FUNC int emdaemon_check_auto_polling_started(int account_id)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if(g_account_alarm_binder_list == NULL) {
+               EM_DEBUG_EXCEPTION("g_account_alarm_binder_list NULL ");
+               return false;
+       }
+
+       email_account_alarm_binder_list_t  *p_temp = g_account_alarm_binder_list;
+       int match_found = false;
+
+       while(p_temp != NULL) {
+               if(p_temp->account_alarm_binder.account_id == account_id) {
+                       EM_DEBUG_EXCEPTION("account match found : polling already started");
+                       match_found = true;
+                       break;
+               }
+               p_temp = p_temp->next;
+       }
+
+       if(!match_found) {
+               EM_DEBUG_EXCEPTION("account match not found : polling not started");
+               return false;
+       }
+       return true;
+}
+
+INTERNAL_FUNC int emdaemon_alarm_polling_cb(alarm_id_t  alarm_id, void* user_param)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       email_mailbox_t mailbox = {0};
+       int account_id = 0, err = EMAIL_ERROR_NONE, timer_interval =0, alarmID =0,ret = false;
+       char* mailbox_name = NULL;
+
+       time_t ct = time(&ct);
+       struct tm* lt = localtime(&ct);
+
+       if (lt) {
+               EM_DEBUG_LOG( "Current Time :  [%d-%d-%d %d:%d:%d] ",
+                       lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
+                       lt->tm_hour, lt->tm_min, lt->tm_sec);
+       }
+
+       if(!_emdaemon_get_polling_account_and_timeinterval(alarm_id,&account_id,&timer_interval)) {
+               EM_DEBUG_EXCEPTION("email_get_polling_account failed");
+               return false;
+       }
+
+       EM_DEBUG_EXCEPTION(" emdaemon_alarm_polling_cb : account_id [%d]",account_id);
+       /* create alarm, for polling */
+       if(!_emdaemon_create_alarm(timer_interval,&alarmID)) {
+               EM_DEBUG_EXCEPTION("_emdaemon_create_alarm failed");
+               return false;
+       }
+
+       /*update alarm ID in list */
+       /* delete from list */
+       if(!_emdaemon_update_account_alarm_binder_list(account_id,alarmID)) {
+               EM_DEBUG_EXCEPTION("_emdaemon_update_account_alarm_binder_list  failed");
+               return false;
+       }
+
+       memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+       mailbox.account_id = account_id;
+
+       if (!emstorage_get_mailbox_name_by_mailbox_type(mailbox.account_id,EMAIL_MAILBOX_TYPE_INBOX,&mailbox_name, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       mailbox.mailbox_name = mailbox_name;
+
+       if (!emdaemon_sync_header(account_id, mailbox.mailbox_id, NULL, &err))  {
+               EM_DEBUG_EXCEPTION("emdaemon_sync_header falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+FINISH_OFF :
+
+       EM_SAFE_FREE(mailbox_name);
+
+       return ret;
+}
+
+static int _emdaemon_get_polling_alarm_and_timerinterval(int account_id, alarm_id_t *alarm_id, int *timer_interval)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if(!account_id || !alarm_id)
+               return false;
+
+       if(g_account_alarm_binder_list == NULL) {
+               EM_DEBUG_EXCEPTION("g_account_alarm_binder_list NULL ");
+               return false;
+       }
+
+       email_account_alarm_binder_list_t  *p_temp = g_account_alarm_binder_list;
+       int match_found = false;
+
+       while(p_temp != NULL) {
+               if(p_temp->account_alarm_binder.account_id == account_id) {
+                       EM_DEBUG_EXCEPTION("account match found ");
+                       *alarm_id =  p_temp->account_alarm_binder.alarm_id;
+
+                       if(timer_interval)
+                               *timer_interval = p_temp->account_alarm_binder.timer_interval;
+
+                       match_found = true;
+                       break;
+               }
+
+               p_temp = p_temp->next;
+       }
+
+       if(!match_found) {
+               EM_DEBUG_EXCEPTION("account match not found ");
+               return false;
+       }
+
+
+       return true;
+}
+
+static int _emdaemon_get_polling_account_and_timeinterval(alarm_id_t  alarm_id, int *account_id, int *timer_interval)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if(!alarm_id || !account_id)
+               return false;
+
+       if(g_account_alarm_binder_list == NULL) {
+               EM_DEBUG_EXCEPTION("g_account_alarm_binder_list NULL ");
+               return false;
+       }
+
+       email_account_alarm_binder_list_t  *p_temp = g_account_alarm_binder_list;
+       int match_found = false;
+
+       while(p_temp != NULL) {
+               if(p_temp->account_alarm_binder.alarm_id == alarm_id) {
+                       EM_DEBUG_EXCEPTION("aalrm match found ");
+                       *account_id =  p_temp->account_alarm_binder.account_id;
+
+                       if(timer_interval)
+                               *timer_interval = p_temp->account_alarm_binder.timer_interval;
+
+                       match_found = true;
+                       break;
+               }
+
+               p_temp = p_temp->next;
+       }
+
+       if(!match_found) {
+               EM_DEBUG_EXCEPTION("aalrm  match not found ");
+               return false;
+       }
+
+       return true;
+}
+
+#define AUTO_POLL_DESTINATION  "com.samsung.email-service"
+static int _emdaemon_create_alarm(int alarm_interval, alarm_id_t *p_alarm_id)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       /*      tzset(); */
+       time_t ct = time(&ct);
+       struct tm* lt = localtime(&ct);
+
+       if (lt) {
+               EM_DEBUG_LOG( "Current Time : [%d-%d-%d %d:%d:%d] ",
+                       lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
+                       lt->tm_hour, lt->tm_min, lt->tm_sec);
+       }
+
+       /*      alarm_info_t alarm_info = {0};   */
+       int a_nErrorCode = 0;
+
+       if((alarm_interval <= 0) || !p_alarm_id) {
+               EM_DEBUG_EXCEPTION("Invalid param ");
+               return false;
+       }
+
+       /*      time_t current_time = {0}; */
+       /*      struct tm current_tm = {0};      */
+       /* Fill alarm info */
+       /*      int                     timeFormat = 0; */ /*0 means 12hrs , 1 means 24hrs*/
+
+       /* TO DO, need to findout header for DBG_MID_MSGPORTING_NORMAL and then we have to use this */
+       /* error_code = vconf_get_int(DBG_MID_MSGPORTING_NORMAL, &timeFormat); */
+
+       a_nErrorCode = alarmmgr_init(AUTO_POLL_DESTINATION);
+       if (a_nErrorCode != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("alarmmgr_init failed : ErrorCode[%d]",a_nErrorCode);
+               return false;
+       }
+
+       a_nErrorCode = alarmmgr_set_cb(emdaemon_alarm_polling_cb, NULL);
+       if (a_nErrorCode != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("alarmmgr_set_cb : ErrorCode[%d]",a_nErrorCode);
+               return false;
+       }
+
+       a_nErrorCode = alarmmgr_add_alarm(ALARM_TYPE_VOLATILE, alarm_interval * 60 /*(sec)*/, ALARM_REPEAT_MODE_ONCE, AUTO_POLL_DESTINATION, p_alarm_id); /*prevent 23154*/
+       if (a_nErrorCode != ALARMMGR_RESULT_SUCCESS) {
+               EM_DEBUG_EXCEPTION("alarmmgr_add_alarm : ErrorCode[%d]",a_nErrorCode);
+               return false;
+       }
+
+       return true;
+}
+
+INTERNAL_FUNC int emdaemon_free_account_alarm_binder_list()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       email_account_alarm_binder_list_t *p = g_account_alarm_binder_list, *p_next = NULL;
+       int a_nErrorCode = 0;
+
+       /* delete alarm as well */
+       while (p) {
+               /* delete alarm */
+               if (p->account_alarm_binder.alarm_id  > 0) {
+                       a_nErrorCode = alarmmgr_remove_alarm(p->account_alarm_binder.alarm_id);
+               }
+
+               p_next = p->next;
+               EM_SAFE_FREE(p);
+               p = p_next;
+       }
+
+       g_account_alarm_binder_list = NULL;
+
+       return true;
+}
+
+static int  _emdaemon_add_to_account_alarm_binder_list(email_account_alarm_binder_list_t *p_account_alarm_binder)
+{
+       email_account_alarm_binder_list_t  *p_temp = NULL;
+
+       if(!p_account_alarm_binder) {
+               EM_DEBUG_EXCEPTION("Invalid param ");
+               return false;
+       }
+
+       if(g_account_alarm_binder_list == NULL) {
+               g_account_alarm_binder_list = p_account_alarm_binder;
+               p_account_alarm_binder = NULL;
+       }
+       else {
+               p_temp = g_account_alarm_binder_list;
+               while(p_temp->next != NULL)
+                       p_temp = p_temp->next;
+
+               p_temp->next = p_account_alarm_binder;
+               p_account_alarm_binder = NULL;
+       }
+
+       return true;
+}
+
+static int  _emdaemon_remove_from_account_alarm_binder_list(int account_id)
+{
+       email_account_alarm_binder_list_t  *p_temp = g_account_alarm_binder_list,  *p_prev = NULL;
+       int match_found = false;
+
+       if(!account_id) {
+               EM_DEBUG_EXCEPTION("Invalid param ");
+               return false;
+       }
+
+       /* first node mattch */
+       if(p_temp->account_alarm_binder.account_id == account_id) {
+               /* match found */
+               match_found = true;
+               g_account_alarm_binder_list = p_temp->next;
+               EM_SAFE_FREE(p_temp);
+       }
+       else {
+               while(p_temp != NULL) {
+                       if(p_temp->account_alarm_binder.account_id == account_id) {
+                               EM_DEBUG_EXCEPTION("account match found ");
+
+                               p_prev->next = p_temp->next;
+                               EM_SAFE_FREE(p_temp);
+
+                               match_found = true;
+                               break;
+                       }
+
+                       p_prev =  p_temp;
+                       p_temp = p_temp->next;
+               }
+       }
+
+       if(!match_found)
+               return false;
+
+       return true;
+}
+
+static int  _emdaemon_update_account_alarm_binder_list(int account_id, alarm_id_t  alarm_id)
+{
+       email_account_alarm_binder_list_t  *p_temp = g_account_alarm_binder_list;
+       int match_found = false;
+
+       if( !account_id || !alarm_id) {
+               EM_DEBUG_EXCEPTION("Invalid param ");
+               return false;
+       }
+
+       while(p_temp != NULL) {
+               if(p_temp->account_alarm_binder.account_id == account_id) {
+                       EM_DEBUG_EXCEPTION("account match found ");
+                       /* update alarm id */
+                       p_temp->account_alarm_binder.alarm_id = alarm_id;
+                       match_found = true;
+                       break;
+               }
+               p_temp = p_temp->next;
+       }
+
+       if(!match_found) {
+               EM_DEBUG_EXCEPTION("account match not found ");
+               return false;
+       }
+
+       return true;
+}
+#endif
+
diff --git a/email-daemon/email-daemon-emn.c b/email-daemon/email-daemon-emn.c
new file mode 100755 (executable)
index 0000000..8c3aa2b
--- /dev/null
@@ -0,0 +1,613 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <stdarg.h>    /*  Needed for the definition of va_list */
+#include <glib.h>
+
+#include "email-daemon.h"
+#include "email-daemon-emn.h"
+
+/* --------------------------------------------------------------------------------*/
+/* ----- WBXML Parsing (2007.06.09) -----------------------------------------------*/
+/* --------------------------------------------------------------------------------*/
+#ifdef USE_OMA_EMN
+
+#include <wbxml.h>
+#include <wbxml_errors.h>
+#include "email-debug-log.h"
+#include <vconf.h>
+
+typedef struct
+{
+       int account_id;
+       email_emn_noti_cb callback;
+       void* user_data;
+} email_emn_noti_pack_t;
+
+
+/* Parse the Email address to Get the user Name for the account [deepam.p@samsung.com] */
+static char* _get_username(char *account_username)
+{
+       EM_IF_NULL_RETURN_VALUE(account_username, NULL);
+
+       int index = 0;
+       char **token_list = NULL;
+       char *username = NULL, *name = NULL;
+
+       username = g_strdup(account_username);
+       token_list = g_strsplit_set(username, "@", -1);
+
+       if (username) {
+               g_free(username);
+       }
+
+       if (token_list[index] != NULL)
+    {
+               name = g_strdup(token_list[index]);
+               g_strfreev(token_list); /*  MUST BE. */
+               EM_DEBUG_LOG("ACCOUNT USER NAME [%s] \n", name);
+               return name;
+       }
+       else
+               return NULL;
+}
+
+static void _cb_parser_start_document(void* ctx, WB_LONG charset, const WBXMLLangEntry* lang)
+{
+    EM_DEBUG_LOG("_cb_parser_start_document\n");
+    EM_DEBUG_LOG("Parsing Document:\n\tRoot Element: %s\n\tPublic ID: %s\n\tDTD: %s\n",
+                 lang->publicID->xmlRootElt,
+                 lang->publicID->xmlPublicID,
+                 lang->publicID->xmlDTD);
+}
+
+static void _cb_parser_end_document(void* ctx)
+{
+    EM_DEBUG_LOG("_cb_parser_end_document\n");
+}
+
+static void _cb_parser_start_element(void* ctx, WBXMLTag* element, WBXMLAttribute** atts, WB_BOOL empty)
+{
+    WB_UTINY* p, **pp = ctx;
+    WB_ULONG j = 0, len = 0;
+    EM_DEBUG_LOG("parse_clb_start_element\n");
+
+    if (strcasecmp((char *)wbxml_tag_get_xml_name(element), "emn") != 0)
+    {
+        EM_DEBUG_LOG("not email notification\n");
+        return ;
+    }
+
+    if (atts == NULL)
+    {
+        EM_DEBUG_LOG("no emn attributes\n");
+        return ;
+    }
+
+    len = EM_SAFE_STRLEN((char *)wbxml_tag_get_xml_name(element)) + 1;
+    while (atts[j] != NULL)
+    {
+        len += (EM_SAFE_STRLEN((char *)wbxml_attribute_get_xml_name(atts[j])) + EM_SAFE_STRLEN((char *)wbxml_attribute_get_xml_value(atts[j])) + 7);
+        j++;
+    }
+    len += 3;
+
+    if (!(p = malloc(sizeof(WB_UTINY) * len + 1)))
+    {
+        return ;
+    }
+
+    EM_DEBUG_LOG("<%s", (char *)wbxml_tag_get_xml_name(element));
+    sprintf((char *)p, "<%s", (char *)wbxml_tag_get_xml_name(element));
+
+    j = 0;
+    while (atts[j] != NULL)
+    {
+        EM_DEBUG_LOG(" %s=\"%s\"", (char *)wbxml_attribute_get_xml_name(atts[j]), (char *)wbxml_attribute_get_xml_value(atts[j]));
+        strcat((char *)p, " ");
+        strcat((char *)p, (char *)wbxml_attribute_get_xml_name(atts[j]));
+        strcat((char *)p, "=");
+        strcat((char *)p, "\"");
+        strcat((char *)p, (char *)wbxml_attribute_get_xml_value(atts[j]));
+        strcat((char *)p, "\"");
+        j++;
+    }
+
+    if (empty)
+    {
+        EM_DEBUG_LOG("/>\n");
+        strcat((char *)p, "/>");
+    }
+    else
+    {
+        EM_DEBUG_LOG(">\n");
+        strcat((char *)p, ">");
+    }
+
+    *pp = p;
+}
+
+static void _cb_parser_end_element(void* ctx, WBXMLTag* element, WB_BOOL empty)
+{
+    EM_DEBUG_LOG("parse_clb_end_element\n");
+}
+
+static void _cb_parser_characters(void* ctx, WB_UTINY* ch, WB_ULONG start, WB_ULONG length)
+{
+    EM_DEBUG_LOG("_cb_parser_characters\n");
+}
+
+static int _get_addr_from_element(unsigned char* elm,
+                                               int* type,
+                                               unsigned char** incoming_server_user_name,
+                                               unsigned char** host_addr,
+                                               unsigned char** mbox_name,
+                                               unsigned char** auth_type)
+{
+    unsigned char*     p;
+    unsigned char*     s;
+    unsigned char*     user = NULL;
+    unsigned char*     host = NULL;
+    unsigned char*     mailbox = NULL;
+    unsigned char*     auth = NULL;
+    
+     EM_DEBUG_FUNC_BEGIN();
+        
+    if (!(p = (unsigned char*)strstr((char *)elm, "mailbox"))) /*  add acetrack.20080331.K8.4043 */
+    {
+        EM_DEBUG_EXCEPTION("invalid notification data\n");
+        return 0;
+    }
+
+    p += 9;
+    s = (unsigned char*)strchr((char *)p, '\"');
+    /*  2007-05-08 by acetrack */
+    if (s)
+      *s = '\0';
+       
+    switch (p[0])
+    {
+    case 'm':/*  mailat (RFC2234) */
+        *type = 1;
+        p += 7;
+        if (!(s = (unsigned char*)strchr((char *)p, '@'))) return 0;
+        *s = '\0';
+        user = (unsigned char*)EM_SAFE_STRDUP((char *)p);
+        s++;
+        host = (unsigned char*)EM_SAFE_STRDUP((char *)s);
+         mailbox = NULL;
+        auth = NULL;
+        break;
+
+    case 'p':/*  pop3 (RFC2384) */
+        *type = 2;
+        p += 6;
+        if ((s = (unsigned char*)strchr((char *)p, ';')))
+        {
+            *s = '\0';
+            if (EM_SAFE_STRLEN((char *)p)) user = (unsigned char*)EM_SAFE_STRDUP((char *)p);
+            p = s + 1;
+        }
+        if ((s = (unsigned char*)strchr((char *)p, '@')))
+        {
+            *s = '\0';
+            if (user || *(p - 3) == '/')
+            {
+                if (strncmp((char *)p, "AUTH=", 5) == 0) auth = (unsigned char*)EM_SAFE_STRDUP((char *)p + 5);
+            }
+            else
+                user = (unsigned char*)EM_SAFE_STRDUP((char *)p);
+            p = s + 1;
+        }
+        if ((s = (unsigned char*)strchr((char *)p, ':')))
+        {
+            *s = '\0';
+            s++;
+            EM_DEBUG_LOG("PORT:%s\n", s);
+        }
+        host = (unsigned char*)EM_SAFE_STRDUP((char *)p);
+        mailbox = NULL;
+        break;
+
+    case 'i':/*  imap (RFC2192) */
+        *type = 3;
+        p += 7;
+        if ((s = (unsigned char*)strchr((char *)p, ';')))
+        {
+            *s = '\0';
+            if (EM_SAFE_STRLEN((char *)p)) user = (unsigned char*)EM_SAFE_STRDUP((char *)p);
+            p = s + 1;
+        }
+        if ((s = (unsigned char*)strchr((char *)p, '@')))
+        {
+            *s = '\0';
+            if (user || *(p - 3) == '/')
+            {
+                if (strncmp((char *)p, "AUTH=", 5) == 0) auth = (unsigned char*)EM_SAFE_STRDUP((char *)p + 5);
+            }
+            else
+                user = (unsigned char*)EM_SAFE_STRDUP((char *)p);
+            p = s + 1;
+        }
+
+        if ((s = (unsigned char *)strchr((char *)p, '/'))) * s = '\0';
+        host = (unsigned char *)EM_SAFE_STRDUP((char *)p);
+        p = s + 1;
+
+        if ((s = (unsigned char*)strchr((char *)p, '?'))) * s = '\0';
+        else if ((s = (unsigned char*)strchr((char *)p, ';'))) * s = '\0';
+        else s = p + EM_SAFE_STRLEN((char *)p);
+        if (*(s - 1) == '/') *(s - 1) = '\0';
+
+        if (EM_SAFE_STRLEN((char *)p)) mailbox =(unsigned char*) EM_SAFE_STRDUP((char *)p);
+        break;
+
+    case 'h': /*  not supported */
+        EM_DEBUG_LOG("Http URI is not yet supported\n");
+        return 0;
+        
+    default:
+        return 0;
+    }
+
+    *incoming_server_user_name = user;
+    *host_addr = host;
+    *mbox_name = mailbox;
+    *auth_type = auth;
+
+    return 1;
+}
+
+static int _get_time_from_element(unsigned char* elm,
+                          unsigned char** time_stamp)
+{
+    EM_DEBUG_FUNC_BEGIN();
+
+    unsigned char* p, *s, *stamp = NULL;
+    if (!(p = (unsigned char*)strstr((char *)elm, "timestamp")))
+    {
+        EM_DEBUG_EXCEPTION("invalid notification data\n");
+        return 0;
+    }
+
+    p += 11;
+    s = (unsigned char*)strchr((char *)p, '\"');
+    /*  2007-05-08 by acetrack */
+    if (s)
+        *s = '\0';
+
+    stamp = malloc(15);
+    if (!stamp)        /*  added acetrack.20080331.K8.4045 */
+    {
+       EM_DEBUG_EXCEPTION("malloc failed");
+       return 0;
+    }
+    memcpy(stamp, p, 4);
+    memcpy(stamp + 4, p + 5, 2);
+    memcpy(stamp + 6, p + 8, 2);
+    memcpy(stamp + 8, p + 11, 2);
+    memcpy(stamp + 10, p + 14, 2);
+    memcpy(stamp + 12, p + 17, 2);
+    stamp[14] = '\0';
+
+    *time_stamp = stamp;
+
+    return 1;
+}
+
+/*  <emn mailbox="mailat:user@wapforum.org" timestamp="2002-04-16T06:40:00Z"/> */
+static int _get_data_from_element(unsigned char* elm,
+                          int* type,
+                          unsigned char** incoming_server_user_name,
+                          unsigned char** host_addr,
+                          unsigned char** mbox_name,
+                          unsigned char** auth_type,
+                          unsigned char** time_stamp)
+{
+
+    EM_DEBUG_FUNC_BEGIN();
+    if (!_get_time_from_element(elm, time_stamp))
+    {
+       return 0;
+       }
+
+    /*  must call get_addr_from_element after calling _get_time_from_element */
+    if (!_get_addr_from_element(elm, type, incoming_server_user_name, host_addr, mbox_name, auth_type))
+    {
+           EM_SAFE_FREE*time_stamp)    /*  added acetrack.20080331.K8.4046 */
+           return 0;
+    }
+
+    return 1;
+}
+
+
+
+/* description
+ *    get account from OMA EMN data
+ * arguments
+ *    wbxml_b64 : BASE64 encoded data
+ *    account_id: id of account to be retrieved from EMN data
+ *    mailbox   : if mail-box information exists in EMN data, mailbox holds the name of mailbox.
+ *    err_code  : hold error code
+ * return
+ *    succeed : 1
+ *    fail : 0
+ */
+static int _get_emn_account(unsigned char* wbxml_b64, email_account_t* account, char** mailbox, int* err_code)
+{
+       EM_DEBUG_LOG("_get_emn_account Enter");
+    WBXMLContentHandler parse_handler = {
+                                            (WBXMLStartDocumentHandler) _cb_parser_start_document,
+                                            (WBXMLEndDocumentHandler) _cb_parser_end_document,
+                                            (WBXMLStartElementHandler) _cb_parser_start_element,
+                                            (WBXMLEndElementHandler) _cb_parser_end_element,
+                                            (WBXMLCharactersHandler) _cb_parser_characters,
+                                            NULL
+                                        };
+
+    WBXMLParser*       wbxml_parser = NULL;
+    WB_UTINY*          wbxml = NULL;
+    WB_UTINY*          elm = NULL;
+    WB_ULONG           wbxml_len = 0;
+    WB_ULONG           err_idx = 0;
+    WBXMLError         ret = WBXML_OK;
+    email_account_t*   accounts = NULL;
+    unsigned char*     incoming_server_user_name = NULL;
+    unsigned char*     host_addr = NULL;
+    unsigned char*     mbox_name = NULL;
+    unsigned char*     auth_type = NULL;
+    unsigned char*     time_stamp = NULL;
+    int                                type = 0;
+    int                                i = 0;
+    int                                count = 0;
+    int                                retr = false;
+    int                                err = EMAIL_ERROR_NONE;
+
+    EM_DEBUG_LOG("");
+
+    if (!wbxml_b64 || !account)
+    {
+        EM_DEBUG_EXCEPTION(">>>> Invalid Parameter >>>> \n");
+        err = EMAIL_ERROR_INVALID_PARAM;
+        goto FINISH_OFF;
+    }
+
+    wbxml = g_base64_decode((const char*)wbxml_b64, (unsigned int*)&wbxml_len);
+    EM_DEBUG_LOG("wbxml = %p\n", wbxml);
+    EM_DEBUG_LOG("wbxml_len = %d\n", wbxml_len);
+
+    /*  create wbxml parser */
+    if (!(wbxml_parser = wbxml_parser_create()))
+    {
+        err = EMAIL_ERROR_OUT_OF_MEMORY;               
+        goto FINISH_OFF;
+    }
+
+    /*  initialize wbxml parser */
+    wbxml_parser_set_user_data(wbxml_parser, (void*)&elm);
+    wbxml_parser_set_content_handler(wbxml_parser, &parse_handler);
+
+    /*  parsing wbxml */
+    if ((ret = wbxml_parser_parse(wbxml_parser, wbxml, wbxml_len)) != WBXML_OK)
+    {
+        err_idx = wbxml_parser_get_current_byte_index(wbxml_parser);
+        EM_DEBUG_LOG("Parsing failed at %u - Token %x - %s", err_idx, wbxml[err_idx], wbxml_errors_string(ret));
+               
+        err = EMAIL_ERROR_XML_PARSER_FAILURE;          
+        goto FINISH_OFF;
+    }
+    else
+    {
+        EM_DEBUG_LOG("Parsing OK !\n");
+    }
+
+    /*  destroy parser */
+    wbxml_parser_destroy(wbxml_parser);
+    wbxml_parser = NULL;
+
+    /*  free buffer */
+    wbxml_free(wbxml);
+    wbxml = NULL;
+
+    if (!elm)
+    {
+        EM_DEBUG_EXCEPTION("invalid elements\n");
+               
+        err = EMAIL_ERROR_XML_PARSER_FAILURE;          
+        goto FINISH_OFF;
+    }
+
+    EM_DEBUG_LOG("elements = [%s]\n", elm);
+    _get_data_from_element(elm, &type, &incoming_server_user_name, &host_addr, &mbox_name, &auth_type, &time_stamp);
+
+    EM_SAFE_FREE(elm);
+
+    EM_DEBUG_LOG("user_type = [%d]\n", type);
+    EM_DEBUG_LOG("incoming_server_user_name = [%s]\n", (char *)incoming_server_user_name ? (char*)incoming_server_user_name : "NIL");
+    EM_DEBUG_LOG("host_addr = [%s]\n", (char *)host_addr ? (char*)host_addr : "NIL");
+    EM_DEBUG_LOG("mbox_name = [%s]\n", (char *)mbox_name ? (char*)mbox_name : "NIL");
+    EM_DEBUG_LOG("auth_type = [%s]\n", (char *)auth_type ? (char*)auth_type : "NIL");
+    EM_DEBUG_LOG("time_stamp= [%s]\n", (char *)time_stamp? (char*)time_stamp: "NIL");
+
+     if (!emdaemon_get_account_list(&accounts, &count, &err))
+    {
+        EM_DEBUG_EXCEPTION("   emdaemon_get_account_list error");
+        err = EMAIL_ERROR_DB_FAILURE;
+        goto FINISH_OFF;
+    }
+       
+    for (i = 0; i < count; i++)
+    {
+        /* sowmya.kr, 201009, Fix for EMN */
+        char* temp_account_name = NULL;
+               char *s = NULL;
+           /*  EM_DEBUG_LOG(">>>> Account Information UserName [ %s ] Email Addr [ %s], Account ID [ %d] >>> \n",accounts[i].incoming_server_user_name,accounts[i].user_email_address, accounts[i].account_id); */
+               temp_account_name =(char*) EM_SAFE_STRDUP((char *)accounts[i].incoming_server_user_name);
+
+               if ((s = (char*)strchr((char *)temp_account_name, '@')))  {
+                       *s = '\0';
+                       EM_SAFE_FREE(accounts[i].incoming_server_user_name);                    
+                       accounts[i].incoming_server_user_name  = (char*)EM_SAFE_STRDUP((char *)temp_account_name);                      
+               }
+               EM_SAFE_FREE(temp_account_name);
+               if (incoming_server_user_name)  {       
+                       if (strcmp(accounts[i].incoming_server_user_name, (char *)incoming_server_user_name) == 0 &&
+                               strstr(accounts[i].user_email_address, (char *)host_addr)) {
+                               EM_DEBUG_LOG(">>>> Account Match >>> \n");
+                               if ((type == 1) ||
+                                       (type == 2 && accounts[i].incoming_server_type == EMAIL_SERVER_TYPE_POP3) ||
+                                       (type == 3 && accounts[i].incoming_server_type == EMAIL_SERVER_TYPE_IMAP4)) {
+                                       accounts[i].flag2 = type;
+                                       EM_DEBUG_LOG("found target account id[%d] name[%s]", accounts[i].account_id, accounts[i].incoming_server_user_name);
+                                       break;
+                               }
+                       }
+               }
+       }
+
+       if (i >= count) {
+               EM_DEBUG_EXCEPTION("no account was found");
+               err = EMAIL_ERROR_ACCOUNT_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+       if (account) {
+               account->account_id = accounts[i].account_id;
+               account->flag2 = accounts[i].flag2;
+       }
+    
+    if (mailbox)
+    {
+        *mailbox = mbox_name ? (char *)mbox_name : NULL;
+        mbox_name = NULL;
+    }
+    emdaemon_free_account(&accounts, count, NULL);
+    accounts = NULL;
+
+    retr = true;
+
+FINISH_OFF:
+    if (wbxml) wbxml_free(wbxml);
+    if (wbxml_parser) wbxml_parser_destroy(wbxml_parser);
+    EM_SAFE_FREE(elm);
+    if (accounts) emdaemon_free_account(&accounts, count, NULL);
+    EM_SAFE_FREE(incoming_server_user_name);
+    EM_SAFE_FREE(mbox_name);
+    EM_SAFE_FREE(auth_type);
+    EM_SAFE_FREE(time_stamp);
+    if (err_code) *err_code = err;
+    return retr;
+}
+
+INTERNAL_FUNC int emdaemon_handle_emn_notification(unsigned char* wbxml_b64, email_emn_noti_cb callback, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("wbxml_b64[%p], callback[%p], err_code[%p]", wbxml_b64, callback, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;;
+       char* mailbox_name = NULL;
+       email_mailbox_t mailbox = { 0 };
+       email_account_t account = { 0 };
+       email_emn_noti_pack_t* pack = NULL;
+       char* pmailbox = NULL;
+       
+       if (!wbxml_b64) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       
+       pack = (email_emn_noti_pack_t*)em_malloc(sizeof(email_emn_noti_pack_t));
+       if (!pack) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+       
+       if (!_get_emn_account(wbxml_b64, &account, &mailbox_name, &err)) {
+               EM_DEBUG_EXCEPTION("_get_emn_account failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       mailbox.account_id = account.account_id;
+
+       if (!emstorage_get_mailbox_name_by_mailbox_type(mailbox.account_id,EMAIL_MAILBOX_TYPE_INBOX,&pmailbox, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d", err);               
+
+               goto FINISH_OFF;
+       }
+
+       if ((account.incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) && (account.flag2 == 3))  {
+
+               if (!mailbox_name || strncmp(pmailbox, mailbox_name, EM_SAFE_STRLEN(pmailbox)) != 0)  {
+                       EM_DEBUG_EXCEPTION("invalid inbox name [%p]", mailbox_name);
+                       err = EMAIL_ERROR_INVALID_MAILBOX;
+                       goto FINISH_OFF;
+               }
+       }
+       
+       /* sync header with mail server */
+       mailbox.mailbox_name = mailbox_tbl->mailbox_name;
+       
+       if (!emdaemon_sync_header(mailbox.account_id, mailbox.mailbox_id, NULL, &err))  {
+               EM_DEBUG_EXCEPTION("emdaemon_sync_header falied [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       ret = true;
+       
+FINISH_OFF:
+       if (ret == false) 
+               EM_SAFE_FREE(pack);
+
+       EM_SAFE_FREE(pmailbox);
+
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+}
+
+int emdaemon_initialize_emn(void)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       /* TODO : Write codes for subscribing OMA-EMN notification */
+
+       EM_DEBUG_FUNC_END();
+       return 0;
+}
+
+int emdaemon_finalize_emn(gboolean bExtDest)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_FUNC_END();
+       return 0;
+}
+
+#endif /*  USE_OMA_EMN */
+
+/* EOF */
diff --git a/email-daemon/email-daemon-etc.c b/email-daemon/email-daemon-etc.c
new file mode 100755 (executable)
index 0000000..00aaa45
--- /dev/null
@@ -0,0 +1,397 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File: emf-etc.c
+ * Desc: email-daemon Etc Implementations
+ *
+ * Auth:
+ *
+ * History:
+ *    2006.08.16 : created
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <vconf.h>
+#include "email-daemon.h"
+#include "email-daemon-account.h"
+#include "email-debug-log.h"
+#include "email-internal-types.h"
+#include "email-core-account.h"
+#include "email-core-event.h"
+#include "email-core-utils.h"
+#include "email-utilities.h"
+#include "email-storage.h"
+
+
+int emdaemon_register_event_callback(email_action_t action, email_event_callback callback, void* event_data)
+{
+       return emcore_register_event_callback(action, callback, event_data);
+}
+
+int emdaemon_unregister_event_callback(email_action_t action, email_event_callback callback)
+{
+       return emcore_unregister_event_callback(action, callback);
+}
+
+INTERNAL_FUNC void emdaemon_get_event_queue_status(int* on_sending, int* on_receiving)
+{
+       emcore_get_event_queue_status(on_sending, on_receiving);
+}
+
+INTERNAL_FUNC int emdaemon_get_pending_job(email_action_t action, int account_id, int mail_id, email_event_status_type_t* status)
+{
+       EM_DEBUG_FUNC_BEGIN("action[%d], account_id[%d], mail_id[%d]", action, account_id, mail_id);
+
+       return emcore_get_pending_event(action, account_id, mail_id, status);
+}
+
+INTERNAL_FUNC int emdaemon_cancel_job(int account_id, int handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], handle[%d], err_code[%p]", account_id, handle, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       
+       if (!emcore_cancel_thread(handle, NULL, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_cancel_thread failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       ret = true;
+       
+FINISH_OFF:
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_cancel_sending_mail_job(int account_id, int mail_id, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], err_code[%p]", account_id, mail_id, err_code);
+       
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;     
+       int handle = 0;
+       email_account_t* ref_account = NULL;
+       
+       if (account_id <= 0)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], mail_id[%d]", account_id, mail_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_PROGRESS_IN_OUTBOX__
+
+       /*      h.gahlaut@samsung.com: Moved this code from email_cancel_sending_mail API to email-service engine
+               since this code has update DB operation which is failing in context of email application process 
+               with an sqlite error -> sqlite3_step fail:8 */
+               
+       /*      which means #define SQLITE_READONLY   8 */  /* Attempt to write a readonly database */ 
+       emstorage_mail_tbl_t *mail_tbl_data = NULL;
+
+       if (!emstorage_get_mail_by_id(mail_id, &mail_tbl_data, false, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_get_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (mail_tbl_data) {
+               if (mail_tbl_data->save_status == EMAIL_MAIL_STATUS_SEND_CANCELED) {
+                       EM_DEBUG_EXCEPTION(">>>> EMAIL_MAIL_STATUS_SEND_CANCELED Already set for Mail ID [ %d ]", mail_id);
+                       goto FINISH_OFF;
+               }
+               else {                  
+                       mail_tbl_data->save_status = EMAIL_MAIL_STATUS_SEND_CANCELED;
+
+                       if(!emstorage_set_field_of_mails_with_integer_value(mail_tbl_data->account_id, &mail_id, 1, "save_status", EMAIL_MAIL_STATUS_SEND_CANCELED, true, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value failed [%d]",err);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+#endif
+
+       if(!emcore_get_handle_by_mailId_from_transaction_info(mail_id , &handle )) {
+               EM_DEBUG_EXCEPTION("emcore_get_handle_by_mailId_from_transaction_info failed for mail_id[%d]", mail_id);
+               err = EMAIL_ERROR_HANDLE_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if (!(ref_account = emcore_get_account_reference(account_id)))  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_cancel_send_mail_thread(handle, NULL, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_cancel_send_mail_thread failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       if(!emcore_delete_transaction_info_by_mailId(mail_id))
+               EM_DEBUG_EXCEPTION("emcore_delete_transaction_info_by_mailId failed for mail_id[%d]", mail_id);
+       
+       ret = true;
+       
+FINISH_OFF:
+       if(err_code != NULL)
+               *err_code = err;
+       
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+#ifdef __FEATURE_PROGRESS_IN_OUTBOX__
+       if(!emstorage_free_mail(&mail_tbl_data, 1, &err))
+               EM_DEBUG_EXCEPTION("emcore_free_mail Failed [%d ]", err);       
+
+#endif
+       EM_DEBUG_FUNC_END();
+       return ret;
+}      
+
+static char *_make_time_string_to_time_t(time_t time)
+{
+       char *time_string = NULL;
+       struct tm *struct_time = NULL;
+
+       if (!time) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               return NULL;
+       }
+
+       time_string = em_malloc(MAX_DATETIME_STRING_LENGTH);
+       if (time_string == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               return NULL;
+       }
+
+       struct_time = localtime(&time);
+       SNPRINTF(time_string, MAX_DATETIME_STRING_LENGTH, "%d/%d/%d", struct_time->tm_mon + 1, struct_time->tm_mday, struct_time->tm_year + 1900);
+
+       EM_DEBUG_LOG("time string = [%s]", time_string);
+       return time_string;     
+}
+
+static char *_make_criteria_to_search_filter(email_search_filter_t *search_filter, int search_filter_count, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("search_filter : [%p], search_filter_count : [%d]", search_filter, search_filter_count);
+
+       int i = 0;
+       int err = EMAIL_ERROR_NONE;
+       char *criteria = NULL;
+       char *temp_criteria = NULL;
+       char *time_string = NULL;
+       
+       if (search_filter == NULL || search_filter_count < 0) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       criteria = (char *)em_malloc(STRING_LENGTH_FOR_DISPLAY * search_filter_count);
+       if (criteria == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       temp_criteria = (char *)em_malloc(STRING_LENGTH_FOR_DISPLAY);
+       if (temp_criteria == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < search_filter_count; i++) {
+               EM_DEBUG_LOG("search_filter_type [%d]", search_filter[i].search_filter_type);
+               memset(temp_criteria, 0x00, STRING_LENGTH_FOR_DISPLAY);
+
+               switch (search_filter[i].search_filter_type) {
+               case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO :
+               case EMAIL_SEARCH_FILTER_TYPE_UID :
+               case EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER :
+               case EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN :
+                       EM_DEBUG_LOG("integer_type_key_value [%d]", search_filter[i].search_filter_key_value.integer_type_key_value);
+                       break;
+
+               case EMAIL_SEARCH_FILTER_TYPE_BCC :
+               case EMAIL_SEARCH_FILTER_TYPE_CC :
+               case EMAIL_SEARCH_FILTER_TYPE_TO :
+               case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID :
+                       EM_DEBUG_LOG("string_type_key_value [%s]", search_filter[i].search_filter_key_value.string_type_key_value);
+                       break;
+
+               case EMAIL_SEARCH_FILTER_TYPE_FROM :
+                       EM_DEBUG_LOG("string_type_key_value [%s]", search_filter[i].search_filter_key_value.string_type_key_value);
+                       SNPRINTF(temp_criteria, STRING_LENGTH_FOR_DISPLAY, "from %s ", search_filter[i].search_filter_key_value.string_type_key_value);
+                       strncat(criteria, temp_criteria, EM_SAFE_STRLEN(temp_criteria));
+                       break;
+
+               case EMAIL_SEARCH_FILTER_TYPE_SUBJECT :
+                       EM_DEBUG_LOG("string_type_key_value [%s]", search_filter[i].search_filter_key_value.string_type_key_value);
+                       SNPRINTF(temp_criteria, STRING_LENGTH_FOR_DISPLAY, "subject %s ", search_filter[i].search_filter_key_value.string_type_key_value);
+                       strncat(criteria, temp_criteria, EM_SAFE_STRLEN(temp_criteria));
+                       break;
+
+               case EMAIL_SEARCH_FILTER_TYPE_KEYWORD :
+                       EM_DEBUG_LOG("string_type_key_value [%s]", search_filter[i].search_filter_key_value.string_type_key_value);
+                       SNPRINTF(temp_criteria, STRING_LENGTH_FOR_DISPLAY, "keyword %s ", search_filter[i].search_filter_key_value.string_type_key_value);
+                       strncat(criteria, temp_criteria, EM_SAFE_STRLEN(temp_criteria));
+                       break;
+
+               case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE :
+                       EM_DEBUG_LOG("time_type_key_value [%d]", search_filter[i].search_filter_key_value.time_type_key_value);
+                       time_string = _make_time_string_to_time_t(search_filter[i].search_filter_key_value.time_type_key_value);
+                       SNPRINTF(temp_criteria, STRING_LENGTH_FOR_DISPLAY, "before %s ", time_string);
+                       strncat(criteria, temp_criteria, EM_SAFE_STRLEN(temp_criteria));
+                       break;
+       
+               case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON :
+                       EM_DEBUG_LOG("time_type_key_value [%d]", search_filter[i].search_filter_key_value.time_type_key_value);
+                       break;
+
+               case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE :
+                       EM_DEBUG_LOG("time_type_key_value [%d]", search_filter[i].search_filter_key_value.time_type_key_value);
+                       time_string = _make_time_string_to_time_t(search_filter[i].search_filter_key_value.time_type_key_value);
+                       SNPRINTF(temp_criteria, STRING_LENGTH_FOR_DISPLAY, "since %s ", time_string);
+                       strncat(criteria, temp_criteria, EM_SAFE_STRLEN(temp_criteria));
+                       break;
+
+               default :
+                       EM_DEBUG_EXCEPTION("Invalid list_filter_item_type [%d]", search_filter);
+                       err = EMAIL_ERROR_INVALID_PARAM;
+                       goto FINISH_OFF;
+               }
+               EM_SAFE_FREE(time_string); /*prevent 26258*/
+       }
+
+FINISH_OFF:
+       
+       EM_SAFE_FREE(temp_criteria);
+       EM_SAFE_FREE(time_string);
+
+       if (err_code != NULL)
+               *err_code = err;
+               
+       EM_DEBUG_FUNC_END();
+       return criteria;
+}
+
+INTERNAL_FUNC int emdaemon_search_mail_on_server(int input_account_id, int input_mailbox_id, email_search_filter_t *input_search_filter, int input_search_filter_count, unsigned int *output_handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id [%d], mailbox_id [%d], input_search_filter [%p], input_search_filter_count [%d], output_handle [%p]", input_account_id, input_mailbox_id, input_search_filter, input_search_filter_count, output_handle);
+       int error = EMAIL_ERROR_NONE;
+       int ret = false;
+       char *criteria = NULL;
+       
+       if (input_mailbox_id == 0 || input_account_id < 0) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               error = EMAIL_ERROR_INVALID_PARAM;
+               return false;
+       }
+
+       email_event_t event_data;
+
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       criteria = _make_criteria_to_search_filter(input_search_filter, input_search_filter_count, &error);
+       if (criteria == NULL) {
+               EM_DEBUG_EXCEPTION("_make_criteria_to_search_filter failed");
+               goto FINISH_OFF;
+       }
+               
+       event_data.type = EMAIL_EVENT_SEARCH_ON_SERVER;
+       event_data.account_id = input_account_id;
+       event_data.event_param_data_1 = EM_SAFE_STRDUP(criteria);
+       event_data.event_param_data_4 = input_mailbox_id;
+
+       if (!emcore_insert_event(&event_data, (int *)output_handle, &error)) {
+               EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", error);
+               error = EMAIL_ERROR_NONE;
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (!ret) {
+               EM_SAFE_FREE(event_data.event_param_data_1);
+       }
+
+       EM_SAFE_FREE(criteria);
+       
+       if (err_code != NULL)
+               *err_code = error;
+
+       EM_DEBUG_FUNC_END("error [%d]", error);
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_clear_all_mail_data(int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int ret = false;
+       int error = EMAIL_ERROR_NONE;
+       
+       if (emdaemon_initialize(&error)) {
+               if (!emstorage_clear_mail_data(true, &error))
+                       EM_DEBUG_EXCEPTION("emstorage_clear_mail_data failed [%d]", error);
+       }
+       else {
+               EM_DEBUG_EXCEPTION("emdaemon_initialize failed [%d]", error);
+               if (err_code)
+                       *err_code = error;
+               return false;
+       }
+
+       emcore_display_unread_in_badge();
+
+       ret = true;
+
+       if (!emstorage_create_table(EMAIL_CREATE_DB_NORMAL, &error)) 
+               EM_DEBUG_EXCEPTION("emstorage_create_table failed [%d]", error);
+       
+       emdaemon_finalize(&error);
+       
+       if (err_code)
+               *err_code = error;
+       EM_DEBUG_FUNC_END();
+    return ret;
+}
+
+       
+/* --------------------------------------------------------------------------------*/
diff --git a/email-daemon/email-daemon-init.c b/email-daemon/email-daemon-init.c
new file mode 100755 (executable)
index 0000000..31334e4
--- /dev/null
@@ -0,0 +1,417 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File: email-daemon-init.c
+ * Desc: email-daemon Initialization
+ *
+ * Auth:
+ *
+ * History:
+ *    2006.08.16 : created
+ *****************************************************************************/
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <glib.h>
+#include <glib-object.h>
+#include <vconf.h>
+#include <vconf-internal-account-keys.h>
+#include <dbus/dbus.h>
+#include <dlfcn.h>           /* added for Disabling the Pthread flag log */
+
+#include "email-daemon.h"
+#include "email-storage.h"
+#include "email-debug-log.h"
+#include "email-daemon-account.h"
+#include "email-daemon-auto-poll.h"   
+#include "email-core-utils.h"
+#include "email-core-mail.h"
+#include "email-core-event.h" 
+#include "email-core-account.h"    
+#include "email-core-mailbox.h"    
+#include "email-core-api.h"
+#include "email-core-smtp.h"    
+#include "email-core-global.h"
+#include "email-storage.h"   
+#include "email-core-sound.h" 
+#include "email-core-task-manager.h"
+
+extern int g_client_count ;
+
+/*  static functions */
+static int _emdaemon_load_email_core()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+
+       /* initialize mail core */
+       if (!emcore_init(&err))
+               goto FINISH_OFF;
+
+       if (emcore_start_event_loop(&err) < 0)
+               goto FINISH_OFF;
+
+       if (emcore_start_event_loop_for_sending_mails(&err) < 0)
+               goto FINISH_OFF;
+
+       /* Disabled task manager
+       if ((err = emcore_start_task_manager_loop()) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_start_task_manager_loop failed [%d]",err);
+               goto FINISH_OFF;
+       }
+       */
+
+#ifdef __FEATURE_PARTIAL_BODY_DOWNLOAD__
+       if (emcore_start_thread_for_downloading_partial_body(&err) < 0) {
+               EM_DEBUG_EXCEPTION("emcore_start_thread_for_downloading_partial_body failed [%d]",err);
+               goto FINISH_OFF;
+       }
+#endif
+       if (emcore_start_thread_for_alerting_new_mails(&err) < 0)
+               goto FINISH_OFF;
+
+FINISH_OFF:
+
+       return err;
+}
+
+static int _emdaemon_unload_email_core()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+
+       /* finish event loop */
+       emcore_stop_event_loop(&err);
+       emcore_stop_task_manager_loop();
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+static void callback_for_SYNC_ALL_STATUS_from_account_svc(keynode_t *input_node, void *input_user_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_node [%p], input_user_data [%p]", input_node, input_user_data);
+       int handle = 0;
+       int i = 0;
+       int err = EMAIL_ERROR_NONE;
+       int account_count = 0;
+       int sync_start_toggle = 0;
+       email_account_t         *account_list = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl_data = NULL;
+
+       if (!emdaemon_get_account_list(&account_list, &account_count, &err))  {
+               EM_DEBUG_EXCEPTION("emdaemon_get_account_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(input_node)
+               sync_start_toggle = vconf_keynode_get_int(input_node);
+
+       for(i = 0; i < account_count; i++) {
+               if(sync_start_toggle == 1) {
+                       if(!emstorage_get_mailbox_by_mailbox_type(account_list[i].account_id, EMAIL_MAILBOX_TYPE_INBOX, &mailbox_tbl_data, true, &err)) {
+                               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type for [%d] failed [%d]", account_list[i].account_id, err);
+                               continue;
+                       }
+
+                       if(!emdaemon_sync_header(account_list[i].account_id, mailbox_tbl_data->mailbox_id, &handle, &err)) {
+                               EM_DEBUG_EXCEPTION("emdaemon_sync_header for [%d] failed [%d]", account_list[i].account_id, err);
+                       }
+
+                       emstorage_free_mailbox(&mailbox_tbl_data, 1, NULL); /* prevent 27459: remove unnecesary if clause */
+                       mailbox_tbl_data = NULL;
+               }
+               else {
+                       emcore_cancel_all_threads_of_an_account(account_list[i].account_id);
+               }
+       }
+
+FINISH_OFF:
+       if(account_list)
+               emdaemon_free_account(&account_list, account_count, NULL);
+       if(mailbox_tbl_data)
+               emstorage_free_mailbox(&mailbox_tbl_data, 1, NULL);
+
+       EM_DEBUG_FUNC_END();
+}
+
+static void callback_for_AUTO_SYNC_STATUS_from_account_svc(keynode_t *input_node, void *input_user_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_node [%p], input_user_data [%p]", input_node, input_user_data);
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       int auto_sync_toggle = 0;
+       int account_count = 0;
+       email_account_t *account_list = NULL;
+       email_account_t *account_info = NULL;
+
+       if (!emdaemon_get_account_list(&account_list, &account_count, &err))  {
+               EM_DEBUG_EXCEPTION("emdaemon_get_account_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(input_node)
+               auto_sync_toggle = vconf_keynode_get_int(input_node);
+
+       for(i = 0; i < account_count; i++) {
+               account_info = account_list + i;
+
+               if(auto_sync_toggle == 1) { /* on */
+                       /* start sync */
+                       if(account_info->check_interval < 0)
+                               account_info->check_interval = ~account_info->check_interval + 1;
+               }
+               else { /* off */
+                       /* terminate sync */
+                       if(account_info->check_interval > 0)
+                               account_info->check_interval = ~account_info->check_interval + 1;
+               }
+
+               if(!emdaemon_update_account(account_info->account_id, account_info, &err)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_update_account failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       if(account_list)
+               emdaemon_free_account(&account_list, account_count, NULL);
+
+       EM_DEBUG_FUNC_END();
+}
+
+static void callback_for_NETWORK_STATUS(keynode_t *input_node, void *input_user_data)
+{
+       EM_DEBUG_FUNC_BEGIN("input_node [%p], input_user_data [%p]", input_node, input_user_data);
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       int total = 0;
+       int unseen = 0;
+       int network_status = 0;
+       int account_count = 0;
+       email_account_t *account_list = NULL;
+       email_account_t *account_info = NULL;
+       emstorage_mailbox_tbl_t *local_mailbox = NULL;
+
+       if (input_node)
+               network_status = vconf_keynode_get_int(input_node);
+
+       if (network_status == VCONFKEY_NETWORK_OFF) {
+               EM_DEBUG_EXCEPTION("Network is OFF");
+               goto FINISH_OFF;
+       }
+
+       if (!emdaemon_get_account_list(&account_list, &account_count, &err))  {
+               EM_DEBUG_EXCEPTION("emdaemon_get_account_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < account_count ; i++) {
+               account_info = account_list + i;
+
+               if (!emstorage_get_mailbox_by_mailbox_type(account_info->account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &local_mailbox, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_get_mail_count(account_info->account_id, local_mailbox->mailbox_name, &total, &unseen, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mail_count failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (total <= 0)
+                       continue;
+
+               if (!emcore_send_saved_mail(account_info->account_id, local_mailbox->mailbox_name, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_send_saved_mail failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_free_mailbox(&local_mailbox, 1, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_free_mailbox failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+
+       if (local_mailbox)
+               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
+       if (account_list)
+               emdaemon_free_account(&account_list, account_count, NULL);
+
+       EM_DEBUG_FUNC_END("Error : [%d]", err);
+}
+
+INTERNAL_FUNC int emdaemon_initialize(int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (g_client_count > 0)  {
+               EM_DEBUG_LOG("Initialization was already done. increased counter=[%d]", g_client_count);
+               g_client_count++;
+               return true;
+       }
+       else 
+               EM_DEBUG_LOG("************* start email service build time [%s %s] ************* ", __DATE__, __TIME__);
+
+       dbus_threads_init_default();
+
+       g_type_init();
+
+       emstorage_shm_file_init(SHM_FILE_FOR_DB_LOCK);
+
+#ifdef __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__
+       emstorage_shm_file_init(SHM_FILE_FOR_MAIL_ID_LOCK);
+#endif /* __FEATURE_USE_SHARED_MUTEX_FOR_GENERATING_MAIL_ID__ */
+
+       /* open database */
+       if (!emstorage_open(&err))  {
+               EM_DEBUG_EXCEPTION("emstorage_open failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_clean_save_status(EMAIL_MAIL_STATUS_SAVED, &err))
+               EM_DEBUG_EXCEPTION("emstorage_check_mail_status Failed [%d]", err );
+       
+       g_client_count = 0;    
+       
+       if (!emdaemon_initialize_account_reference())  {
+               EM_DEBUG_EXCEPTION("emdaemon_initialize_account_reference fail...");
+               err = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF;
+       }
+    EM_DEBUG_LOG("emdaemon_initialize_account_reference over - g_client_count [%d]", g_client_count);  
+       
+       if ((err = _emdaemon_load_email_core()) != EMAIL_ERROR_NONE)  {
+               EM_DEBUG_EXCEPTION("_emdaemon_load_email_core failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       /* Subscribe Events */
+       vconf_notify_key_changed(VCONFKEY_ACCOUNT_SYNC_ALL_STATUS_INT,  callback_for_SYNC_ALL_STATUS_from_account_svc,  NULL);
+       vconf_notify_key_changed(VCONFKEY_ACCOUNT_AUTO_SYNC_STATUS_INT, callback_for_AUTO_SYNC_STATUS_from_account_svc, NULL);
+       vconf_notify_key_changed(VCONFKEY_NETWORK_STATUS, callback_for_NETWORK_STATUS, NULL);
+
+       emcore_display_unread_in_badge();
+       
+       ret = true;
+       
+FINISH_OFF:
+       if (ret == true)
+               g_client_count = 1;
+
+       if (err_code)
+               *err_code = err;
+       
+       EM_DEBUG_FUNC_END("ret [%d], g_client_count [%d]", ret, g_client_count);
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_finalize(int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       
+       if (g_client_count > 1) {
+               EM_DEBUG_EXCEPTION("engine is still used by application. decreased counter=[%d]", g_client_count);
+               g_client_count--;
+               err = EMAIL_ERROR_CLOSE_FAILURE;
+               goto FINISH_OFF;
+       }
+       
+       if ( (err = _emdaemon_unload_email_core()) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("_emdaemon_unload_email_core failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       /* free account reference list */
+       emcore_free_account_reference();
+       
+       /* close database */
+       if (!emstorage_close(&err)) {
+               EM_DEBUG_EXCEPTION("emstorage_close failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       
+       g_client_count = 0;
+       
+#ifdef __FEATURE_AUTO_POLLING__
+       emdaemon_free_account_alarm_binder_list();
+#endif
+
+       ret = true;
+       
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       
+       return ret;
+}
+
+#ifdef __FEATURE_AUTO_POLLING__
+INTERNAL_FUNC int emdaemon_start_auto_polling(int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       /*  default variable */
+       int ret = false, count = 0, i= 0;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t* account_list = NULL;
+
+       /* get account list */
+       if (!emstorage_get_account_list(&count, &account_list, false, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_list failed [%d]", err);              
+               goto FINISH_OFF;
+       }
+
+       for (i = 0; i < count; i++)  {
+               /* start auto polling, if check_interval not zero */
+               if(account_list[i].check_interval > 0) {
+                       if(!emdaemon_add_polling_alarm( account_list[i].account_id,account_list[i].check_interval))
+                               EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm failed");
+               }
+       }
+
+       ret = true;
+FINISH_OFF:  
+       if (account_list)
+               emstorage_free_account(&account_list, count, NULL);
+       
+       if (err_code != NULL)
+               *err_code = err;
+       
+       return ret;
+}
+#endif /* __FEATURE_AUTO_POLLING__ */
+
diff --git a/email-daemon/email-daemon-mail.c b/email-daemon/email-daemon-mail.c
new file mode 100755 (executable)
index 0000000..1deb058
--- /dev/null
@@ -0,0 +1,1483 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File: email-daemon-mail.c
+ * Desc: email-daemon Mail Operation
+ *
+ * Auth:
+ *
+ * History:
+ *    2006.08.16 : created
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <glib.h>
+#include <unistd.h>
+#include <malloc.h>
+#include <pthread.h>
+
+#include "email-internal-types.h"
+#include "email-daemon.h"
+#include "email-core-event.h"
+#include "email-daemon-account.h"
+#include "email-debug-log.h"
+#include "email-storage.h"
+#include "email-utilities.h"
+#include "email-core-account.h"
+#include "email-core-mail.h"
+#include "email-core-mailbox.h"
+#include "email-core-utils.h"
+#include "email-core-smtp.h"
+#include "email-core-timer.h"
+#include "email-core-signal.h"
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+extern int g_local_activity_run;
+extern int g_save_local_activity_run;
+#endif
+static int _emdaemon_check_mail_id(int mail_id, int* err_code);
+
+INTERNAL_FUNC int emdaemon_send_mail(int mail_id, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], handle[%p], err_code[%p]", mail_id, handle, err_code);
+
+       int ret = false, err = EMAIL_ERROR_NONE, err_2 = EMAIL_ERROR_NONE;
+       int  result_handle = 0, account_id = 0;
+       email_event_t event_data = { 0, };
+       emstorage_mail_tbl_t* mail_table_data = NULL;
+       emstorage_mailbox_tbl_t* local_mailbox = NULL;
+       email_account_t* ref_account = NULL;
+       int dst_mailbox_id = 0;
+
+       if(mail_id <= 0) {
+               EM_DEBUG_EXCEPTION("mail_id is not valid");
+               err= EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if(!emstorage_get_mail_by_id(mail_id, &mail_table_data, true, &err)) {
+               EM_DEBUG_EXCEPTION("Failed to get mail by mail_id [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!mail_table_data || mail_table_data->mailbox_id <= 0 || mail_table_data->account_id <= 0) {
+               if (mail_table_data != NULL)
+                       EM_DEBUG_EXCEPTION(" mail_table_data->mailbox_id[%d], mail_table_data->account_id[%d]", mail_table_data->mailbox_id, mail_table_data->account_id);
+               if (err_code)
+                       *err_code = EMAIL_ERROR_INVALID_MAILBOX;
+               if(mail_table_data)
+                       emstorage_free_mail(&mail_table_data, 1, &err);
+               return false;
+       }
+
+       account_id = mail_table_data->account_id;
+
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (!ref_account) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_MOVE_TO_OUTBOX_FIRST__
+       if (!emstorage_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &local_mailbox, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+               goto FINISH_OFF;
+       }
+       dst_mailbox_id = local_mailbox->mailbox_id;
+       if ( mail_table_data->mailbox_id != dst_mailbox_id ) {
+                       /*  mail is moved to 'OUTBOX' first of all. */
+               if (!emcore_move_mail(&mail_id, 1, dst_mailbox_id, EMAIL_MOVED_AFTER_SENDING, 0, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_mail_move falied [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+#endif /* __FEATURE_MOVE_TO_OUTBOX_FIRST__ */
+
+       if(!emcore_notify_network_event(NOTI_SEND_START, account_id, NULL, mail_id, 0))
+               EM_DEBUG_EXCEPTION(" emcore_notify_network_event [ NOTI_SEND_START] Failed >>>> ");
+
+       /* set EMAIL_MAIL_STATUS_SEND_WAIT status */
+
+       if(!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", EMAIL_MAIL_STATUS_SEND_WAIT, true, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value [%d]",err);
+
+               goto FINISH_OFF;
+       }
+
+       event_data.type               = EMAIL_EVENT_SEND_MAIL;
+       event_data.account_id         = account_id;
+       event_data.event_param_data_4 = mail_id;
+       event_data.event_param_data_5 = mail_table_data->mailbox_id;
+
+       if (!emcore_insert_event_for_sending_mails(&event_data, &result_handle, &err)) {
+               EM_DEBUG_EXCEPTION(" emcore_insert_event failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+                       EM_DEBUG_LOG("Setting g_save_local_activity_run ");
+                       g_save_local_activity_run = 1;
+#endif
+
+       if ( handle )
+               *handle = result_handle;
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == false) {
+               EM_DEBUG_EXCEPTION("emdaemon_send_mail failed [%d]", err);
+
+               if(!emstorage_set_field_of_mails_with_integer_value(account_id, &mail_id, 1, "save_status", EMAIL_MAIL_STATUS_SAVED, true, &err))
+                       EM_DEBUG_EXCEPTION("emstorage_set_field_of_mails_with_integer_value [%d]",err);
+
+               EM_SAFE_FREE(event_data.event_param_data_3);
+       }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if(!emcore_add_transaction_info(mail_id , result_handle , &err_2))
+               EM_DEBUG_EXCEPTION("emcore_add_transaction_info failed [%d]", err_2);
+
+       if(local_mailbox)
+               emstorage_free_mailbox(&local_mailbox, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+
+       if(mail_table_data)
+               emstorage_free_mail(&mail_table_data, 1, &err);
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_send_mail_saved(int account_id, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d],handle[%p], err_code[%p]", account_id, handle, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_event_t event_data = { 0 , };
+       email_account_t* ref_account = NULL;
+       char *mailbox_name = NULL;
+
+       if (account_id <= 0)  {
+               EM_DEBUG_EXCEPTION("account_id = %d", account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_mailbox_name_by_mailbox_type(account_id,EMAIL_MAILBOX_TYPE_OUTBOX,&mailbox_name, false, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_name_by_mailbox_type failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       event_data.type               = EMAIL_EVENT_SEND_MAIL_SAVED;
+       event_data.account_id         = account_id;
+       event_data.event_param_data_3 = EM_SAFE_STRDUP(mailbox_name);
+
+       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (ret == false)  {
+               EM_SAFE_FREE(event_data.event_param_data_3);
+       }
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       EM_SAFE_FREE(mailbox_name);
+
+       if (err_code)
+               *err_code = err;
+
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count [%d], input_meeting_req [%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+
+       int         err = EMAIL_ERROR_NONE;
+       int         handle = 0;
+       email_event_t event_data = { 0 };
+       email_account_t* ref_account = NULL;
+
+       if (!input_mail_data || input_mail_data->account_id <= 0 ||
+               ( ((input_mail_data->report_status & EMAIL_MAIL_REPORT_MDN) != 0) && !input_mail_data->full_address_to))  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(input_mail_data->account_id);
+       if (!ref_account)  {
+               EM_DEBUG_LOG(" emcore_get_account_reference failed [%d]", input_mail_data->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if ((err = emcore_add_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_add_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+       if ( input_from_eas == 0 && ref_account->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+               event_data.type               = EMAIL_EVENT_SAVE_MAIL;
+               event_data.account_id         = input_mail_data->account_id;
+               event_data.event_param_data_4 = input_mail_data->mail_id;
+
+               if (!emcore_insert_event(&event_data, &handle, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+#endif
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+INTERNAL_FUNC int emdaemon_add_meeting_request(int account_id, int input_mailbox_id, email_meeting_request_t *meeting_req, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], input_mailbox_id[%d], meeting_req[%p], err_code[%p]", account_id, input_mailbox_id, meeting_req, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if ( account_id <= 0 || !meeting_req || meeting_req->mail_id <= 0 )  {
+               if(meeting_req)
+                       EM_DEBUG_EXCEPTION("mail_id[%d]", meeting_req->mail_id);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_add_meeting_request(account_id, input_mailbox_id, meeting_req, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_save_mail_meeting_request failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_download_body(int account_id, int mail_id, int verbose, int with_attachment,  int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], verbose[%d], with_attachment[%d], handle[%p], err_code[%p]", account_id, mail_id, verbose, with_attachment,  handle, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+/*     mpNewMail_StopAlertSound(); */
+
+       if (!_emdaemon_check_mail_id(mail_id, &err))  {
+               EM_DEBUG_EXCEPTION("_emdaemon_check_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       email_event_t event_data;
+
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       event_data.type = EMAIL_EVENT_DOWNLOAD_BODY;
+       event_data.event_param_data_4 = mail_id;
+       event_data.account_id = account_id;
+       event_data.event_param_data_3 = GINT_TO_POINTER(verbose << 1 | with_attachment);
+
+       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+               err = EMAIL_ERROR_DB_FAILURE;
+               goto FINISH_OFF;
+       }
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       EM_DEBUG_LOG("Setting g_local_activity_run ");
+       g_local_activity_run = 1;
+#endif
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emdaemon_get_attachment(int attachment_id, email_attachment_data_t** attachment, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_id[%d], attachment[%p], err_code[%p]", attachment_id, attachment, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!attachment_id || !attachment)  {
+               EM_DEBUG_EXCEPTION("mail_id[%d], attachment_id[%d], attachment[%p]\n", attachment_id, attachment);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_attachment_info(attachment_id, attachment, &err) || !attachment)  {
+               EM_DEBUG_EXCEPTION("emcore_get_attachment_info failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emdaemon_add_attachment(int mail_id, email_attachment_data_t* attachment, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], attachment[%p], err_code[%p]", mail_id, attachment, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!attachment)  {
+               EM_DEBUG_EXCEPTION(" mailbox[%p], mail_id[%d], attachment[%p]", mail_id, attachment);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!_emdaemon_check_mail_id(mail_id, &err))  {
+               EM_DEBUG_EXCEPTION(" _emdaemon_check_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_mail_add_attachment(mail_id, attachment, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_mail_add_attachment failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+int emdaemon_delete_mail_attachment(int attachment_id, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("attachment_id[%d], err_code[%p]", attachment_id, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!attachment_id)  {
+               EM_DEBUG_EXCEPTION("attachment_id[%d]", attachment_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_delete_mail_attachment(attachment_id, &err))  {
+               EM_DEBUG_EXCEPTION(" emcore_delete_mail_attachment failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_download_attachment(int account_id, int mail_id, int nth, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mail_id[%d], nth[%d], handle[%p], err_code[%p]", account_id, mail_id, nth, handle, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       if (!nth)  {
+               EM_DEBUG_EXCEPTION("nth[%p] is invalid", nth);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!_emdaemon_check_mail_id(mail_id, &err))  {
+               EM_DEBUG_EXCEPTION("_emdaemon_check_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       email_event_t event_data;
+
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       event_data.type = EMAIL_EVENT_DOWNLOAD_ATTACHMENT;
+       event_data.account_id         = account_id;
+       event_data.event_param_data_4 = mail_id;
+       event_data.event_param_data_5 = nth;
+
+       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       EM_DEBUG_LOG("Setting g_local_activity_run ");
+       g_local_activity_run = 1;
+#endif
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_free_attachment_data(email_attachment_data_t** atch_data, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       return emcore_free_attachment_data(atch_data, 1, err_code);
+}
+
+void* thread_func_to_delete_mail(void *thread_argument)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int  err = EMAIL_ERROR_NONE;
+       int *mail_id_list = NULL;
+       int  mail_id_count = 0;
+       int  account_id = 0;
+       int  from_server = 0;
+       int  noti_param_2 = 0;
+       int handle = 0;
+       email_event_t *event_data = (email_event_t*)thread_argument;
+
+       account_id         = event_data->account_id;
+       mail_id_list       = (int*)event_data->event_param_data_3;
+       mail_id_count      = event_data->event_param_data_4;
+       from_server        = event_data->event_param_data_5;
+
+       if (!emcore_delete_mail(account_id, mail_id_list, mail_id_count, EMAIL_DELETE_LOCALLY, EMAIL_DELETED_BY_COMMAND, noti_param_2, &err)) {
+               EM_DEBUG_EXCEPTION(" emcore_delete_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (from_server == EMAIL_DELETE_LOCAL_AND_SERVER || from_server == EMAIL_DELETE_FROM_SERVER) {
+               if (!emcore_insert_event(event_data, (int*)handle, &err)) {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       /* all of members will be freed after using in each event handler */
+
+       if (from_server != EMAIL_DELETE_LOCAL_AND_SERVER && from_server != EMAIL_DELETE_FROM_SERVER) {
+               EM_SAFE_FREE(event_data->event_param_data_3);
+       }
+       EM_SAFE_FREE(event_data);
+
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+INTERNAL_FUNC int emdaemon_delete_mail(int mailbox_id, int mail_ids[], int mail_ids_count, int from_server, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox_id[%d], mail_ids[%p], mail_ids_count[%d], from_server[%d], handle[%p], err_code[%p]", mailbox_id, mail_ids, mail_ids_count, from_server, handle, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int *p = NULL;
+       int thread_error = 0;
+       email_account_t *ref_account = NULL;
+       email_event_t *event_data = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl_data = NULL;
+       thread_t delete_thread;
+
+       /* mailbox can be NULL for deleting thread mail. */
+       if (mail_ids_count <= 0) {
+               EM_DEBUG_EXCEPTION("mail_ids_count [%d]", mail_ids_count);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ( (err = emstorage_get_mailbox_by_id(mailbox_id, &mailbox_tbl_data)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%err]", err);
+               goto FINISH_OFF;
+       }
+
+       if ((p = em_malloc(sizeof(int) * mail_ids_count)) == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc for p failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memcpy(p, mail_ids, sizeof(int) * mail_ids_count);
+
+       if ((event_data = em_malloc(sizeof(email_event_t)) ) == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc for event_data failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox_tbl_data->account_id);
+
+       if (!ref_account) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed.");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (ref_account->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC) {
+               from_server = EMAIL_DELETE_LOCALLY;
+       }
+
+       event_data->type                   = EMAIL_EVENT_DELETE_MAIL;
+       event_data->account_id             = mailbox_tbl_data->account_id;
+       event_data->event_param_data_3     = (char*)p;
+       event_data->event_param_data_4     = mail_ids_count;
+       event_data->event_param_data_5     = from_server;
+
+       THREAD_CREATE(delete_thread, thread_func_to_delete_mail, (void*)event_data, thread_error);
+       THREAD_DETACH(delete_thread); /* free resources used for new thread */
+       ret = true;
+
+FINISH_OFF:
+
+       if (mailbox_tbl_data)
+               emstorage_free_mailbox(&mailbox_tbl_data, 1, NULL);
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (thread_error != 0) {
+               EM_SAFE_FREE(event_data);
+               EM_SAFE_FREE(p);
+       }
+
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+int emdaemon_delete_mail_all(int input_mailbox_id, int input_from_server, int *output_handle, int *output_err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], input_from_server[%d], handle[%p], err_code[%p]", input_mailbox_id, input_from_server, output_handle, output_err_code);
+
+       int                      ret = false;
+       int                      err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+       email_event_t              event_data = { 0 };
+
+       if (!input_mailbox_id) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl) != EMAIL_ERROR_NONE)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(!emcore_delete_all_mails_of_mailbox(mailbox_tbl->account_id, input_mailbox_id, EMAIL_DELETE_LOCALLY, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_delete_all_mails_of_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+       if(input_from_server == EMAIL_DELETE_LOCAL_AND_SERVER || input_from_server == EMAIL_DELETE_FROM_SERVER) {
+               event_data.type               = EMAIL_EVENT_DELETE_MAIL_ALL;
+               event_data.account_id         = mailbox_tbl->account_id;
+               event_data.event_param_data_4 = input_mailbox_id;
+               event_data.event_param_data_5 = input_from_server;
+
+               if (!emcore_insert_event(&event_data, (int*)output_handle, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+               int i, total = 0 , search_handle = 0;
+               int *mail_ids = NULL;
+               emstorage_activity_tbl_t new_activity;
+               int activityid = 0;
+
+               if (false == emcore_get_next_activity_id(&activityid,&err)) {
+                       EM_DEBUG_EXCEPTION(" emcore_get_next_activity_id Failed - %d ", err);
+               }
+
+               if (!emstorage_mail_search_start(NULL, mailbox->account_id, mailbox->mailbox_name, 0, &search_handle, &total, true, &err)) {
+                       EM_DEBUG_EXCEPTION(" emstorage_mail_search_start failed [%d]", err);
+
+
+                       goto FINISH_OFF;
+               }
+
+               mail_ids = em_malloc(sizeof(int) * total);
+               if (mail_ids == NULL)  {
+                       EM_DEBUG_EXCEPTION(" mailloc failed...");
+
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+
+               for (i = 0; i < total; i++)  {
+                       if (!emstorage_mail_search_result(search_handle, RETRIEVE_ID, (void**)&mail_ids[i], true, &err))  {
+                               EM_DEBUG_EXCEPTION(" emstorage_mail_search_result failed [%d]", err);
+
+
+                               EM_SAFE_FREE(mail_ids);
+                               goto FINISH_OFF;
+                       }
+
+                       new_activity.activity_id        = activityid;
+                       new_activity.activity_type      = ACTIVITY_DELETEMAIL;
+                       new_activity.mail_id            = mail_ids[i];
+                       new_activity.server_mailid      = NULL;
+                       new_activity.src_mbox           = mailbox->mailbox_name;
+                       new_activity.dest_mbox          = NULL;
+                       new_activity.account_id         = mailbox->account_id;
+
+                       if (! emcore_add_activity(&new_activity, &err))
+                               EM_DEBUG_EXCEPTION(" emcore_add_activity  Failed  - %d ", err);
+
+               }
+
+               EM_SAFE_FREE(mail_ids);
+
+               EM_DEBUG_LOG("Setting g_local_activity_run ");
+               g_local_activity_run = 1;
+#endif
+       }
+#endif         /*  __FEATURE_SYNC_CLIENT_TO_SERVER__ */
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       if (output_err_code)
+               *output_err_code = err;
+
+       return ret;
+}
+
+void* thread_func_to_move_mail(void *thread_argument)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int *mail_ids = NULL, mail_ids_count, noti_param_1, noti_param_2, err;
+       int handle = 0;
+       email_event_t *event_data = (email_event_t*)thread_argument;
+       int dst_mailbox_id = 0;
+
+/*     dst_mailbox_name   = (char*)event_data->event_param_data_1; */ /*prevent 33693*/
+       mail_ids           = (int*)event_data->event_param_data_3;
+       mail_ids_count     = event_data->event_param_data_4;
+       dst_mailbox_id     = event_data->event_param_data_5;
+       noti_param_1       = event_data->event_param_data_6;
+       noti_param_2       = event_data->event_param_data_7;
+
+
+       if (!emcore_move_mail(mail_ids, mail_ids_count, dst_mailbox_id, noti_param_1, noti_param_2, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_mail_move failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_insert_event(event_data, (int*)&handle, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+       /* emcore_free_event(event_data); */ /* all of members will be freed after using in each event handler */
+       EM_SAFE_FREE(event_data);
+
+       EM_DEBUG_FUNC_END();
+       return SUCCESS;
+}
+
+INTERNAL_FUNC int emdaemon_move_mail_all_mails(int src_mailbox_id, int dst_mailbox_id, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("src_mailbox_id[%d], dst_mailbox_id[%d], err_code[%p]", src_mailbox_id, dst_mailbox_id, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int select_num = 0;
+       int *mails = NULL;
+       int *p = NULL;
+       int i = 0;
+       int num = 0;
+       int thread_error;
+       email_account_t *ref_account = NULL;
+       email_mail_list_item_t *mail_list = NULL;
+       email_event_t *event_data = NULL;
+       thread_t move_thread;
+       emstorage_mailbox_tbl_t *dst_mailbox_tbl = NULL;
+       emstorage_mailbox_tbl_t *src_mailbox_tbl = NULL;
+
+       if ( dst_mailbox_id <= 0|| src_mailbox_id <= 0)  {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_mailbox_by_id(dst_mailbox_id, &dst_mailbox_tbl)) != EMAIL_ERROR_NONE || !dst_mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_mailbox_by_id(src_mailbox_id, &src_mailbox_tbl)) != EMAIL_ERROR_NONE || !src_mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(dst_mailbox_tbl->account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", dst_mailbox_tbl->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if(!emstorage_get_mail_list(src_mailbox_tbl->account_id, src_mailbox_id, NULL, EMAIL_LIST_TYPE_NORMAL, -1, -1, 0, NULL, EMAIL_SORT_DATETIME_HIGH, false, &mail_list, &select_num, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_list failed");
+               goto FINISH_OFF;
+       }
+
+       mails = malloc(sizeof(int) * select_num);
+
+       if( !mails ) {
+               EM_DEBUG_EXCEPTION("Malloc failed...!");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memset(mails, 0x00, sizeof(int) * select_num);
+
+       for(i = 0 ; i < select_num ; i++) {
+               if( mail_list[i].save_status != EMAIL_MAIL_STATUS_SENDING ) {
+                       mails[num] = mail_list[i].mail_id;
+                       num++;
+               }
+       }
+
+       if( num <= 0) {
+               EM_DEBUG_EXCEPTION("can't find avalable mails. num = %d", num);
+               err = EMAIL_ERROR_MAIL_NOT_FOUND;
+               goto FINISH_OFF;
+       }
+
+       if ((event_data = em_malloc(sizeof(email_event_t)) ) == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc for event_data failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if ((p = em_malloc(sizeof(int) * num)) == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc for p failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memcpy(p, mails, sizeof(int) * num);
+
+       event_data->account_id         = dst_mailbox_tbl->account_id;
+       event_data->type               = EMAIL_EVENT_MOVE_MAIL;
+       event_data->event_param_data_3 = (char*)p;
+       event_data->event_param_data_4 = num;
+       event_data->event_param_data_5 = dst_mailbox_id;
+       event_data->event_param_data_8 = src_mailbox_id;
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       int i = 0, activityid = 0;
+
+       if (false == emcore_get_next_activity_id(&activityid,&err))
+               EM_DEBUG_EXCEPTION(" emcore_get_next_activity_id Failed - %d ", err);
+
+       for (i =0; i < event_data.event_param_data_4; i++) {
+               emstorage_activity_tbl_t        new_activity;
+               new_activity.activity_id = activityid;
+               new_activity.activity_type = ACTIVITY_MOVEMAIL;
+               new_activity.account_id    = event_data.account_id;
+               new_activity.mail_id       = mail_ids[i];
+               new_activity.dest_mbox     = event_data.event_param_data_1;
+               new_activity.server_mailid = NULL;
+               new_activity.src_mbox      = event_data.event_param_data_2;
+
+               if (!emcore_add_activity(&new_activity, &err))
+                       EM_DEBUG_EXCEPTION(" emcore_add_activity Failed - %d ", err);
+       }
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+       THREAD_CREATE(move_thread, thread_func_to_move_mail, (void*)event_data, thread_error);
+       THREAD_DETACH(move_thread); /* free resources used for new thread */
+       ret = true;
+
+FINISH_OFF:
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       EM_DEBUG_LOG("Setting g_local_activity_run ");
+       g_local_activity_run = 1;
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+
+       if (err_code)
+               *err_code = err;
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (dst_mailbox_tbl)
+               emstorage_free_mailbox(&dst_mailbox_tbl, 1, NULL);
+
+       if (src_mailbox_tbl)
+               emstorage_free_mailbox(&src_mailbox_tbl, 1, NULL);
+
+       if(mail_list)
+               EM_SAFE_FREE(mail_list);
+
+       if(mails != NULL )
+               EM_SAFE_FREE(mails);
+
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_move_mail(int mail_ids[], int num, int dst_mailbox_id, int noti_param_1, int noti_param_2, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%p], num[%d], dst_mailbox_id[%d], err_code[%p]", mail_ids, num, dst_mailbox_id, err_code);
+
+       /*  default variable */
+       int mail_id = 0, *p = NULL, thread_error;
+       int ret = false, err = EMAIL_ERROR_NONE;
+       emstorage_mail_tbl_t* mail_table_data = NULL;
+       email_account_t* ref_account = NULL;
+       email_event_t *event_data = NULL;
+       thread_t move_thread;
+       emstorage_mailbox_tbl_t *dest_mailbox_tbl = NULL;
+       int src_mailbox_id = 0;
+
+       if (num <= 0 || dst_mailbox_id <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_mailbox_by_id(dst_mailbox_id, &dest_mailbox_tbl)) != EMAIL_ERROR_NONE || !dest_mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(dest_mailbox_tbl->account_id);
+
+       if (!ref_account) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", dest_mailbox_tbl->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       /* Getting source mailbox name */
+       mail_id = mail_ids[0];
+
+       if (!emstorage_get_mail_field_by_id(mail_id, RETRIEVE_SUMMARY, &mail_table_data, true, &err) || !mail_table_data) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_field_by_id failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       if (src_mailbox_id == 0)
+               src_mailbox_id = mail_table_data->mailbox_id;
+
+       emstorage_free_mail(&mail_table_data, 1, NULL);
+
+       if ((event_data = em_malloc(sizeof(email_event_t)) ) == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc for event_data failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if ((p = em_malloc(sizeof(int) * num)) == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc for p failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       memcpy(p, mail_ids, sizeof(int) * num);
+
+       event_data->account_id        = dest_mailbox_tbl->account_id;
+       event_data->type               = EMAIL_EVENT_MOVE_MAIL;
+       event_data->event_param_data_3 = (char*)p;
+       event_data->event_param_data_4 = num;
+       event_data->event_param_data_5 = dst_mailbox_id;
+       event_data->event_param_data_8 = src_mailbox_id;
+       event_data->event_param_data_6 = noti_param_1;
+       event_data->event_param_data_7 = noti_param_2;
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       int i = 0, activityid = 0;
+
+       if (false == emcore_get_next_activity_id(&activityid,&err))
+               EM_DEBUG_EXCEPTION(" emcore_get_next_activity_id Failed - %d ", err);
+
+       for (i =0; i < event_data.event_param_data_4; i++) {
+               emstorage_activity_tbl_t        new_activity;
+               new_activity.activity_id = activityid;
+               new_activity.activity_type = ACTIVITY_MOVEMAIL;
+               new_activity.account_id    = event_data.account_id;
+               new_activity.mail_id       = mail_ids[i];
+               new_activity.dest_mbox     = event_data.event_param_data_1;
+               new_activity.server_mailid = NULL;
+               new_activity.src_mbox      = event_data.event_param_data_2;
+
+               if (!emcore_add_activity(&new_activity, &err))
+                       EM_DEBUG_EXCEPTION(" emcore_add_activity Failed - %d ", err);
+       }
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+       THREAD_CREATE(move_thread, thread_func_to_move_mail, (void*)event_data, thread_error);
+       THREAD_DETACH(move_thread); /* free resources used for new thread */
+       ret = true;
+
+FINISH_OFF:
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       EM_DEBUG_LOG("Setting g_local_activity_run ");
+       g_local_activity_run = 1;
+#endif /* __FEATURE_LOCAL_ACTIVITY__ */
+
+       if (err_code)
+               *err_code = err;
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (dest_mailbox_tbl)
+               emstorage_free_mailbox(&dest_mailbox_tbl, 1, NULL);
+
+       EM_DEBUG_FUNC_END("ret [%d]", ret);
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_set_flags_field(int account_id, int mail_ids[], int num, email_flags_field_type field_type, int value, int onserver, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_ids[%d], num[%d], field_type [%d], value[%d], err_code[%p]", mail_ids[0], num, field_type, value, err_code);
+
+       int ret = false, err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *account_tbl = NULL;
+
+       if(account_id <= 0 || !mail_ids || num <= 0) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_account_by_id(account_id, EMAIL_ACC_GET_OPT_DEFAULT, &account_tbl, false, &err)) {
+               EM_DEBUG_EXCEPTION("emstorage_get_account_by_id falled [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_set_flags_field(account_id, mail_ids, num, field_type, value, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_set_flags_field falled [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if( onserver && account_tbl->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4 )  {
+               int *mail_id_array = NULL;
+               email_event_t event_data = {0};
+               int handle = 0;
+
+               mail_id_array = em_malloc(sizeof(int) * num);
+
+               if (mail_id_array == NULL)  {
+                       EM_DEBUG_EXCEPTION("em_malloc failed...");
+              err = EMAIL_ERROR_OUT_OF_MEMORY;
+              goto FINISH_OFF;
+               }
+
+               memcpy(mail_id_array, mail_ids, sizeof(int) * num);
+
+               event_data.type               = EMAIL_EVENT_SYNC_FLAGS_FIELD_TO_SERVER;
+               event_data.account_id         = account_id;
+               event_data.event_param_data_1 = NULL;
+               event_data.event_param_data_3 = (char*)mail_id_array;
+               event_data.event_param_data_4 = num;
+               event_data.event_param_data_5 = field_type;
+               event_data.event_param_data_6 = value;
+
+               if (!emcore_insert_event(&event_data, (int*)&handle, &err))  {
+                       EM_DEBUG_LOG("emcore_insert_event failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (account_tbl)
+               emstorage_free_account(&account_tbl, 1, NULL);
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mail_data[%p], input_attachment_data_list[%p], input_attachment_count [%d], input_meeting_req [%p], input_from_eas[%d]", input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas);
+
+       int            err = EMAIL_ERROR_NONE;
+       int            handle = 0;
+       email_event_t    event_data = { 0 };
+       email_account_t *ref_account = NULL;
+
+       if (!input_mail_data || input_mail_data->account_id <= 0 || input_mail_data->mail_id == 0 ||
+               (((input_mail_data->report_status & EMAIL_MAIL_REPORT_MDN) != 0) && !input_mail_data->full_address_to))  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(input_mail_data->account_id);
+       if (!ref_account)  {
+               EM_DEBUG_LOG(" emcore_get_account_reference failed [%d]", input_mail_data->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if ( (err = emcore_update_mail(input_mail_data, input_attachment_data_list, input_attachment_count, input_meeting_request, input_from_eas)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_update_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+       if ( input_from_eas == 0) {
+               event_data.type               = EMAIL_EVENT_UPDATE_MAIL;
+               event_data.account_id         = input_mail_data->account_id;
+               event_data.event_param_data_1 = (char*)input_mail_data;
+               event_data.event_param_data_2 = (char*)input_attachment_data_list;
+               event_data.event_param_data_3 = (char*)input_meeting_request;
+               event_data.event_param_data_4 = input_attachment_count;
+               event_data.event_param_data_5 = input_from_eas;
+
+               if (!emcore_insert_event_for_sending_mails(&event_data, &handle, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event_for_sending_mails failed [%d]", err);
+                       err = EMAIL_ERROR_NONE;
+                       goto FINISH_OFF;
+               }
+       }
+#endif
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+
+int _emdaemon_check_mail_id(int mail_id, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mail_id[%d], err_code[%p]", mail_id, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       emstorage_mail_tbl_t* mail = NULL;
+
+       if (!emstorage_get_mail_field_by_id(mail_id, RETRIEVE_SUMMARY, &mail, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_field_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (mail != NULL)
+               emstorage_free_mail(&mail, 1, NULL);
+
+       if (err_code != NULL)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_send_mail_retry(int mail_id,  int timeout_in_sec, int* err_code)
+{
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       long nTimerValue = 0;
+       char mail_id_string[10] = { 0, };
+
+       if (!_emdaemon_check_mail_id(mail_id, &err))  {
+               EM_DEBUG_EXCEPTION("_emdaemon_check_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if ( timeout_in_sec == 0 ) {
+               if(!emdaemon_send_mail(mail_id, NULL, &err)) {
+                       EM_DEBUG_EXCEPTION("emdaemon_send_mail failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       else if ( timeout_in_sec > 0 ) {
+               sprintf(mail_id_string,"%d",mail_id);
+               nTimerValue = timeout_in_sec * 1000;
+               if ( emcore_set_timer_ex(nTimerValue, (EMAIL_TIMER_CALLBACK) _OnMailSendRetryTimerCB, (void*)mail_id_string) <= 0) {
+                       EM_DEBUG_EXCEPTION("Failed to start timer");
+                       goto FINISH_OFF;
+               }
+       }
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+
+       return ret;
+}
+
+
+INTERNAL_FUNC void _OnMailSendRetryTimerCB( void* data )
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int mail_id = 0 ;
+
+       if( !data ) {
+               EM_DEBUG_LOG("Invalid param");
+               goto FINISH_OFF;
+       }
+
+       mail_id = atoi((char*)data);
+
+       if (!_emdaemon_check_mail_id(mail_id, &err))  {
+               EM_DEBUG_EXCEPTION("_emdaemon_check_mail_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if(!emdaemon_send_mail(mail_id, NULL, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_send_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END();
+       return;
+}
+
+INTERNAL_FUNC int emdaemon_move_mail_thread_to_mailbox(int thread_id, int target_mailbox_id, int move_always_flag, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("thread_id [%d], target_mailbox_id [%d], move_always_flag [%d], err_code [%p]", thread_id, target_mailbox_id, move_always_flag, err_code);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int *mail_id_list = NULL, result_count = 0, i, mailbox_count = 0, account_id;
+       email_mail_list_item_t *mail_list = NULL;
+       email_mailbox_t *target_mailbox_list = NULL, *target_mailbox = NULL;
+       char mailbox_id_param_string[10] = {0,};
+
+       if (target_mailbox_id == 0) {
+               EM_DEBUG_EXCEPTION("target_mailbox_id [%d]", target_mailbox_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_get_mail_list(0, 0, NULL, thread_id, -1, -1, 0, NULL, EMAIL_SORT_DATETIME_HIGH, true, &mail_list, &result_count, &err) || !mail_list || !result_count) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       mail_id_list = em_malloc(sizeof(int) * result_count);
+
+       if (mail_id_list == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < result_count; i++) {
+               mail_id_list[i] = mail_list[i].mail_id;
+       }
+       account_id = mail_list[0].account_id;
+
+
+       if (!emcore_get_mailbox_list(account_id, &target_mailbox_list, &mailbox_count, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_get_mailbox_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < mailbox_count; i++) {
+               EM_DEBUG_LOG("%s %d", target_mailbox_list[i].mailbox_name, target_mailbox_id);
+               if(target_mailbox_list[i].mailbox_id == target_mailbox_id) {
+                       target_mailbox = (target_mailbox_list + i);
+                       break;
+               }
+       }
+
+       if(!target_mailbox) {
+               EM_DEBUG_EXCEPTION("couldn't find proper target mailbox.");
+               goto FINISH_OFF;
+       }
+
+       if (!emdaemon_move_mail(mail_id_list, result_count, target_mailbox->mailbox_id, EMAIL_MOVED_BY_MOVING_THREAD, move_always_flag, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_move_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       SNPRINTF(mailbox_id_param_string, 10, "%d", target_mailbox->mailbox_id);
+       if (!emcore_notify_storage_event(NOTI_THREAD_MOVE, account_id, thread_id, mailbox_id_param_string, move_always_flag))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [NOTI_MAIL_MOVE] >>>> ");
+
+       ret = true;
+
+FINISH_OFF:
+       emcore_free_mailbox_list(&target_mailbox_list, mailbox_count);
+       EM_SAFE_FREE(mail_list);
+       EM_SAFE_FREE(mail_id_list);
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_delete_mail_thread(int thread_id, int delete_always_flag, int *handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("thread_id [%d], delete_always_flag [%d], err_code [%p]", thread_id, delete_always_flag, err_code);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int account_id = 0;
+       int mailbox_id, *mail_id_list = NULL, result_count = 0, i;
+       email_mail_list_item_t *mail_list = NULL;
+
+       if (!emstorage_get_mail_list(0, 0, NULL, thread_id, -1, -1, 0, NULL, EMAIL_SORT_MAILBOX_NAME_HIGH, true, &mail_list, &result_count, &err) || !mail_list || !result_count) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       mail_id_list = em_malloc(sizeof(int) * result_count);
+
+       if (mail_id_list == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < result_count; i++) {
+               mail_id_list[i] = mail_list[i].mail_id;
+       }
+
+       account_id = mail_list[0].account_id;
+       mailbox_id = mail_list[0].mailbox_id;
+
+       // should remove requiring of mailbox information from this function.
+       // email-service should find mailboxes itself by its mail id.
+       if (!emdaemon_delete_mail(mailbox_id, mail_id_list, result_count, false, handle, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_delete_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_notify_storage_event(NOTI_THREAD_DELETE, account_id, thread_id, NULL, delete_always_flag))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [NOTI_THREAD_DELETE] >>>> ");
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(mail_list);
+       EM_SAFE_FREE(mail_id_list);
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_modify_seen_flag_of_thread(int thread_id, int seen_flag, int on_server, int *handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("thread_id [%d], seen_flag [%d], on_server [%d], handle [%p], err_code [%p]", thread_id, seen_flag, on_server, handle, err_code);
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       int account_id, *mail_id_list = NULL, result_count = 0, i;
+       email_mail_list_item_t *mail_list = NULL;
+
+       if (!emstorage_get_mail_list(0, 0, NULL, thread_id, -1, -1, 0, NULL, EMAIL_SORT_MAILBOX_NAME_HIGH, true, &mail_list, &result_count, &err) || !mail_list || !result_count) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mail_list failed [%d]", err);
+
+               goto FINISH_OFF;
+       }
+
+       mail_id_list = em_malloc(sizeof(int) * result_count);
+
+       if (mail_id_list == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed...");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       for(i = 0; i < result_count; i++) {
+               mail_id_list[i] = mail_list[i].mail_id;
+       }
+
+       account_id = mail_list[0].account_id;
+
+       if (!emdaemon_set_flags_field(account_id, mail_id_list, result_count, EMAIL_FLAGS_SEEN_FIELD, seen_flag, on_server, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_set_flags_field failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_notify_storage_event(NOTI_THREAD_MODIFY_SEEN_FLAG, account_id, thread_id, NULL, seen_flag))
+               EM_DEBUG_EXCEPTION(" emcore_notify_storage_event Failed [NOTI_MAIL_MOVE] >>>> ");
+
+       ret = true;
+
+FINISH_OFF:
+       EM_SAFE_FREE(mail_list);
+       EM_SAFE_FREE(mail_id_list);
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_on_server [%d], output_handle [%p]", input_mailbox_id, input_on_server, output_handle);
+       int                      err = EMAIL_ERROR_NONE;
+       int                      handle = 0;
+       email_event_t              event_data = { 0 };
+       email_account_t           *ref_account = NULL;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+
+       if (input_mailbox_id <= 0)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox_tbl->account_id);
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", mailbox_tbl->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_SYNC_CLIENT_TO_SERVER__
+       if(input_on_server) {
+               event_data.type               = EMAIL_EVENT_EXPUNGE_MAILS_DELETED_FLAGGED;
+               event_data.account_id         = mailbox_tbl->account_id;
+               event_data.event_param_data_4 = input_mailbox_id;
+
+               if (!emcore_insert_event(&event_data, &handle, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       else
+#endif
+               if ( (err = emcore_expunge_mails_deleted_flagged_from_local_storage(input_mailbox_id)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_expunge_mails_deleted_flagged_from_local_storage failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if(mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-daemon/email-daemon-mailbox.c b/email-daemon/email-daemon-mailbox.c
new file mode 100755 (executable)
index 0000000..c6d7162
--- /dev/null
@@ -0,0 +1,650 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+
+/******************************************************************************
+ * File: email-daemon-mailbox.c
+ * Desc: email-daemon Mailbox Operation
+ *
+ * Auth:
+ *
+ * History:
+ *    2006.08.16 : created
+ *****************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "email-daemon.h"
+#include "email-core-event.h"
+#include "email-daemon-account.h"
+#include "email-debug-log.h"
+#include "email-core-mailbox.h"
+#include "email-core-account.h"
+#include "email-core-global.h"
+#include "email-core-utils.h"
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+extern int g_local_activity_run;
+#endif
+
+INTERNAL_FUNC int emdaemon_get_imap_mailbox_list(int account_id, char* mailbox, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d] mailbox[%p] err_code[%p]", account_id, mailbox, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t* ref_account = NULL;
+
+       if (account_id <= 0 ||!mailbox)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], mailbox[%p]", account_id, mailbox);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       email_event_t event_data;
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       event_data.type = EMAIL_EVENT_SYNC_IMAP_MAILBOX;
+       event_data.account_id = account_id;
+       event_data.event_param_data_3 = EM_SAFE_STRDUP(mailbox);
+
+       if (!emcore_insert_event(&event_data, (int*)handle, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_get_mailbox_list(int account_id, email_mailbox_t** mailbox_list, int* count, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id[%d], mailbox_list[%p], count[%p], err_code[%p]", account_id, mailbox_list, count, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t* ref_account = NULL;
+
+       if (account_id <= 0 || !mailbox_list || !count)  {
+               EM_DEBUG_EXCEPTION("account_id[%d], mailbox_list[%p], count[%p]", account_id, mailbox_list, count);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_mailbox_list(account_id, mailbox_list, count, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_get_mailbox_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_get_mail_count_of_mailbox(email_mailbox_t* mailbox, int* total, int* unseen, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("mailbox[%p], total[%p], unseen[%p], err_code[%p]", mailbox, total, unseen, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t* ref_account = NULL;
+
+       if (!mailbox || !total || !unseen)  {
+               EM_DEBUG_EXCEPTION("mailbox[%p], total[%p], unseen[%p]", mailbox, total, unseen);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox->account_id);
+       if (ref_account == NULL)  {
+               EM_DEBUG_EXCEPTION(" emcore_get_account_reference failed [%d]", mailbox->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_mail_count(mailbox, total, unseen, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_count failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_add_mailbox(email_mailbox_t* new_mailbox, int on_server, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("new_mailbox[%p], err_code[%p]", new_mailbox, err_code);
+
+       int ret = false;;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t* ref_account = NULL;
+
+       if (!new_mailbox || new_mailbox->account_id <= 0 || !new_mailbox->mailbox_name)  {
+               if (new_mailbox != NULL)
+                       EM_DEBUG_EXCEPTION("new_mailbox->account_id[%d], new_mailbox->mailbox_name[%p]", new_mailbox->account_id, new_mailbox->mailbox_name);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(new_mailbox->account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", new_mailbox->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       email_event_t event_data;
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+
+       /*  on_server is allowed to be only 0 when server_type is EMAIL_SERVER_TYPE_ACTIVE_SYNC */
+       if ( ref_account->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC )
+               on_server = 0;
+
+       if ( on_server ) {      /*  async */
+               event_data.type               = EMAIL_EVENT_CREATE_MAILBOX;
+               event_data.account_id         = new_mailbox->account_id;
+               event_data.event_param_data_1 = EM_SAFE_STRDUP(new_mailbox->mailbox_name);
+               event_data.event_param_data_2 = EM_SAFE_STRDUP(new_mailbox->alias);
+               event_data.event_param_data_4 = on_server;
+               event_data.event_param_data_3 = GINT_TO_POINTER(new_mailbox->mailbox_type);
+               if(!emcore_insert_event(&event_data, (int*)handle, &err))    {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       else {  /*  sync */
+               if (!emcore_create_mailbox(new_mailbox, on_server, &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_create failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_update_mailbox(email_mailbox_t* old_mailbox, email_mailbox_t* new_mailbox, int on_server, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("old_mailbox[%p], new_mailbox[%p], on_server[%d], handle[%p], err_code[%p]", old_mailbox, new_mailbox, on_server, handle, err_code);
+
+       /*  default variable */
+       int ret = false;;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t* ref_account = NULL;
+
+       if (!old_mailbox || old_mailbox->account_id <= 0 || !old_mailbox->mailbox_name
+               || !new_mailbox || new_mailbox->account_id <= 0 || !new_mailbox->mailbox_name)  {
+               EM_DEBUG_EXCEPTION("INVALID PARAM");
+               if (old_mailbox != NULL)
+                       EM_DEBUG_EXCEPTION("old_mailbox->account_id[%d], old_mailbox->mailbox_name[%p]", old_mailbox->account_id, old_mailbox->mailbox_name);
+               if (new_mailbox != NULL)
+                       EM_DEBUG_EXCEPTION("new_mailbox->account_id[%d], new_mailbox->mailbox_name[%p]", new_mailbox->account_id, new_mailbox->mailbox_name);
+
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(old_mailbox->account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", old_mailbox->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;              /*  instead of EMAIL_ERROR_INVALID_PARAM; */
+               goto FINISH_OFF;
+       }
+
+       email_event_t event_data;
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       /*  Update mailbox information only on local db */
+       if (!emcore_update_mailbox(old_mailbox, new_mailbox, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_modify failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_set_mailbox_type(int input_mailbox_id, email_mailbox_type_e input_mailbox_type)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_mailbox_type [%d]", input_mailbox_id, input_mailbox_type);
+
+       /*  default variable */
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+
+       if (!input_mailbox_id)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ( (err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emstorage_update_mailbox_type(mailbox_tbl->account_id, -1, mailbox_tbl->mailbox_name, input_mailbox_type, true, &err))  {
+               EM_DEBUG_EXCEPTION("emstorage_update_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+
+FINISH_OFF:
+       if (mailbox_tbl)
+               emstorage_free_mailbox(&mailbox_tbl, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emdaemon_set_local_mailbox(int input_mailbox_id, int input_is_local_mailbox)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_mailbox_type [%d]", input_mailbox_id, input_is_local_mailbox);
+
+       /*  default variable */
+       int err = EMAIL_ERROR_NONE;
+
+       if (input_mailbox_id <= 0)  {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if ( (err = emstorage_set_local_mailbox(input_mailbox_id, input_is_local_mailbox, true)) != EMAIL_ERROR_NONE)  {
+               EM_DEBUG_EXCEPTION("emstorage_set_local_mailbox failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+INTERNAL_FUNC int emdaemon_delete_mailbox(int input_mailbox_id, int on_server, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id[%d], err_code[%p]", input_mailbox_id, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       emstorage_mailbox_tbl_t *mailbox_tbl = NULL;
+       email_account_t* ref_account = NULL;
+
+       if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &mailbox_tbl)) != EMAIL_ERROR_NONE || !mailbox_tbl) {
+               EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed. [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!input_mailbox_id || mailbox_tbl->account_id <= 0)  {
+               if (input_mailbox_id != 0)
+                       EM_DEBUG_EXCEPTION("mailbox_tbl->account_id[%d]", mailbox_tbl->account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox_tbl->account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", mailbox_tbl->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       email_event_t event_data;
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       /*  on_server is allowed to be only 0 when server_type is EMAIL_SERVER_TYPE_ACTIVE_SYNC */
+       if ( ref_account->incoming_server_type == EMAIL_SERVER_TYPE_ACTIVE_SYNC ) {
+               on_server = 0;
+       }
+       if ( on_server ) {      /*  async */
+               event_data.type = EMAIL_EVENT_DELETE_MAILBOX;
+               event_data.account_id = mailbox_tbl->account_id;
+               event_data.event_param_data_4 = input_mailbox_id;
+               event_data.event_param_data_5 = on_server;
+               if(!emcore_insert_event(&event_data, (int*)handle, &err))    {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       else {
+               if (!emcore_delete_mailbox(input_mailbox_id, on_server,  &err))  {
+                       EM_DEBUG_EXCEPTION("emcore_delete failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_delete_mailbox_all(email_mailbox_t* mailbox, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("malibox[%p], err_code[%p]", mailbox, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_account_t* ref_account = NULL;
+
+       if (!mailbox)  {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (mailbox->account_id <= 0)  {
+               EM_DEBUG_EXCEPTION("malibox->account_id[%d]", mailbox->account_id);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(mailbox->account_id);
+
+       if (!ref_account)  {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", mailbox->account_id);
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_delete_mailbox_all(mailbox, &err))  {
+               EM_DEBUG_EXCEPTION("emcore_delete_all failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+
+INTERNAL_FUNC int emdaemon_sync_header(int input_account_id, int input_mailbox_id, int *handle, int* err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("input_account_id[%d], input_mailbox_id[%d], handle[%p], err_code[%p]", input_account_id, input_mailbox_id, handle, err_code);
+
+       /*  default variable */
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+
+       email_event_t event_data;
+       email_account_t* ref_account = NULL;
+
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       if (input_mailbox_id < 0) {
+               EM_DEBUG_EXCEPTION("parameter is invalid");
+               err = EMAIL_ERROR_INVALID_ACCOUNT;
+               goto FINISH_OFF;
+       }
+
+       if(input_account_id == ALL_ACCOUNT) {
+               EM_DEBUG_LOG(">>>> emdaemon_sync_header for all account event_data.event_param_data_4 [%d]", event_data.event_param_data_4);
+               event_data.type               = EMAIL_EVENT_SYNC_HEADER;
+               event_data.account_id         = input_account_id;
+               event_data.event_param_data_5 = input_mailbox_id;
+               /* In case of Mailbox NULL, we need to set arg as EMAIL_SYNC_ALL_MAILBOX */
+               if (input_mailbox_id == 0)
+                       event_data.event_param_data_4 = EMAIL_SYNC_ALL_MAILBOX;
+
+               if (!emcore_insert_event(&event_data, (int*)handle, &err))   {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       else {
+
+               if (!(ref_account = emcore_get_account_reference(input_account_id))) {
+                       EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", input_account_id);
+                       err = EMAIL_ERROR_INVALID_ACCOUNT;
+                       goto FINISH_OFF;
+               }
+
+               /* Modified the code to sync all mailbox in a Single Event */
+               event_data.type               = EMAIL_EVENT_SYNC_HEADER;
+               event_data.account_id         = input_account_id;
+               event_data.event_param_data_5 = input_mailbox_id;
+               /* In case of Mailbox NULL, we need to set arg as EMAIL_SYNC_ALL_MAILBOX */
+               if (input_mailbox_id == 0)
+                       event_data.event_param_data_4 = EMAIL_SYNC_ALL_MAILBOX;
+               EM_DEBUG_LOG(">>>> EVENT ARG [ %d ] ", event_data.event_param_data_4);
+
+               if (!emcore_insert_event(&event_data, (int*)handle, &err))   {
+                       EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+#ifdef __FEATURE_LOCAL_ACTIVITY__
+       EM_DEBUG_LOG("Setting g_local_activity_run ");
+       g_local_activity_run = 1;
+#endif
+
+       ret = true;
+
+FINISH_OFF:
+
+       if (ref_account) {
+               emcore_free_account(ref_account);
+               EM_SAFE_FREE(ref_account);
+       }
+
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_set_mail_slot_size_of_mailbox(int account_id, int mailbox_id, int new_slot_size, int *handle, int *err_code)
+{
+       EM_DEBUG_FUNC_BEGIN("account_id [%d], mailbox_id[%d], handle[%p], err_code[%p]", account_id, mailbox_id, handle, err_code);
+
+       int ret = false;
+       int err = EMAIL_ERROR_NONE;
+       email_event_t event_data;
+
+       if(handle == NULL) {
+               EM_DEBUG_EXCEPTION("handle is required");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       memset(&event_data, 0x00, sizeof(email_event_t));
+
+       event_data.type = EMAIL_EVENT_SET_MAIL_SLOT_SIZE;
+       event_data.account_id = account_id;
+       event_data.event_param_data_4 = mailbox_id;
+       event_data.event_param_data_5 = new_slot_size;
+
+       if (!emcore_insert_event(&event_data, (int*)handle, &err))   {
+               EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ret = true;
+
+FINISH_OFF:
+       if (err_code)
+               *err_code = err;
+       EM_DEBUG_FUNC_END();
+       return ret;
+}
+
+INTERNAL_FUNC int emdaemon_rename_mailbox(int input_mailbox_id, char *input_mailbox_path, char *input_mailbox_alias, int input_on_server, int *output_handle)
+{
+       EM_DEBUG_FUNC_BEGIN("input_mailbox_id [%d], input_mailbox_path [%p], input_mailbox_alias[%p], input_on_server [%d], output_handle[%p]", input_mailbox_id, input_mailbox_path, input_mailbox_alias, input_on_server, output_handle);
+
+       int err = EMAIL_ERROR_NONE;
+       emstorage_account_tbl_t *account_data = NULL;
+       emstorage_mailbox_tbl_t *old_mailbox_data = NULL;
+       email_event_t event_data;
+
+       if(input_mailbox_id <= 0 || output_handle == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if (input_on_server) {
+               if ((err = emstorage_get_mailbox_by_id(input_mailbox_id, &old_mailbox_data)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_mailbox_by_id failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (!emstorage_get_account_by_id(old_mailbox_data->account_id, EMAIL_ACC_GET_OPT_DEFAULT, &account_data, true, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_get_account_by_id failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               if (account_data->incoming_server_type == EMAIL_SERVER_TYPE_IMAP4) {
+                       memset(&event_data, 0x00, sizeof(email_event_t));
+
+                       event_data.type               = EMAIL_EVENT_RENAME_MAILBOX_ON_IMAP_SERVER;
+                       event_data.event_param_data_1 = EM_SAFE_STRDUP(old_mailbox_data->mailbox_name);
+                       event_data.event_param_data_2 = EM_SAFE_STRDUP(input_mailbox_path);
+                       event_data.event_param_data_3 = EM_SAFE_STRDUP(input_mailbox_alias);
+                       event_data.event_param_data_4 = input_mailbox_id;
+                       event_data.account_id         = old_mailbox_data->account_id;
+
+                       if (!emcore_insert_event(&event_data, (int*)output_handle, &err)) {
+                               EM_DEBUG_EXCEPTION("emcore_insert_event falied [%d]", err);
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+       else {
+               if ((err = emstorage_rename_mailbox(input_mailbox_id, input_mailbox_path, input_mailbox_alias, true)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emstorage_rename_mailbox failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       if (old_mailbox_data)
+               emstorage_free_mailbox(&old_mailbox_data, 1, NULL);
+
+       if (account_data)
+               emstorage_free_account(&account_data, 1, NULL);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
diff --git a/email-daemon/include/.gitignore b/email-daemon/include/.gitignore
new file mode 100644 (file)
index 0000000..f42dfd4
--- /dev/null
@@ -0,0 +1,2 @@
+contact-engine-h
+filemanager-service-h
diff --git a/email-daemon/include/email-daemon-account.h b/email-daemon/include/email-daemon-account.h
new file mode 100755 (executable)
index 0000000..b1394f6
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File: email-daemon-account.h
+ * Desc: email-daemon Account Header
+ *
+ * Auth:
+ *
+ * History:
+ *    2006.08.01 : created
+ *****************************************************************************/
+#ifndef __EMAIL_DAEMON_ACCONT_H__
+#define __EMAIL_DAEMON_ACCONT_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include "email-daemon.h"
+
+int emdaemon_initialize_account_reference();
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-daemon/include/email-daemon-auto-poll.h b/email-daemon/include/email-daemon-auto-poll.h
new file mode 100755 (executable)
index 0000000..b165b18
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/**
+ * This file defines all APIs of Auto Poll.
+ * @file       email-daemon-auto-poll.h
+ * @author  
+ * @version    0.1
+ * @brief      This file is the header file of Auto Poll.
+ */
+#ifndef __EMAIL_DAEMON_AUTO_POLL_H__
+#define __EMAIL_DAEMON_AUTO_POLL_H__
+
+#include "email-internal-types.h"
+#include "alarm.h"
+
+#ifdef __FEATURE_AUTO_POLLING__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+INTERNAL_FUNC int emdaemon_add_polling_alarm(int account_id, int alarm_interval);
+INTERNAL_FUNC int emdaemon_remove_polling_alarm(int account_id);
+INTERNAL_FUNC int emdaemon_check_auto_polling_started(int account_id);
+INTERNAL_FUNC int emdaemon_alarm_polling_cb(alarm_id_t  alarm_id, void* user_param);
+INTERNAL_FUNC int emdaemon_free_account_alarm_binder_list();
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* __FEATURE_AUTO_POLLING__ */
+
+#endif /* __EMAIL_DAEMON_AUTO_POLL_H__ */
+/* EOF */
diff --git a/email-daemon/include/email-daemon-emn.h b/email-daemon/include/email-daemon-emn.h
new file mode 100755 (executable)
index 0000000..a91bb65
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/**
+ * This file defines all APIs of EMN.
+ * @file       email-daemon-emn.h
+ * @author     Kyuho Jo(kyuho.jo@samsung.com)
+ * @version    0.1
+ * @brief      This file is the header file of EMN library.
+ */
+
+#ifndef __EMAIL_DAEMON_EMN_H__
+#define __EMAIL_DAEMON_EMN_H__
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMN EMN
+* @{
+*/
+
+#include "email-internal-types.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+enum
+{
+       EMN_HEADER_DATA = 0,
+       EMN_WBXML_DATA,
+};
+
+/* Error Values for the Email options */
+enum
+{
+       EMAIL_OPTION_ERROR_NONE = 0,
+       EMAIL_OPTION_ERROR_INVALID_PARAM,
+       EMAIL_OPTION_ERROR_STORAGE,
+};
+
+/* Manual Network value */
+#define   EMAIL_OPTION_NETWORK_MANUAL  1
+
+
+/* Enums for the Gcong Option Key */
+typedef enum
+{
+       EMAIL_OPTION_KEY_HOME_NETWORK = 0,
+       EMAIL_OPTION_KEY_ROAMING_NETWORK,
+}optionkey;
+
+
+int emdaemon_initialize_emn(void);
+int emdaemon_finalize_emn(int bExtDest);
+
+/** 
+ * This callback specifies the callback of retrieving the result that is downloaded new messages.
+ *
+ * @param[in] mail_count       Specifies count of new mail.
+ * @param[in] user_data                Specifies the user data.
+ * @param[in] err_code         Specifies the error code.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+typedef int (*email_emn_noti_cb)(
+       void*                                   user_data,
+       int                     err_code
+);
+
+#ifdef USE_OMA_EMN
+/**
+ * Handle OMA EMN data
+ *
+ * @param[in] wbxml_b64                Specifies the encoded string
+ * @param[in] callback         Specifies the callback function for retrieving the result that is downloaded new mail.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_handle_emn_notification(unsigned char* wbxml_b64, email_emn_noti_cb callback, int* err_code);
+#endif
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/**
+* @} @}
+*/
+
+
+#endif /* __EMAIL_DAEMON_EMN_H__ */
+/* EOF */
+
diff --git a/email-daemon/include/email-daemon-init.h b/email-daemon/include/email-daemon-init.h
new file mode 100755 (executable)
index 0000000..74760fc
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/******************************************************************************
+ * File: email-daemon-init.h
+ * Desc: email-daemon Initialization Header
+ *
+ * Auth:
+ *
+ * History:
+ *    2006.08.16 : created
+ *****************************************************************************/
+#ifndef __EMAIL_DAEMON_INIT_H__
+#define __EMAIL_DAEMON_INIT_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#include "email-storage.h"
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif
diff --git a/email-daemon/include/email-daemon-mutex.h b/email-daemon/include/email-daemon-mutex.h
new file mode 100755 (executable)
index 0000000..3917473
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 _EM_DAEMON_MUTEX_H_
+#define _EM_DAEMON_MUTEX_H_
+
+#include <sys/time.h>
+
+#endif /* _EM_DAEMON_MUTEX_H_ */
+
diff --git a/email-daemon/include/email-daemon.h b/email-daemon/include/email-daemon.h
new file mode 100755 (executable)
index 0000000..39de525
--- /dev/null
@@ -0,0 +1,666 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+
+/**
+ * This file defines all APIs of Email Framework.
+ * @file       email-daemon.h
+ * @author     Kyu-ho Jo(kyuho.jo@samsung.com)
+ * @version    0.1
+ * @brief      This file is the header file of email-engine library.
+ */
+#ifndef __EMAIL_DAEMON_H__
+#define __EMAIL_DAEMON_H__
+
+/**
+* @defgroup EMAIL_SERVICE EmailFW
+* @{
+*/
+
+/**
+* @ingroup EMAIL_SERVICE
+* @defgroup EMAIL_SERVICE Email Service
+* @{
+*/
+
+#include "email-types.h"
+#include "email-internal-types.h"
+
+#include <time.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/*****************************************************************************/
+/*  Initialization                                                           */
+/*****************************************************************************/
+/**
+ * Initialize Email-engine.
+ *
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_initialize(int* err_code);
+
+/**
+ * Finalize Email-engine.
+ *
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_finalize(int* err_code);
+
+
+/*****************************************************************************/
+/*  Account                                                                  */
+/*****************************************************************************/
+/**
+ * Create a new email account.
+ *
+ * @param[in] account  Specifies the structure pointer of account.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_create_account(email_account_t* account, int* err_code);
+
+/**
+ * Delete a email account.
+ *
+ * @param[in] account_id       Specifies the account ID.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_delete_account(int account_id, int* err_code);
+
+/**
+ * Validate a email account.
+ *
+ * @param[in] account_id       Specifies the account ID.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_validate_account(int account_id, int *handle, int* err_code);
+
+/**
+ * Change the information of a email account.
+ *
+ * @param[in] account_id       Specifies the orignal account ID.
+ * @param[in] new_account      Specifies the information of new account.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_update_account(int account_id, email_account_t* new_account, int* err_code);
+
+/**
+ * Change the information of a email account after validation
+ *
+ * @param[in] old_account_id   Specifies the orignal account ID.
+ * @param[in] new_account_info Specifies the information of new account.
+ * @param[in] handle                   Specifies the handle for stopping validation.
+ * @param[out] err_code                        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_validate_account_and_update(int old_account_id, email_account_t* new_account_info, int *handle,int *err_code);
+
+/**
+ * Get a email account by ID.
+ *
+ * @param[in] account_id       Specifies the account ID.
+ * @param[in] pulloption       Specifies the pulloption.
+ * @param[out] acount          The returned account is saved here.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_get_account(int account_id, int pulloption, email_account_t* acount, int* err_code);
+
+/**
+ * Get all emails.
+ *
+ * @param[out] acount_list     The returned accounts are saved here.(possibly NULL)
+ * @param[out] count                   The count of returned accounts is saved here.(possibly 0)
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_get_account_list(email_account_t** acount_list, int* count, int* err_code);
+
+/**
+ * Free allocated memory.
+ *
+ * @param[in] account_list     Specifies the structure pointer of account.
+ * @param[in] count                    Specifies the count of accounts.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_free_account(email_account_t** account_list, int count, int* err_code);
+
+/**
+ * Get a information of filtering.
+ *
+ * @param[in] filter_id                        Specifies the filter ID.
+ * @param[out] filtering_set   The returned information of filter are saved here.
+ * @param[out] err_code                        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_get_filter(int filter_id, email_rule_t** filtering_set, int* err_code);
+
+/**
+ * Get all filterings.
+ *
+ * @param[out] filtering_set           The returned filterings are saved here.(possibly NULL)
+ * @param[out] count                           The count of returned filters is saved here.(possibly 0)
+ * @param[out] err_code                        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_get_filter_list(email_rule_t** filtering_set, int* count, int* err_code);
+
+/**
+ * find a filter already exists.
+ *
+ * @param[in] filtering_set    Specifies the pointer of adding filter structure.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true if enable add filter, else returns false.
+ */
+INTERNAL_FUNC int emdaemon_find_filter(email_rule_t* filter_info, int* err_code);
+
+/**
+ * Add a filter information.
+ *
+ * @param[in] filtering_set            Specifies the pointer of adding filter structure.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.(only EMAIL_FILTER_BLOCK supported.)
+ */
+INTERNAL_FUNC int emdaemon_add_filter(email_rule_t* filtering_set);
+
+/**
+ * Change a filter information.
+ *
+ * @param[in] filter_id        Specifies the original filter ID.
+ * @param[in] new_set  Specifies the information of new filter.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_update_filter(int filter_id, email_rule_t* new_set, int* err_code);
+
+/**
+ * Delete a filter information.
+ *
+ * @param[in] filter_id        Specifies the filter ID.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_delete_filter(int filter_id, int* err_code);
+
+/**
+ * Free allocated memory.
+ *
+ * @param[in] filtering_set    Specifies the pointer of pointer of filter structure for memory free.
+ * @param[in] count                    Specifies the count of filter.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_free_filter (email_rule_t** filtering_set, int count, int* err_code);
+
+
+/*****************************************************************************/
+/*  Mail                                                                     */
+/*****************************************************************************/
+
+/**
+ * Send a mail.
+ *
+ * @param[in] mail_id                          Specifies the mail ID.
+ * @param[in] callback                 Specifies the callback function for retrieving sending information.
+ * @param[in] handle                           Specifies the handle for stopping sending.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_send_mail(int mail_id, int *handle, int* err_code);
+
+/**
+ * Send all mails to been saved in Offline-mode.
+ *
+ * @param[in] account_id                       Specifies the account ID.
+ * @param[in] callback                         Specifies the callback function for retrieving sending information.
+ * @param[in] handle                                   Specifies the handle for stopping sending.
+ * @param[out] err_code                        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_send_mail_saved(int account_id, int *handle, int* err_code);
+
+INTERNAL_FUNC int emdaemon_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas);
+
+INTERNAL_FUNC int emdaemon_add_meeting_request(int account_id, int input_mailbox_id, email_meeting_request_t *meeting_req, int* err_code);
+
+/**
+ * Delete a mail or multiple mails.
+ *
+ * @param[in] mailbox_id               Specifies the mailbox.
+ * @param[in] mail_id                  Specifies the arrary of mail id.
+ * @param[in] num                              Specifies the number of mail id.
+ * @param[in] from_server          Specifies whether mails are deleted from server.
+ * @param[in] callback                 Specifies the callback function for retrieving deleting information.
+ * @param[in] handle                           Reserved.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+
+INTERNAL_FUNC int emdaemon_delete_mail(int mailbox_id, int mail_id[], int num, int from_server,  int *handle, int* err_code);
+
+/**
+ * Delete all mail from a mailbox.
+ *
+ * @param[in] input_mailbox_id Specifies the id of target mailbox.
+ * @param[in] input_from_server        Specifies whether mails are also deleted from server.
+ * @param[in] output_handle            Reserved.
+ * @param[out] output_err_code Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_delete_mail_all(int input_mailbox_id, int input_from_server, int *output_handle, int *output_err_code);
+
+/**
+ * Move a email to another mailbox.
+ *
+ *
+ * @param[in] mail_id                  Specifies the mail ID.
+ * @param[in] dst_mailbox_id   Specifies the mailbox ID for moving email.
+ * @param[in] noti_param_1     Specifies first parameter of result notification.
+ * @param[in] noti_param_2     Specifies second parameter of result notification.
+ * @param[out] err_code                        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_move_mail(int mail_ids[], int num, int dst_mailbox_id, int noti_param_1, int noti_param_2, int* err_code);
+
+/**
+ * Move all email to another mailbox.
+ *
+ *
+ * @param[in] src_mailbox_id           Specifies the source mailbox ID for moving email.
+ * @param[in] dst_mailbox_id           Specifies the destination mailbox ID for moving email.
+ * @param[out] err_code                                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_move_mail_all_mails(int src_mailbox_id, int dst_mailbox_id, int* err_code);
+
+
+/**
+ * Update a existing email information.
+ *
+ * @param[in] input_mail_data  Specifies the structure of mail data.
+ * @param[in] input_attachment_data_list       Specifies the structure of mail data.
+ * @param[in] input_attachment_count   Specifies the pointer of attachment structure.
+ * @param[in] input_meeting_request    Specifies the number of attachment data.
+ * @param[in] input_from_eas   Specifies whether the mail is from EAS.
+ * @remarks N/A
+ * @return This function returns EMAIL_ERROR_NONE on success or error code on failure.
+ */
+INTERNAL_FUNC int emdaemon_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t *input_meeting_request, int input_from_eas);
+
+
+/**
+ * Callback for mail resend
+ *
+ * @param[in] data                           Specifies the pointer to mail_id.
+ * @remarks N/A
+ * @return This function returns void.
+ */
+INTERNAL_FUNC void _OnMailSendRetryTimerCB( void* data );
+
+/**
+ * Download email body from server.
+ *
+ * @param[in] account_id               Specifies the account ID.
+ * @param[in] mail_id                  Specifies the mail ID.
+ * @param[in] callback         Specifies the callback function for retrieving download status.
+ * @param[in] handle                   Specifies the handle for stopping downloading.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_download_body(int account_id, int mail_id, int verbose, int with_attachment,  int *handle, int* err_code);
+
+/**
+ * Get a mail attachment.
+ *
+ * @param[in] mail_id          Specifies the mail ID.
+ * @param[in] attachment_id    Specifies the attachment ID.
+ * @param[out] attachment      The returned attachment is save here.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_get_attachment(int attachment_id, email_attachment_data_t** attachment, int* err_code);
+
+/**
+ * Download a email nth-attachment from server.
+ *
+ * @param[in] account_id               Specifies the account ID.
+ * @param[in] mail_id                  Specifies the mail ID.
+ * @param[in] nth                              Specifies the buffer that a attachment number been saved. the minimum number is "1".
+ * @param[in] callback         Specifies the callback function for retrieving download status.
+ * @param[in] handle                   Specifies the handle for stopping downloading.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_download_attachment(int account_id, int mail_id, int nth,  int *handle, int* err_code);
+
+
+/**
+ * Append a attachment to email.
+ *
+ * @param[in] mail_id          Specifies the mail ID.
+ * @param[in] attachment       Specifies the structure of attachment.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_add_attachment(int mail_id, email_attachment_data_t* attachment, int* err_code);
+
+/**
+ * Delete a attachment from email.
+ *
+ * @param[in] mail_id           Specifies the mail id.
+ * @param[in] attachment_id  Specifies the attachment id.
+ * @param[out] err_code         Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_delete_mail_attachment(int attachment_id, int* err_code);
+
+/**
+ * Free allocated memroy for email attachment.
+ *
+ * @param[in] atch_info        Specifies the pointer of mail attachment structure pointer.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_free_attachment_data(email_attachment_data_t** atch_info, int* err_code);
+
+/**
+ * Change email read/unread flag.
+ * @param[in] account_id  Specifies the account id.
+ * @param[in] mail_ids         Specifies the array of mail ID.
+ * @param[in] num                          Specifies the numbers of mail ID.
+ * @param[in] field_type  Specifies the field type what you want to set. Refer email_flags_field_type.
+ * @param[in] value          Specifies the value what you want to set.
+ * @param[in] onserver         Specifies the mail on server.
+ * @param[out] err_code          Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_set_flags_field(int account_id, int mail_ids[], int num, email_flags_field_type field_type, int value, int onserver, int* err_code);
+
+/*****************************************************************************/
+/*  Mailbox                                                                  */
+/*****************************************************************************/
+INTERNAL_FUNC int emdaemon_get_imap_mailbox_list(int account_id, char* mailbox, int *handle, int* err_code);
+
+/**
+ * Download header of new emails from mail server.
+ *
+ * @param[in] input_account_id         Specifies the account ID.
+ * @param[in] input_mailbox_id         Specifies the mailbox ID.
+ * @param[out] handle          Specifies the handle for stopping downloading.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_sync_header(int input_account_id, int input_mailbox_id, int *handle, int* err_code);
+
+
+/**
+ * Get mail count from mailbox.
+ *
+ * @param[in] mailbox  Specifies the pointer of mailbox structure.
+ * @param[out] total   Total email count is saved here.
+ * @param[out] unseen  Unread email count is saved here.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_get_mail_count_of_mailbox(email_mailbox_t* mailbox, int* total, int* unseen, int* err_code);
+
+/**
+ * Get all mailboxes from account.
+ *
+ * @param[in] account_id               Specifies the account ID.
+ * @param[out] mailbox_list    Specifies the pointer of mailbox structure pointer.(possibly NULL)
+ * @param[out] count                   The mailbox count is saved here.(possibly 0)
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_get_mailbox_list(int account_id, email_mailbox_t** mailbox_list, int* count, int* err_code);
+
+/**
+ * Create a new mailbox.
+ *
+ * @param[in] new_mailbox      Specifies the pointer of creating mailbox information.
+ * @param[out] handle          Specifies the handle for stopping creating mailbox.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_add_mailbox(email_mailbox_t* new_mailbox, int on_server, int *handle, int* err_code);
+
+/**
+ * Delete a mailbox.
+ *
+ * @param[in] input_mailbox_id Specifies the input_mailbox_id of deleting mailbox information.
+ * @param[out] handle                  Specifies the handle for stopping creating mailbox.
+ * @param[out] err_code                        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_delete_mailbox(int input_mailbox_id, int on_server, int *handle, int* err_code);
+
+/**
+ * Delete all sub-mailboxes from a specific mailbox.
+ *
+ * @param[in] mailbox  Specifies the pointer of mailbox information.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_delete_mailbox_all(email_mailbox_t* mailbox, int* err_code);
+
+/**
+ * Free allocated memory for mailbox information.
+ *
+ * @param[in] mailbox_list     Specifies the pointer for searching mailbox structure pointer.
+ * @param[in] count                    Specifies the count of mailboxes.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_free_mailbox(email_mailbox_t** mailbox_list, int count, int* err_code);
+
+/*****************************************************************************/
+/*  Etc                                                                      */
+/*****************************************************************************/
+
+
+/**
+ * Register a callback for event processing.
+ *
+ * @param[in] action                   Kind of event callback.
+ * @param[in] callback         Function which will be called during processing event.
+ * @param[in] event_data       Event data which will be passed to the callback.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_register_event_callback(email_action_t action, email_event_callback callback, void* event_data);
+
+/**
+ * Unregister a callback for event processing.
+ *
+ * @param[in] action                   Kind of event callback.
+ * @param[in] callback         Function which will be called during processing event.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_unregister_event_callback(email_action_t action, email_event_callback callback);
+
+/**
+ * Get current event queue status.
+ *
+ * @param[out] on_sending              True if sending is in progress.
+ * @param[out] on_receiving            True if receiving is in progress.
+ * @remarks N/A
+ */
+INTERNAL_FUNC void emdaemon_get_event_queue_status(int* on_sending, int* on_receiving);
+
+/**
+ * Get the handle of a pending job.
+ *
+ * @param[in] action                   Specifies kind of the job.
+ * @param[in] account_id       Specifies the account ID.
+ * @param[in] mail_id                  Specifies the mail ID.
+ * @remarks N/A
+ * @return This function return its handle if a pending job exists, otherwise -1.
+ */
+INTERNAL_FUNC int emdaemon_get_pending_job(email_action_t action, int account_id, int mail_id, email_event_status_type_t* status);
+
+/**
+ * Cancel a progressive work.
+ *
+ * @param[in] account_id               Specifies the account ID.
+ * @param[in] handle                           Specifies the ID of cancelling work.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_cancel_job(int account_id, int handle, int* err_code);
+
+
+
+/**
+ * Cancel a progressive send mail job.
+ *
+ * @param[in] account_id               Specifies the account ID.
+ * @param[in] mail_id                          Specifies the Mail ID of cancelling send mail.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_cancel_sending_mail_job(int account_id, int mail_id, int* err_code);
+
+/**
+ * set email options.
+ *
+ * @param[in] option                   Specifies the email options.
+ * @param[out] err_code        Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_set_option(email_option_t* option, int* err_code);
+
+/**
+ * get email options.
+ *
+ * @param[out] option                  Specifies the email options.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_get_option(email_option_t* option, int* err_code);
+
+/**
+ * Sync the Local activity
+ *
+ *
+ * @param[in] account_id               Specifies the Account ID.
+ * @param[out] err_code                Specifies the error code returned.
+ * @remarks N/A
+ * @return This function returns true on success or false on failure.
+ */
+INTERNAL_FUNC int emdaemon_sync_local_activity(int account_id, int *err_code);
+
+
+#ifdef __FEATURE_AUTO_POLLING__
+INTERNAL_FUNC int emdaemon_start_auto_polling(int* err_code);
+#endif /* __FEATURE_AUTO_POLLING__ */
+
+INTERNAL_FUNC int emdaemon_insert_accountinfo_to_contact(email_account_t* account);
+
+INTERNAL_FUNC int emdaemon_update_accountinfo_to_contact(email_account_t* old_account, email_account_t* new_account);
+
+INTERNAL_FUNC int emdaemon_update_mailbox(email_mailbox_t* old_mailbox, email_mailbox_t* new_mailbox, int on_server, int *handle, int* err_code);
+
+INTERNAL_FUNC int emdaemon_set_mailbox_type(int input_mailbox_id, email_mailbox_type_e input_mailbox_type);
+
+INTERNAL_FUNC int emdaemon_set_local_mailbox(int input_mailbox_id, int input_is_local_mailbox);
+
+INTERNAL_FUNC int emdaemon_search_mail_on_server(int input_account_id, int input_mailbox_id, email_search_filter_t *input_search_filter, int input_search_filter_count, unsigned int *output_handle, int *err_code);
+
+INTERNAL_FUNC int emdaemon_clear_all_mail_data(int* err_code);
+
+INTERNAL_FUNC int emdaemon_send_mail_retry( int mail_id,  int timeout_in_sec, int* err_code);
+
+INTERNAL_FUNC int emdaemon_validate_account_and_create(email_account_t* new_account, int *handle, int* err_code);
+
+INTERNAL_FUNC int emdaemon_set_mail_slot_size_of_mailbox(int account_id, int mailbox_id, int new_slot_size, int *handle, int *err_code);
+
+INTERNAL_FUNC int emdaemon_rename_mailbox(int input_mailbox_id, char *input_mailbox_path, char *input_mailbox_alias, int input_on_server, int *output_handle);
+
+INTERNAL_FUNC int emdaemon_move_mail_thread_to_mailbox(int thread_id, int target_mailbox_id, int move_always_flag, int *err_code);
+
+INTERNAL_FUNC int emdaemon_delete_mail_thread(int thread_id, int delete_always_flag, int *handle, int *err_code);
+
+INTERNAL_FUNC int emdaemon_modify_seen_flag_of_thread(int thread_id, int seen_flag, int on_server, int *handle, int *err_code);
+
+INTERNAL_FUNC int emdaemon_expunge_mails_deleted_flagged(int input_mailbox_id, int input_on_server, int *output_handle);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/**
+* @} @}
+*/
+
+#endif /* __EMAIL_DAEMON_H__ */
diff --git a/email-daemon/main.c b/email-daemon/main.c
new file mode 100755 (executable)
index 0000000..836c1b3
--- /dev/null
@@ -0,0 +1,3215 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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.
+*
+*/
+
+
+/* Email service Main .c */
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <malloc.h>
+#include <glib.h>
+#include <glib-object.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <signal.h>
+#include <time.h>
+
+#include "email-daemon.h"
+#include "email-ipc.h"
+#include "email-utilities.h"
+#include "email-debug-log.h"
+#include "email-daemon-auto-poll.h"
+#include "email-daemon-account.h"
+#include "email-convert.h"
+#include "email-internal-types.h"
+#include "email-types.h"
+#include "email-core-account.h"
+#include "email-core-mail.h"
+#include "email-core-smtp.h"
+#include "email-core-event.h"
+#include "email-core-global.h"
+#include "email-core-mailbox.h"
+#include "email-core-utils.h"
+#include "email-core-smime.h"
+#include "email-core-cert.h"
+#include "email-core-task-manager.h"
+#include "email-core-signal.h"
+#include "email-storage.h"
+
+void stb_create_account(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int buffer_size = 0;
+       int local_result = 0;
+       char* local_account_stream = NULL;
+       email_account_t account;
+       int err = EMAIL_ERROR_NONE;
+
+       /* Initialize the email_account_t */
+       memset(&account, 0x00, sizeof(email_account_t));
+
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       EM_DEBUG_LOG("size [%d]", buffer_size);
+       if(buffer_size <= 0)    {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       local_account_stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0);
+       /* Convert account stream to structure */
+       em_convert_byte_stream_to_account(local_account_stream, buffer_size, &account);
+
+
+       EM_DEBUG_LOG("Account name - %s", account.account_name);
+       EM_DEBUG_LOG("Email Address - %s", account.user_email_address);
+
+       if(!emdaemon_create_account(&account, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_create_account fail ");
+               goto FINISH_OFF;
+       }
+
+
+#ifdef __FEATURE_AUTO_POLLING__
+       /* start auto polling, if check_interval not zero */
+       if(account.check_interval > 0) {
+               if(!emdaemon_add_polling_alarm( account.account_id,account.check_interval))
+                       EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm[NOTI_ACCOUNT_ADD] : start auto poll failed >>> ");
+       }
+#endif
+
+       /* add account details to contact DB */
+       emdaemon_insert_accountinfo_to_contact(&account);
+
+       local_result = 1;
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       EM_DEBUG_LOG("[3] APPID[%d], APIID [%d]", emipc_get_app_id(a_hAPI), emipc_get_api_id(a_hAPI));
+       EM_DEBUG_LOG("account id[%d]", account.account_id);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &(account.account_id), sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       /* pass result to app */
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+FINISH_OFF:
+       if ( local_result == 0 ) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed : local_result ");
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed : err");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_delete_account(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int account_id = 0;
+       int local_result = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       /* account_id */
+       account_id = *((int*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0));
+       if(!emdaemon_delete_account(account_id, &err)) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+                       EM_DEBUG_LOG("emipc_add_parameter failed ");
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+               goto FINISH_OFF;
+       }
+
+#ifdef __FEATURE_AUTO_POLLING__
+       /* stop auto polling for this acount */
+       if(emdaemon_check_auto_polling_started(account_id)) {
+               if(!emdaemon_remove_polling_alarm(account_id))
+                       EM_DEBUG_EXCEPTION("emdaemon_remove_polling_alarm[ NOTI_ACCOUNT_DELETE] : remove auto poll failed >>> ");
+       }
+#endif
+       local_result = 1;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+FINISH_OFF:
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_update_account(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int account_id = 0, buffer_size = 0, local_result = 0, with_validation = 0;
+       char* local_account_stream = NULL;
+       email_account_t new_account_info = {0};
+       email_account_t old_account_info = {0};
+       int err = EMAIL_ERROR_NONE;
+       int handle = 0;
+
+       account_id = *((int*)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0));
+
+       /* get account structure from stream */
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 1);
+       EM_DEBUG_LOG("size [%d]", buffer_size);
+       local_account_stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 1);
+       em_convert_byte_stream_to_account(local_account_stream, buffer_size, &new_account_info);
+
+       /*get validation flag */
+       with_validation = *((int*)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 2));
+
+
+       if(!emdaemon_get_account(account_id, EMAIL_ACC_GET_OPT_FULL_DATA, &old_account_info, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_get_account failed ");
+               goto FINISH_OFF;
+       }
+
+
+       if( EM_SAFE_STRLEN (new_account_info.incoming_server_password) == 0 ) {
+               EM_SAFE_FREE(new_account_info.incoming_server_password); /* be allocated but has zero length */
+               EM_DEBUG_LOG("old_account_info->incoming_server_password [%s]", old_account_info.incoming_server_password);
+               new_account_info.incoming_server_password = EM_SAFE_STRDUP(old_account_info.incoming_server_password);
+               if(new_account_info.incoming_server_password == NULL) {
+                               EM_DEBUG_EXCEPTION("allocation for new_account_info->password failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+               }
+
+
+       if( EM_SAFE_STRLEN (new_account_info.outgoing_server_password) == 0 ) {
+               EM_SAFE_FREE(new_account_info.outgoing_server_password);
+               if(old_account_info.outgoing_server_password) {
+                       new_account_info.outgoing_server_password = strdup (old_account_info.outgoing_server_password);
+                       if(new_account_info.outgoing_server_password == NULL) {
+                               EM_DEBUG_EXCEPTION("allocation for new_account_info->outgoing_server_password failed");
+                               err = EMAIL_ERROR_OUT_OF_MEMORY;
+                               goto FINISH_OFF;
+                       }
+               }
+       }
+
+       if(with_validation) {
+               emdaemon_validate_account_and_update(account_id, &new_account_info, &handle, &err);
+               local_result = 1;
+       }
+       else {
+               if(emdaemon_update_account(account_id, &new_account_info, &err)) {
+                       emdaemon_update_accountinfo_to_contact(&old_account_info, &new_account_info);
+                       local_result = 1;
+               }
+               else {
+                       EM_DEBUG_EXCEPTION("emdaemon_update_account failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter for result failed");
+
+       if(with_validation) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter for handle failed");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+FINISH_OFF:
+       if ( local_result == 0 ) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+       }
+
+       emcore_free_account(&old_account_info);
+
+       emcore_free_account(&new_account_info);
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_validate_account(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int account_id = 0;
+       int local_result = 0;
+       int err_code = 0;
+       int handle = 0;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       local_result = emdaemon_validate_account(account_id, &handle,&err_code);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+               EM_DEBUG_LOG("emipc_add_parameter failed ");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err_code, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+void stb_get_account_list(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int local_result = 0;
+       int i= 0;
+       char* local_stream = NULL;
+       email_account_t* account_list;
+       int count;
+       int size = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       if(emdaemon_get_account_list(&account_list, &count, &err)) {
+               EM_DEBUG_LOG("emdaemon_get_account_list success");
+               local_result = 1;
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+
+               EM_DEBUG_LOG("Count [%d]", count);
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &count, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter count failed ");
+
+               for(i=0; i<count; i++) {
+                       EM_DEBUG_LOG("Name - %s", account_list[i].account_name);
+
+                       local_stream = em_convert_account_to_byte_stream(account_list+i, &size);
+
+                       if (!local_stream) {
+                               EM_DEBUG_EXCEPTION ("INVALID PARAM: local_stream NULL ");
+                               emcore_free_account_list(&account_list, count, NULL);
+                               return;
+                       }
+
+                       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, local_stream, size))
+                               EM_DEBUG_EXCEPTION("Add  Param mailbox failed  ");
+
+                       size = 0;
+                       EM_SAFE_FREE(local_stream);
+               }
+
+               emcore_free_account_list(&account_list, count, NULL);
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+
+       else {
+               EM_DEBUG_LOG("emdaemon_get_account_list failed");
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed : err");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+
+       EM_SAFE_FREE(local_stream);
+       EM_DEBUG_FUNC_END();
+}
+
+/* sowmya.kr, 10-May-2010, changes for API improvement */
+void stb_sync_header(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int handle = -1;
+       int account_id = 0, maibox_id = 0;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       /* maibox_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &maibox_id);
+       EM_DEBUG_LOG("maibox_id [%d]", maibox_id);
+
+       if(emdaemon_sync_header(account_id, maibox_id, &handle, &err)) {
+               EM_DEBUG_LOG("emdaemon_sync_header success ");
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_download_body(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int mail_id = 0;
+       int attachment_count = 0;
+       int handle = 0;
+       int account_id = 0;
+
+       /* Account Id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+
+       /* Mail Id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &mail_id);
+
+       /* Has Attachment */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &attachment_count);
+
+       /*Download Body */
+       if (!emdaemon_download_body(account_id, mail_id, 1, attachment_count, &handle, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_download_body - failed");
+               goto FINISH_OFF;
+       }
+
+       err = EMAIL_ERROR_NONE;
+
+FINISH_OFF:
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+       EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+void stb_create_mailbox(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int                 buffer_size                         = 0;
+       int                 err = EMAIL_ERROR_NONE;
+       char               *local_stream  = NULL;
+       int                 on_server           = 0;
+       email_mailbox_t mailbox = {0};
+       int             handle = 0; /* Added for cancelling mailbox creating  */
+
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       EM_DEBUG_LOG("size [%d]", buffer_size);
+
+       if(buffer_size <= 0) {
+               EM_DEBUG_EXCEPTION("buffer_size(%d) should be greater than 0", buffer_size);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       local_stream = emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0);
+       em_convert_byte_stream_to_mailbox(local_stream, buffer_size, &mailbox);
+       EM_DEBUG_LOG("Mailbox name - %s", mailbox.mailbox_name);
+
+       on_server = *((int*)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 1));
+
+       emdaemon_add_mailbox(&mailbox, on_server, &handle, &err);
+
+FINISH_OFF:
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 1");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 2");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &mailbox.mailbox_id, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 3");
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+               return;
+       }
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+void stb_delete_mailbox(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int              err = EMAIL_ERROR_NONE;
+       int      on_server              = 0;
+       int      handle = 0; /* Added for cancelling mailbox deleting */
+       int      input_mailbox_id = 0;
+
+       /* src_mailbox_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &input_mailbox_id);
+       EM_DEBUG_LOG("input_mailbox_id [%d]", input_mailbox_id);
+
+       if (input_mailbox_id > 0)
+               EM_DEBUG_LOG("input_mailbox_id [%d]", input_mailbox_id);
+       else
+               EM_DEBUG_LOG("input_mailbox_id == 0");
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &on_server);
+
+       if(emdaemon_delete_mailbox(input_mailbox_id, on_server, &handle, &err))
+               err = EMAIL_ERROR_NONE;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_set_mailbox_type(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int     err = EMAIL_ERROR_NONE;
+       int mailbox_id = 0;
+       int mailbox_type = 0;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mailbox_id);
+       EM_DEBUG_LOG("mailbox_id[%d]", mailbox_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &mailbox_type);
+       EM_DEBUG_LOG("mailbox_type[%d]", mailbox_type);
+
+       if( (err = emdaemon_set_mailbox_type(mailbox_id, mailbox_type)) != EMAIL_ERROR_NONE)
+               err = EMAIL_ERROR_NONE;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 1");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_set_local_mailbox(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int     err = EMAIL_ERROR_NONE;
+       int mailbox_id = 0;
+       int is_local_mailbox = 0;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mailbox_id);
+       EM_DEBUG_LOG("mailbox_id[%d]", mailbox_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &is_local_mailbox);
+       EM_DEBUG_LOG("is_local_mailbox[%d]", is_local_mailbox);
+
+       if( (err = emdaemon_set_local_mailbox(mailbox_id, is_local_mailbox)) != EMAIL_ERROR_NONE)
+               err = EMAIL_ERROR_NONE;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 1");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_set_mail_slot_size_of_mailbox(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int     err    = EMAIL_ERROR_NONE;
+       int handle = 0;
+       int account_id = 0;
+       int mailbox_id = 0;
+       int mail_slot_size = 0;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id[%d]", account_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &mailbox_id);
+       EM_DEBUG_LOG("mail_slot_size[%d]", mail_slot_size);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &mail_slot_size);
+       EM_DEBUG_LOG("mail_slot_size[%d]", mail_slot_size);
+
+       if(emdaemon_set_mail_slot_size_of_mailbox(account_id, mailbox_id, mail_slot_size, &handle, &err))
+               err = EMAIL_ERROR_NONE;
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 1");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 2");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_rename_mailbox(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int buffer_size  = 0;
+       int     err = EMAIL_ERROR_NONE;
+       int handle = 0;
+       int mailbox_id = 0;
+       int on_server = 0;
+       char *mailbox_path = NULL;
+       char *mailbox_alias = NULL;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mailbox_id);
+       EM_DEBUG_LOG("mailbox_id[%d]", mailbox_id);
+
+       buffer_size = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 1);
+       EM_DEBUG_LOG("mailbox_path string size[%d]", buffer_size);
+       if(buffer_size > 0)       {
+               mailbox_path = (char*)em_malloc(buffer_size);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, buffer_size, mailbox_path);
+               EM_DEBUG_LOG("mailbox_path [%s]", mailbox_path);
+       }
+
+       buffer_size = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 2);
+       EM_DEBUG_LOG("mailbox_alias string size[%d]", buffer_size);
+       if(buffer_size > 0)       {
+               mailbox_alias = (char*)em_malloc(buffer_size);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, buffer_size, mailbox_alias);
+               EM_DEBUG_LOG("mailbox_alias [%s]", mailbox_alias);
+       }
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 3, sizeof(int), &on_server);
+       EM_DEBUG_LOG("on_server[%d]", on_server);
+
+       if ((err = emdaemon_rename_mailbox(mailbox_id, mailbox_path, mailbox_alias, on_server, &handle)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emdaemon_rename_mailbox failed [%d]", err);
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 1");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed 2");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_SAFE_FREE(mailbox_alias);
+       EM_SAFE_FREE(mailbox_path);
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_send_mail(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       char* local_stream = NULL;
+       int mail_id;
+       int handle;
+       int err = EMAIL_ERROR_NONE;
+
+       /* Mail_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mail_id);
+       EM_DEBUG_LOG("mail_id [%d]", mail_id);
+
+       if(emdaemon_send_mail(mail_id, &handle, &err)) {
+               err = EMAIL_ERROR_NONE;
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+       else {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+
+       EM_SAFE_FREE(local_stream);
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+/* obsolete - there is no api calling this function */
+void stb_get_mailbox_list(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int counter = 0;
+       char* local_stream = NULL;
+       int account_id;
+       email_mailbox_t* mailbox_list = NULL;
+       int count = 0;
+       int size = 0;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+
+       if(emdaemon_get_mailbox_list(account_id, &mailbox_list, &count, &err))
+               EM_DEBUG_LOG("emdaemon_get_mailbox_list - success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if(EMAIL_ERROR_NONE == err) {
+               EM_DEBUG_LOG("Count [%d]", count);
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &count, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+               for(counter=0; counter<count; counter++) {
+                       EM_DEBUG_LOG("Name - %s", mailbox_list[counter].mailbox_name);
+
+                       local_stream = em_convert_mailbox_to_byte_stream(mailbox_list+counter, &size);
+
+                       if (!local_stream) {
+                               EM_DEBUG_EXCEPTION ("INVALID PARAM: local_stream NULL ");
+                               emcore_free_mailbox_list(&mailbox_list, count);
+                               return;
+                       }
+
+                       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, local_stream, size))
+                               EM_DEBUG_EXCEPTION("Add  Param mailbox failed  ");
+
+                       EM_SAFE_FREE(local_stream);
+                       size = 0;
+               }
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       emcore_free_mailbox_list(&mailbox_list, count);
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_delete_all_mails(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int mailbox_id = 0;
+       int from_server = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       /* mailbox_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mailbox_id);
+
+       /* from_server */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &from_server);
+
+       emdaemon_delete_mail_all(mailbox_id, from_server, NULL, &err);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_delete_mail(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int mailbox_id = 0;
+       int from_server = 0;
+       int counter = 0;
+       int num;
+       int *mail_ids = NULL;
+
+       /* Mailbox */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mailbox_id);
+
+       EM_DEBUG_LOG("mailbox_id [%d]", mailbox_id);
+
+       /* Number of mail_ids */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &num);
+       EM_DEBUG_LOG("number of mails [%d]", num);
+
+       if (num > 0) {
+               mail_ids = em_malloc(sizeof(int) * num);
+               if (!mail_ids) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+       }
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, num * sizeof(int), mail_ids);
+
+       for(counter = 0; counter < num; counter++)
+               EM_DEBUG_LOG("mail_ids [%d]", mail_ids[counter]);
+
+       /* from_server */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 3, sizeof(int), &from_server);
+       EM_DEBUG_LOG("from_server [%d]", from_server);
+
+       emdaemon_delete_mail(mailbox_id, mail_ids, num, from_server, NULL, &err);
+
+FINISH_OFF:
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       EM_SAFE_FREE(mail_ids);
+
+       EM_DEBUG_FUNC_END();
+}
+void stb_clear_mail_data (HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+
+       if(emdaemon_clear_all_mail_data(&err)) {
+               EM_DEBUG_LOG(">>> stb_clear_mail_data Success [ %d]  >> ", err);
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed : err");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_add_rule(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int buffer_size = 0;
+       int err = EMAIL_ERROR_NONE;
+       char* local_rule_stream = NULL;
+       email_rule_t rule = { 0 };
+
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       if(buffer_size <= 0) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       local_rule_stream = (char*)     emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0);
+       if(!local_rule_stream) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       em_convert_byte_stream_to_rule(local_rule_stream, buffer_size, &rule);
+       EM_DEBUG_LOG("account ID  [%d]", rule.account_id);
+
+       /* call add_filter handler */
+       err = emdaemon_add_filter(&rule);
+
+FINISH_OFF:
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       emcore_free_rule(&rule);
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+/* obsolete - there is no api calling this function */
+void stb_get_rule(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int filter_id = 0;
+       email_rule_t* rule = NULL;
+       int size =0;
+       char* local_rule_stream = NULL;
+
+       filter_id = *((int*)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0));
+
+       emdaemon_get_filter(filter_id, &rule, &err);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       /* insert a rule if there exists a rule */
+       if ( rule ) {
+               local_rule_stream = em_convert_rule_to_byte_stream(rule, &size);
+               if(!local_rule_stream) { /*prevent 26265*/
+                       EM_DEBUG_EXCEPTION("em_convert_rule_to_byte_stream failed");
+                       emcore_free_rule(rule);
+                       EM_SAFE_FREE(rule);
+                       return;
+               }
+
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, local_rule_stream, size))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+
+               EM_SAFE_FREE(local_rule_stream);
+               emcore_free_rule(rule);
+               EM_SAFE_FREE(rule);
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+               return;
+       }
+
+       EM_DEBUG_FUNC_END();
+}
+
+/* obsolete - there is no api calling this function */
+void stb_get_rule_list(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+       char* local_stream = NULL;
+       int count = 0;
+       int size = 0;
+       email_rule_t* filtering_list = NULL;
+
+       emdaemon_get_filter_list(&filtering_list, &count, &err);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       /* insert rules if there exist rules*/
+       if( count > 0 ) {
+               EM_DEBUG_LOG("num of rules [%d]", count);
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &count, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+               for(i=0; i<count; i++) {
+                       EM_DEBUG_LOG("Value - %s", filtering_list[i].value);
+
+                       local_stream = em_convert_rule_to_byte_stream(filtering_list+i, &size);
+
+                       if(!local_stream) break;
+
+                       if(!emipc_add_dynamic_parameter(a_hAPI, ePARAMETER_OUT, local_stream, size))
+                               EM_DEBUG_EXCEPTION("emipc_add_dynamic_parameter failed  ");
+
+                       size = 0;
+               }
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+
+       EM_DEBUG_FUNC_END();
+}
+
+/* obsolete - there is no api calling this function */
+void stb_find_rule(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int buffer_size = 0;
+       int err = EMAIL_ERROR_NONE;
+       char* local_rule_stream = NULL;
+       email_rule_t rule = { 0 };
+
+
+       buffer_size = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+
+       if(buffer_size > 0)      {
+               local_rule_stream = (char*)em_malloc(buffer_size);
+               EM_NULL_CHECK_FOR_VOID(local_rule_stream);
+               if(local_rule_stream) {
+                       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, buffer_size, local_rule_stream);
+                       em_convert_byte_stream_to_rule(local_rule_stream, buffer_size, &rule);
+                       EM_SAFE_FREE(local_rule_stream);
+                       EM_DEBUG_LOG("account ID  [%d]", rule.account_id);
+
+                       if(emdaemon_find_filter(&rule, &err))
+                               err = EMAIL_ERROR_NONE;
+
+                       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+                       if (!emipc_execute_stub_api(a_hAPI))
+                               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+               }
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_update_rule(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int filter_id = 0;
+       int buffer_size = 0;
+       int err = EMAIL_ERROR_NONE;
+       char* rule_stream = NULL;
+       email_rule_t rule = {0};
+
+
+       /* get filter_id */
+       filter_id = *((int*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0));
+
+       /* get rule */
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 1);
+       EM_DEBUG_LOG("size [%d]", buffer_size);
+       if(buffer_size <= 0)  {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       rule_stream     = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 1);
+       if(!rule_stream) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+       em_convert_byte_stream_to_rule(rule_stream, buffer_size, &rule);
+
+       /* call update handler */
+       emdaemon_update_filter(filter_id, &rule, &err);
+
+FINISH_OFF:
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       emcore_free_rule(&rule);
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_move_all_mails(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int src_mailbox_id = 0, dst_mailbox_id = 0;
+
+       /* src_mailbox_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &src_mailbox_id);
+       EM_DEBUG_LOG("src_mailbox_id [%d]", src_mailbox_id);
+
+       if (src_mailbox_id > 0)
+               EM_DEBUG_LOG("src_mailbox_id [%d]", src_mailbox_id);
+       else
+               EM_DEBUG_LOG("src_mailbox_id == 0");
+
+       /* dst_mailbox_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &dst_mailbox_id);
+       EM_DEBUG_LOG("dst_mailbox_id [%d]", dst_mailbox_id);
+
+       if (dst_mailbox_id > 0)
+               EM_DEBUG_LOG("dst_mailbox_id [%d]", dst_mailbox_id);
+       else
+               EM_DEBUG_LOG("dst_mailbox_id == 0");
+
+       if(emdaemon_move_mail_all_mails(src_mailbox_id, dst_mailbox_id, &err))
+               EM_DEBUG_LOG("emdaemon_move_mail_all_mails:Success");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+               return;
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+               return;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_set_flags_field(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       email_flags_field_type field_type = 0;
+       int account_id;
+       int value = 0;
+       int onserver = 0;
+       int num = 0;
+       int counter = 0;
+       int *mail_ids = NULL;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       /* Number of mail_ids */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &num);
+       EM_DEBUG_LOG("number of mails [%d]", num);
+
+       /* mail_id */
+       mail_ids = em_malloc(sizeof(int) * num);
+
+       if(!mail_ids) {
+               EM_DEBUG_EXCEPTION("em_malloc failed ");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, num * sizeof(int), mail_ids);
+
+       for(counter=0; counter < num; counter++)
+               EM_DEBUG_LOG("mailids [%d]", mail_ids[counter]);
+
+       /* field type */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 3, sizeof(int), &field_type);
+       EM_DEBUG_LOG("field_type [%d]", field_type);
+
+       /* value */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 4, sizeof(int), &value);
+       EM_DEBUG_LOG("value [%d]", value);
+
+       /*  on server */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 5, sizeof(int), &onserver);
+       EM_DEBUG_LOG("onserver [%d]", onserver);
+
+       if(emdaemon_set_flags_field(account_id, mail_ids, num, field_type, value, onserver, &err))
+               EM_DEBUG_LOG("emdaemon_set_flags_field - success");
+
+FINISH_OFF:
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       if (mail_ids)
+               EM_SAFE_FREE(mail_ids);
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_add_mail(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int  buffer_size = 0;
+       int  local_result = 0;
+       int  result_attachment_data_count = 0;
+       int  param_index = 0;
+       int  sync_server = 0;
+       int  err = EMAIL_ERROR_NONE;
+       email_mail_data_t result_mail_data = {0};
+       email_attachment_data_t *result_attachment_data = NULL;
+       email_meeting_request_t result_meeting_request = {0};
+
+
+       /* email_mail_data_t */;
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+       EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
+
+       /* mail_data */
+       if(buffer_size > 0)      {
+               char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+               em_convert_byte_stream_to_mail_data(stream, buffer_size, &result_mail_data);
+       }
+
+       /* attachment */
+       if (result_mail_data.attachment_count > 0) {
+               buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+               EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
+
+               if(buffer_size > 0)      {
+                       char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
+                       em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
+
+                       EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+
+                       if(result_attachment_data_count && !result_attachment_data) {
+                               EM_DEBUG_EXCEPTION("em_convert_byte_stream_to_attachment_data failed");
+                               err = EMAIL_ERROR_ON_PARSING;
+                               goto FINISH_OFF;
+                       }
+               }
+
+               param_index++;
+       }
+
+
+       /* meeting request */
+       EM_DEBUG_LOG("email_meeting_request_t");
+       if ( result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_REQUEST
+               || result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_RESPONSE
+               || result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST) {
+               buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+
+               if(buffer_size > 0) {
+                       char* stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+                       em_convert_byte_stream_to_meeting_req(stream, buffer_size, &result_meeting_request);
+               }
+       }
+
+       EM_DEBUG_LOG("sync_server");
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, param_index++, sizeof(int), &sync_server);
+
+       if( (err = emdaemon_add_mail(&result_mail_data, result_attachment_data, result_attachment_data_count, &result_meeting_request, sync_server)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emdaemon_add_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       local_result = 1;
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &result_mail_data.mail_id, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &result_mail_data.thread_id, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+FINISH_OFF:
+       if ( local_result == 0 ) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+       }
+
+       emcore_free_mail_data(&result_mail_data);
+
+       if(result_attachment_data)
+               emcore_free_attachment_data(&result_attachment_data, result_attachment_data_count, NULL);
+
+       emstorage_free_meeting_request(&result_meeting_request);
+
+       em_flush_memory();
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+void stb_update_mail(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int  buffer_size = 0;
+       int  local_result = 0;
+       int  result_attachment_data_count = 0;
+       int  param_index = 0;
+       int  sync_server = 0;
+       int  *temp_buffer = NULL;
+       int  err = EMAIL_ERROR_NONE;
+       email_mail_data_t result_mail_data = {0};
+       email_attachment_data_t *result_attachment_data = NULL;
+       email_meeting_request_t result_meeting_request = {0};
+
+       EM_DEBUG_LOG("email_mail_data_t");
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+
+       if(buffer_size > 0)      {
+               char* stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+               em_convert_byte_stream_to_mail_data(stream, buffer_size, &result_mail_data);
+       }
+
+       if (result_mail_data.attachment_count > 0) {
+               buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+               EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
+
+               if(buffer_size > 0) {
+                       char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
+                       em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
+
+                       EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+
+                       if(result_attachment_data_count && !result_attachment_data) {
+                               EM_DEBUG_EXCEPTION("em_convert_byte_stream_to_attachment_data failed");
+                               err = EMAIL_ERROR_ON_PARSING;
+                               goto FINISH_OFF;
+                       }
+               }
+               param_index++;
+       }
+
+       EM_DEBUG_LOG("email_meeting_request_t");
+
+       if ( result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_REQUEST
+               || result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_RESPONSE
+               || result_mail_data.meeting_request_status == EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST) {
+               buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+
+               if(buffer_size > 0) {
+                       char* stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+                       em_convert_byte_stream_to_meeting_req(stream, buffer_size, &result_meeting_request);
+               }
+       }
+
+       EM_DEBUG_LOG("sync_server");
+
+       temp_buffer = emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+
+       if(!temp_buffer) {
+               EM_DEBUG_EXCEPTION("emipc_get_nth_parameter_data[%d] failed", param_index - 1);
+               err = EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       sync_server = *temp_buffer;
+
+       if( (err = emdaemon_update_mail(&result_mail_data, result_attachment_data,
+                       result_attachment_data_count, &result_meeting_request, sync_server)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emdaemon_update_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       local_result = 1;
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &result_mail_data.mail_id, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &result_mail_data.thread_id, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+FINISH_OFF:
+       if ( local_result == 0 ) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+       }
+
+       emcore_free_mail_data(&result_mail_data);
+
+       if(result_attachment_data)
+               emcore_free_attachment_data(&result_attachment_data, result_attachment_data_count, NULL);
+
+       emstorage_free_meeting_request(&result_meeting_request);
+
+       em_flush_memory();
+       EM_DEBUG_FUNC_END();
+}
+
+
+void stb_move_thread_to_mailbox(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int mailbox_id = 0, thread_id = 0, move_always_flag = 0;
+       int err = EMAIL_ERROR_NONE;
+       char *target_mailbox_name = NULL;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &thread_id);
+       EM_DEBUG_LOG("thread_id [%d]", thread_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &mailbox_id);
+       EM_DEBUG_LOG("mailbox_id [%d]", mailbox_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &move_always_flag);
+       EM_DEBUG_LOG("move_always_flag [%d]", move_always_flag);
+
+       if(emdaemon_move_mail_thread_to_mailbox(thread_id, mailbox_id, move_always_flag, &err))
+               EM_DEBUG_LOG("emdaemon_move_mail_thread_to_mailbox success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter fail");
+               EM_SAFE_FREE(target_mailbox_name);
+               return;
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api fail");
+               EM_SAFE_FREE(target_mailbox_name);
+               return;
+       }
+
+       EM_SAFE_FREE(target_mailbox_name);
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_delete_thread(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int thread_id = 0, delete_always_flag = 0;
+       int handle = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &thread_id);
+       EM_DEBUG_LOG("thread_id [%d]", thread_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &delete_always_flag);
+       EM_DEBUG_LOG("delete_always_flag [%d]", delete_always_flag);
+
+       if(emdaemon_delete_mail_thread(thread_id, delete_always_flag, &handle, &err))
+               EM_DEBUG_LOG("emdaemon_delete_mail_thread success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter fail");
+               return;
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api fail");
+               return;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_modify_seen_flag_of_thread(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int thread_id = 0, seen_flag = 0, on_server = 0;
+       int handle = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &thread_id);
+       EM_DEBUG_LOG("thread_id [%d]", thread_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &seen_flag);
+       EM_DEBUG_LOG("seen_flag [%d]", seen_flag);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &on_server);
+       EM_DEBUG_LOG("on_server [%d]", on_server);
+
+       if(emdaemon_modify_seen_flag_of_thread(thread_id, seen_flag, on_server, &handle, &err))
+               EM_DEBUG_LOG("emdaemon_modify_seen_flag_of_thread success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter fail");
+               return;
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api fail");
+               return;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_expunge_mails_deleted_flagged(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int mailbox_id = 0, on_server = 0;
+       int handle = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), (void*)&mailbox_id);
+       EM_DEBUG_LOG("mailbox_id [%d]", mailbox_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), (void*)&on_server);
+       EM_DEBUG_LOG("on_server [%d]", on_server);
+
+       if( (err = emdaemon_expunge_mails_deleted_flagged(mailbox_id, on_server, &handle)) != EMAIL_ERROR_NONE)
+               EM_DEBUG_LOG("emdaemon_expunge_mails_deleted_flagged success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int))) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter fail");
+               return;
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int))) {
+               EM_DEBUG_LOG("ipcAPI_AddParameter local_result failed ");
+               return;
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api fail");
+               return;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_update_mail_attribute(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int mail_id_count = 0, counter = 0;
+       email_mail_attribute_type attribute;
+       /* email_mail_attribute_value_t value; */
+
+       /* mail_id_count */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mail_id_count);
+       EM_DEBUG_LOG("mail_id_count [%d]", mail_id_count);
+
+       /* mail_id_array */
+       int mail_id_array[mail_id_count];
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, mail_id_count * sizeof(int), mail_id_array);
+
+       for(counter = 0; counter < mail_id_count; counter++)
+               EM_DEBUG_LOG("mail_id[%d] [%d]", counter, mail_id_array[counter]);
+
+       /* attribute */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &attribute);
+       EM_DEBUG_LOG("attribute [%d]", attribute);
+
+       /* value */
+       /*
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 3, sizeof(int), &value);
+       EM_DEBUG_LOG("target_mailbox_id [%d]", mailbox_id);
+       */
+
+       /*
+       if(emdaemon_move_mail(mail_ids, num, mailbox_id, EMAIL_MOVED_BY_COMMAND, 0, &err))
+               EM_DEBUG_LOG("emdaemon_move_mail success");
+       */
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter fail");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api fail");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_move_mail(HIPC_API a_hAPI)
+{
+       int err = EMAIL_ERROR_NONE;
+       int num = 0, counter = 0, mailbox_id = 0;
+
+       /* Number of mail_ids */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &num);
+       EM_DEBUG_LOG("number of mails [%d]", num);
+
+       /* mail_id */
+       int mail_ids[num];
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, num * sizeof(int), mail_ids);
+
+       for(counter = 0; counter < num; counter++)
+               EM_DEBUG_LOG("mailids [%d]", mail_ids[counter]);
+
+       /* target_mailbox_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &mailbox_id);
+       EM_DEBUG_LOG("target_mailbox_id [%d]", mailbox_id);
+
+       if (mailbox_id > 0)
+               EM_DEBUG_LOG("mailbox_id [%d]", mailbox_id);
+       else
+               EM_DEBUG_LOG("mailbox_id == 0");
+
+       if(emdaemon_move_mail(mail_ids, num, mailbox_id, EMAIL_MOVED_BY_COMMAND, 0, &err))
+               EM_DEBUG_LOG("emdaemon_move_mail success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter fail");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api fail");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_delete_rule(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int filter_id = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       /* filter_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &filter_id);
+
+       if(emdaemon_delete_filter(filter_id, &err))
+               err = EMAIL_ERROR_NONE;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_add_attachment(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int buffer_size = 0;
+       int err = EMAIL_ERROR_NONE;
+       int mail_id = -1;
+       int attachment_count = 0;
+       char* attachment_stream = NULL;
+       email_attachment_data_t* attachment = NULL;
+
+       /* mail_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mail_id);
+
+       /* attachment */
+       buffer_size = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 1);
+
+       if(buffer_size > 0)      {
+               attachment_stream = (char*)em_malloc(buffer_size);
+               EM_NULL_CHECK_FOR_VOID(attachment_stream);
+               if(attachment_stream) {
+                       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, buffer_size, attachment_stream);
+                       em_convert_byte_stream_to_attachment_data(attachment_stream, buffer_size, &attachment, &attachment_count);
+                       EM_SAFE_FREE(attachment_stream);
+               }
+       }
+
+       if (!attachment) {
+               EM_DEBUG_EXCEPTION("em_convert_byte_stream_to_attachment_data failed  ");
+               return;
+       }
+
+       emdaemon_add_attachment(mail_id, attachment, &err);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+       if(EMAIL_ERROR_NONE == err) {
+               EM_DEBUG_LOG("emdaemon_add_attachment -Success");
+
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &(attachment->attachment_id), sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter attachment_id failed ");
+       }
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_SAFE_FREE(attachment);
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_get_attachment(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int attachment_id;
+       char* attachment_stream = NULL;
+       email_attachment_data_t* attachment = NULL;
+       int size = 0;
+
+       /* attachment_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &attachment_id);
+
+       emdaemon_get_attachment(attachment_id, &attachment, &err);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+
+       if(EMAIL_ERROR_NONE == err) {
+               EM_DEBUG_LOG("emdaemon_get_attachment - Success");
+               /* attachment */
+               attachment_stream = em_convert_attachment_data_to_byte_stream(attachment, 1, &size);
+               if(!attachment_stream) { /*prevent 26263*/
+                       emcore_free_attachment_data(&attachment, 1, &err);
+                       return;
+               }
+               EM_NULL_CHECK_FOR_VOID(attachment_stream);
+
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, attachment_stream, size))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed  ");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+
+       EM_SAFE_FREE(attachment_stream);
+       emcore_free_attachment_data(&attachment, 1, &err);
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_get_imap_mailbox_list(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int account_id = 0;
+       int handle = 0;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+
+       if(emdaemon_get_imap_mailbox_list(account_id, "", &handle, &err))
+               err = EMAIL_ERROR_NONE;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_LOG("ipcAPI_AddParameter local_result failed ");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_LOG("ipcAPI_AddParameter local_result failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_LOG("emipc_execute_stub_api failed  ");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_delete_attachment(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int attachment_id = 0;
+
+       /* attachment_index */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &attachment_id);
+
+       emdaemon_delete_mail_attachment(attachment_id, &err);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_download_attachment(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+       int mail_id = 0;
+       int nth = 0;
+       int handle = 0;
+       int account_id = 0;
+
+       EM_DEBUG_LOG("account_id");
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+
+       EM_DEBUG_LOG("mail_id");
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &mail_id);
+
+       EM_DEBUG_LOG("nth");
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &nth);
+
+       if(emdaemon_download_attachment(account_id, mail_id, nth, &handle, &err)) {
+               err = EMAIL_ERROR_NONE;
+
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+               EM_DEBUG_LOG(">>>>>>>>>> HANDLE = %d", handle);
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter handle failed ");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+       else {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+               /* Download handle - 17-Apr-09 */
+               EM_DEBUG_LOG(">>>>>>>>>> HANDLE = %d", handle);
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter handle failed ");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_mail_send_saved(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int account_id = 0;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+
+       EM_DEBUG_LOG("calling emdaemon_send_mail_saved");
+       if(emdaemon_send_mail_saved(account_id, NULL, &err))
+               err = EMAIL_ERROR_NONE;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_add_read_receipt(HIPC_API a_hAPI){
+       EM_DEBUG_FUNC_BEGIN();
+       int read_mail_id = 0;
+       int receipt_mail_id = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       /* read_mail_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &read_mail_id);
+       EM_DEBUG_LOG("read_mail_id [%d]", read_mail_id);
+
+       if( (err = emcore_add_read_receipt(read_mail_id, &receipt_mail_id)) != EMAIL_ERROR_NONE )
+               EM_DEBUG_EXCEPTION("emcore_add_read_receipt failed [%d]", err);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if (err == EMAIL_ERROR_NONE) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &receipt_mail_id, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+}
+
+void stb_retry_sending_mail(HIPC_API a_hAPI)
+{
+
+       EM_DEBUG_FUNC_BEGIN();
+       int mail_id = 0;
+       int timeout_in_sec = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       /* Mail_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mail_id);
+       EM_DEBUG_LOG("mail_id [%d]", mail_id);
+
+       /* timeout_in_sec */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &timeout_in_sec);
+       EM_DEBUG_LOG("timeout_in_sec [%d]", timeout_in_sec);
+
+       if(emdaemon_send_mail_retry(mail_id, timeout_in_sec,&err))
+               EM_DEBUG_LOG("emdaemon_get_mailbox_list - success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_get_event_queue_status(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int on_sending = 0;
+       int on_receiving = 0;
+
+       /*get the network status */
+       emdaemon_get_event_queue_status(&on_sending, &on_receiving);
+
+       /* on_sending */
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &on_sending, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       /* on_receving */
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &on_receiving, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       EM_DEBUG_LOG("stb_get_event_queue_status - Before Execute API");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_cancel_job(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int account_id = 0;
+       int handle = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &handle);
+       EM_DEBUG_LOG("handle [%d]", handle);
+
+       if(emdaemon_cancel_job(account_id, handle, &err))
+               err = EMAIL_ERROR_NONE;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_get_pending_job(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       email_action_t action = -1;
+       int account_id = 0;
+       int mail_id = -1;
+       int err = EMAIL_ERROR_NONE;
+       email_event_status_type_t status = 0;
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &action);
+       EM_DEBUG_LOG("action [%d]", action);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &mail_id);
+       EM_DEBUG_LOG("mail_id [%d]", mail_id);
+
+       if(emdaemon_get_pending_job(action, account_id, mail_id, &status))
+               err = EMAIL_ERROR_NONE;
+       else
+               err = EMAIL_ERROR_UNKNOWN;
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &status, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter status failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_print_receiving_event_queue_via_debug_msg(HIPC_API a_hAPI)
+{
+       email_event_t *event_queue = NULL;
+       int event_active_queue = 0, err, i;
+
+       emcore_get_receiving_event_queue(&event_queue, &event_active_queue, &err);
+
+       EM_DEBUG_LOG("======================================================================");
+       EM_DEBUG_LOG("Event active index [%d]", event_active_queue);
+       EM_DEBUG_LOG("======================================================================");
+       for(i = 1; i < 32; i++)
+               EM_DEBUG_LOG("event[%d] : type[%d], account_id[%d], arg[%d], status[%d]", i, event_queue[i].type, event_queue[i].account_id, event_queue[i].event_param_data_4, event_queue[i].status);
+       EM_DEBUG_LOG("======================================================================");
+       EM_DEBUG_LOG("======================================================================");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_cancel_send_mail_job(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int mail_id = 0;
+       int err = EMAIL_ERROR_NONE;
+       int account_id = 0;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       /* Mail_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &mail_id);
+       EM_DEBUG_LOG("mail_id [%d]", mail_id);
+
+       if(emdaemon_cancel_sending_mail_job(account_id,mail_id,&err))
+               EM_DEBUG_LOG("success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_search_mail_on_server(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int                    i = 0;
+       int                    err = EMAIL_ERROR_NONE;
+       int                    account_id = 0;
+       int                                        mailbox_id = 0;
+       int                    buffer_size = 0;
+       int                    search_filter_count = 0;
+       char                  *stream_for_search_filter_list = NULL;
+       unsigned int           job_handle = 0;
+       email_search_filter_t *search_filter_list = NULL;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       /* mailbox_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &mailbox_id);
+       EM_DEBUG_LOG("mailbox_id [%d]", mailbox_id);
+
+       /* search_filter_list */
+       buffer_size = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 2);
+
+       if(buffer_size > 0)      {
+               stream_for_search_filter_list = (char*)em_malloc(buffer_size);
+               EM_NULL_CHECK_FOR_VOID(stream_for_search_filter_list);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, buffer_size, stream_for_search_filter_list);
+               em_convert_byte_stream_to_search_filter(stream_for_search_filter_list, &search_filter_list, &search_filter_count);
+               EM_SAFE_FREE(stream_for_search_filter_list);
+       }
+
+       if(!emdaemon_search_mail_on_server(account_id ,mailbox_id, search_filter_list, search_filter_count, &job_handle, &err))
+               EM_DEBUG_LOG("success");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &job_handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       if(search_filter_list) {
+               for(i = 0; i < search_filter_count; i++) {
+                       switch(search_filter_list[i].search_filter_type) {
+                               case EMAIL_SEARCH_FILTER_TYPE_BCC              :
+                               case EMAIL_SEARCH_FILTER_TYPE_CC               :
+                               case EMAIL_SEARCH_FILTER_TYPE_FROM             :
+                               case EMAIL_SEARCH_FILTER_TYPE_KEYWORD          :
+                               case EMAIL_SEARCH_FILTER_TYPE_SUBJECT          :
+                               case EMAIL_SEARCH_FILTER_TYPE_TO               :
+                               case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       :
+                                       EM_SAFE_FREE(search_filter_list[i].search_filter_key_value.string_type_key_value);
+                                       break;
+                               default :
+                                       break;
+                       }
+               }
+       }
+
+       EM_SAFE_FREE(search_filter_list);
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_clear_result_of_search_mail_on_server(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int                      err = EMAIL_ERROR_NONE;
+       int                      account_id = 0;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       if (!emstorage_delete_mail_by_mailbox(account_id, EMAIL_SEARCH_RESULT_MAILBOX_NAME, true, &err)) 
+               EM_DEBUG_EXCEPTION(" emstorage_get_mailbox_by_mailbox_type failed [%d]", err);
+
+       if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       EM_DEBUG_FUNC_END();
+}
+
+
+
+void stb_add_account_with_validation(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int buffer_size = 0;
+       int local_result = 0;
+       int handle = 0;
+       char* stream = NULL;
+       email_account_t *account = NULL;
+       email_account_t *ref_account = NULL;
+       int ref_check_interval = 0;
+       int ref_account_id = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       /* get account info */
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       EM_DEBUG_LOG("size [%d]", buffer_size);
+       if(buffer_size <= 0) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       stream =(char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, 0);
+       if(!stream) {
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       account = em_malloc(sizeof(email_account_t));
+
+       if(account == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_OUT_OF_MEMORY");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       em_convert_byte_stream_to_account(stream, buffer_size, account);
+
+       if((err = emcore_add_account_to_unvalidated_account_list(account)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_add_account_to_unvalidated_account_list failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ref_account = emcore_get_account_reference(account->account_id);
+
+       if (!ref_account) {
+               EM_DEBUG_EXCEPTION("emcore_get_account_reference failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       ref_check_interval = ref_account->check_interval;
+       ref_account_id = ref_account->account_id;
+
+       if(!emdaemon_validate_account_and_create(ref_account, &handle, &err)) {
+               EM_DEBUG_EXCEPTION("emdaemon_validate_account_and_create fail [%d]", err);
+               goto FINISH_OFF;
+       }
+#ifdef __FEATURE_AUTO_POLLING__
+       /*  start auto polling, if check_interval not zero */
+       if(ref_check_interval > 0) {
+               if(!emdaemon_add_polling_alarm(ref_account_id, ref_check_interval))
+                       EM_DEBUG_EXCEPTION("emdaemon_add_polling_alarm[NOTI_ACCOUNT_ADD] : start auto poll failed >>> ");
+       }
+#endif /*  __FEATURE_AUTO_POLLING__ */
+       /*  add account details to contact DB  */
+       /*  emdaemon_insert_accountinfo_to_contact(account); */
+
+       local_result = 1;
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+FINISH_OFF:
+       if ( local_result == 0 ) { /* there is an error */
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed : local_result ");
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed : err");
+               if (!emipc_execute_stub_api(a_hAPI))
+                       EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       }
+
+/*     note: account is freed in thread_func_branch_command, which is run by other thread */
+/*     emcore_free_account(account); */
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_backup_account(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+#ifdef __FEATURE_BACKUP_ACCOUNT__
+       char *file_path = NULL;
+       int local_result = 0, err_code = 0, handle = 0, file_path_length = 0;
+
+       /* file_path_length */
+       file_path_length = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       if(file_path_length > 0) {
+               EM_DEBUG_LOG("file_path_length [%d]", file_path_length);
+               file_path = em_malloc(file_path_length);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, file_path_length, file_path);
+               EM_DEBUG_LOG("file_path [%s]", file_path);
+               local_result = emcore_backup_accounts((const char*)file_path, &err_code);
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+               EM_DEBUG_LOG("emipc_add_parameter failed ");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err_code, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_SAFE_FREE(file_path);
+#endif /*  __FEATURE_BACKUP_ACCOUNT__ */
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_restore_account(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+#ifdef __FEATURE_BACKUP_ACCOUNT__
+       char *file_path = NULL;
+       int local_result = 0, err_code = 0, handle = 0, file_path_length = 0;
+
+       /* file_path_length */
+       file_path_length = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       if(file_path_length > 0)  {
+               EM_DEBUG_LOG("file_path_length [%d]", file_path_length);
+               file_path = em_malloc(file_path_length);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, file_path_length, file_path);
+               EM_DEBUG_LOG("file_path [%s]", file_path);
+               local_result = emcore_restore_accounts((const char*)file_path, &err_code);
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+               EM_DEBUG_LOG("emipc_add_parameter failed ");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err_code, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &handle, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_SAFE_FREE(file_path);
+#endif /*  __FEATURE_BACKUP_ACCOUNT__ */
+       EM_DEBUG_FUNC_END();
+}
+
+
+void stb_get_password_length(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int account_id = 0;
+       int local_result = 0;
+       int err_code = 0;
+       int password_length = 0;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       local_result = emstorage_get_password_length_of_account(account_id, &password_length,&err_code);
+
+       EM_DEBUG_LOG("password_length [%d]", password_length);
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &local_result, sizeof(int)))
+               EM_DEBUG_LOG("emipc_add_parameter failed ");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err_code, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &password_length, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter result failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_add_certificate(HIPC_API a_hAPI)
+{
+       int err = EMAIL_ERROR_NONE;
+       int cert_file_len = 0;
+       int email_address_len = 0;
+       char *cert_file_path = NULL;
+       char *email_address = NULL;
+
+       cert_file_len = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       if (cert_file_len > 0) {
+               cert_file_path = em_malloc(cert_file_len + 1);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, cert_file_len, cert_file_path);
+       }
+
+       email_address_len = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 1);
+       if (email_address_len > 0) {
+               email_address = em_malloc(email_address_len + 1);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, email_address_len, email_address);
+       }
+
+       if (!emcore_add_public_certificate(cert_file_path, email_address, &err)) {
+               EM_DEBUG_EXCEPTION("em_core_smime_add_certificate failed");
+       }
+
+       if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+
+       if (EMAIL_ERROR_NONE == err) {
+               EM_DEBUG_LOG("email_mail_add_attachment -Success");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_SAFE_FREE(cert_file_path);          
+       EM_SAFE_FREE(email_address); 
+       EM_DEBUG_FUNC_END();    
+}
+
+void stb_delete_certificate(HIPC_API a_hAPI)
+{
+       int err = EMAIL_ERROR_NONE;
+       int email_address_len = 0;
+       char *email_address = NULL;
+       char temp_email_address[130] = {0, };
+
+       email_address_len = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       if (email_address_len > 0) {
+               EM_DEBUG_LOG("email address string length [%d]", email_address_len);
+               email_address = em_malloc(email_address_len + 1);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, email_address_len, email_address);
+               EM_DEBUG_LOG("email address [%s]", email_address);
+       }
+
+       SNPRINTF(temp_email_address, sizeof(temp_email_address), "<%s>", email_address);
+       if (!emcore_delete_public_certificate(temp_email_address, &err)) {
+               EM_DEBUG_EXCEPTION("em_core_smime_add_certificate failed");
+       }
+
+       if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+
+       if (EMAIL_ERROR_NONE == err) {
+               EM_DEBUG_LOG("email_mail_add_attachment -Success");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       
+       EM_SAFE_FREE(email_address);
+       EM_DEBUG_FUNC_END();    
+}
+
+void stb_verify_signature(HIPC_API a_hAPI)
+{
+       int err = EMAIL_ERROR_NONE;
+       int verify = 0;
+       int mail_id = 0;
+       int count = 0;
+       int attachment_tbl_count = 0;
+       email_mail_data_t *mail_data = NULL;
+       emstorage_attachment_tbl_t *attachment_tbl_list = NULL;
+
+       err = emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &mail_id);
+       if (err != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_get_parameter failed");
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_get_mail_data(mail_id, &mail_data)) {
+               EM_DEBUG_EXCEPTION("emcore_get_mail_data failed");
+               goto FINISH_OFF;
+       }
+
+       if ((err = emstorage_get_attachment_list(mail_id, true, &attachment_tbl_list, &attachment_tbl_count)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emstorage_get_attachment_list failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (attachment_tbl_count <= 0) {
+               EM_DEBUG_EXCEPTION("Invalid signed mail");
+               err = EMAIL_ERROR_INVALID_MAIL;
+               goto FINISH_OFF;
+       }
+
+       for (count = 0; count < attachment_tbl_count; count++) {
+               if (strcasestr(attachment_tbl_list[count].attachment_name, "p7s") == NULL)
+                       continue;
+
+               break;  
+       }
+
+       if (!emcore_verify_signature(attachment_tbl_list[count].attachment_path, mail_data->file_path_mime_entity, &verify, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_verify_signature failed");
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+
+       if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &verify, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+
+       if (verify) {
+               EM_DEBUG_LOG("Verify S/MIME signed mail-Success");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+
+       if (attachment_tbl_list)
+               emstorage_free_attachment(&attachment_tbl_list, attachment_tbl_count, NULL);
+
+       if (mail_data) {
+               emcore_free_mail_data(mail_data);
+               EM_SAFE_FREE(mail_data);
+       }
+
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_verify_certificate(HIPC_API a_hAPI)
+{
+       int err = EMAIL_ERROR_NONE;
+       int verify = 0;
+       int cert_file_len = 0;
+       char *cert_file_path = 0;
+
+       cert_file_len = emipc_get_parameter_length(a_hAPI, ePARAMETER_IN, 0);
+       if (cert_file_len > 0) {
+               cert_file_path = em_malloc(cert_file_len + 1);
+               emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, cert_file_len, cert_file_path);
+       }
+
+       if (!emcore_verify_certificate(cert_file_path, &verify, &err)) {
+               EM_DEBUG_EXCEPTION("em_core_smime_add_certificate failed");
+       }
+
+       if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &verify, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter local_result failed ");
+
+       if (verify) {
+               EM_DEBUG_LOG("Verify S/MIME signed mail-Success");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_SAFE_FREE(cert_file_path);           
+       EM_DEBUG_FUNC_END();    
+}
+
+void stb_ping_service(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");  
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_update_notification_bar_for_unread_mail(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE, account_id;
+
+       /* account_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &account_id);
+       EM_DEBUG_LOG("account_id [%d]", account_id);
+
+       if(!emcore_finalize_sync(account_id, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_finalize_sync failed [%d]", err);
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_show_user_message(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int err = EMAIL_ERROR_NONE;
+       int param_id = 0;
+       int param_error = 0;
+       email_action_t param_action = 0;
+
+       /* param_id */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 0, sizeof(int), &param_id);
+       EM_DEBUG_LOG("param_id [%d]", param_id);
+
+       /* param_action */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 1, sizeof(int), &param_action);
+       EM_DEBUG_LOG("param_action [%d]", param_action);
+
+       /* param_error */
+       emipc_get_parameter(a_hAPI, ePARAMETER_IN, 2, sizeof(int), &param_error);
+       EM_DEBUG_LOG("param_error [%d]", param_error);
+
+       if( (err = emcore_show_user_message(param_id, param_action, param_error)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_show_user_message failed [%d]", err);
+       }
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed ");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed  ");
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+}
+
+void stb_write_mime_file(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int i = 0;
+       int exist_file_path = 0;
+       int buffer_size = 0;
+       int local_result = 0;
+       int result_attachment_data_count = 0;
+       int param_index = 0;
+       int err = EMAIL_ERROR_NONE;
+       int ret = EMAIL_ERROR_NONE;
+       char *file_path = NULL;
+       char *output_file_path = NULL;
+       email_mail_data_t result_mail_data = {0};
+       email_attachment_data_t *result_attachment_data = NULL;
+       emstorage_mail_tbl_t *input_mail_tbl_data = NULL;
+       emstorage_attachment_tbl_t *input_attachment_tbl_data = NULL;
+       
+       /* email_mail_data_t */;
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+       EM_DEBUG_LOG("email_mail_data_t buffer_size[%d]", buffer_size);
+
+       /* mail_data */
+       if(buffer_size > 0)      {
+               char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+               em_convert_byte_stream_to_mail_data(stream, buffer_size, &result_mail_data);
+       }
+
+       /* attachment */
+       if (result_mail_data.attachment_count > 0) {
+               buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+               EM_DEBUG_LOG("email_attachment_data_t buffer_size[%d]", buffer_size);
+
+               if(buffer_size > 0) {
+                       char *stream = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
+                       em_convert_byte_stream_to_attachment_data(stream, buffer_size, &result_attachment_data, &result_attachment_data_count);
+
+                       EM_DEBUG_LOG("result_attachment_data_count[%d]", result_attachment_data_count);
+
+                       if(result_attachment_data_count && !result_attachment_data) {
+                               EM_DEBUG_EXCEPTION("em_convert_byte_stream_to_attachment_data failed");
+                               err = EMAIL_ERROR_ON_PARSING;
+                               goto FINISH_OFF;
+                       }
+               }
+
+               param_index++;
+       }
+
+       
+       buffer_size = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+       if (buffer_size > 0) {
+               output_file_path = (char *)emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index);
+               EM_DEBUG_LOG("output_file_path : [%s]", output_file_path);
+       }
+
+       /* Convert mail_data to mail_tbl */
+       if (!em_convert_mail_data_to_mail_tbl(&result_mail_data, 1, &input_mail_tbl_data, &err)) {
+               EM_DEBUG_EXCEPTION("em_convert_mail_data_to_mail_tbl failed");
+               goto FINISH_OFF;
+       }
+
+       /* Convert attachment_data to attachment_tbl */
+       if (result_attachment_data_count > 0) {
+               input_attachment_tbl_data = (emstorage_attachment_tbl_t *)em_malloc(sizeof(emstorage_attachment_tbl_t) * result_attachment_data_count);
+               if (input_attachment_tbl_data == NULL) {
+                       EM_DEBUG_EXCEPTION("em_malloc failed");
+                       err = EMAIL_ERROR_OUT_OF_MEMORY;
+                       goto FINISH_OFF;
+               }
+       }
+
+       for (i = 0; i < result_attachment_data_count ; i++) {
+               input_attachment_tbl_data[i].attachment_id = result_attachment_data[i].attachment_id;
+               input_attachment_tbl_data[i].attachment_name = EM_SAFE_STRDUP(result_attachment_data[i].attachment_name);
+               input_attachment_tbl_data[i].attachment_path = EM_SAFE_STRDUP(result_attachment_data[i].attachment_path);
+               input_attachment_tbl_data[i].attachment_size = result_attachment_data[i].attachment_size;
+               input_attachment_tbl_data[i].mail_id = result_attachment_data[i].mail_id;
+               input_attachment_tbl_data[i].account_id = result_attachment_data[i].account_id;
+               input_attachment_tbl_data[i].mailbox_id = result_attachment_data[i].mailbox_id;
+               input_attachment_tbl_data[i].attachment_save_status = result_attachment_data[i].save_status;
+               input_attachment_tbl_data[i].attachment_drm_type = result_attachment_data[i].drm_status;
+               input_attachment_tbl_data[i].attachment_inline_content_status = result_attachment_data[i].inline_content_status;
+               input_attachment_tbl_data[i].attachment_mime_type = EM_SAFE_STRDUP(result_attachment_data[i].attachment_mime_type);
+       }
+
+       if ((err = em_verify_email_address_of_mail_tbl(input_mail_tbl_data, false)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("em_verify_email_address_of_mail_tbl failed : [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       if (!emcore_make_rfc822_file_from_mail(input_mail_tbl_data, input_attachment_tbl_data, result_attachment_data_count, NULL, &file_path, NULL, &err)) {
+               EM_DEBUG_EXCEPTION("emcore_make_rfc822_file_from_mail failed");
+               goto FINISH_OFF;
+       }
+
+       if (output_file_path) {
+               if (!emstorage_move_file(file_path, output_file_path, false, &err)) {
+                       EM_DEBUG_EXCEPTION("emstorage_move_file failed : [%d]", err);
+                       goto FINISH_OFF;
+               }
+       } else {
+               exist_file_path = 1;
+               output_file_path = EM_SAFE_STRDUP(file_path);
+       }
+
+
+       if (!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, (char *)output_file_path, EM_SAFE_STRLEN(output_file_path) + 1)) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       local_result = 1;
+
+FINISH_OFF:
+       if ( local_result == 0 ) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       emstorage_free_attachment(&input_attachment_tbl_data, result_attachment_data_count, &ret);
+
+       emstorage_free_mail(&input_mail_tbl_data, 1, &ret);
+
+       emcore_free_mail_data(&result_mail_data);
+
+       if(result_attachment_data)
+               emcore_free_attachment_data(&result_attachment_data, result_attachment_data_count, NULL);
+
+       EM_SAFE_FREE(file_path);
+       if (exist_file_path)
+               EM_SAFE_FREE(output_file_path);
+
+       em_flush_memory();
+       EM_DEBUG_FUNC_END();
+}
+
+void stb_handle_task(int task_type, HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int param_index = 0;
+       int is_async_task = (task_type > EMAIL_ASYNC_TASK_BOUNDARY)?1:0;
+       int err = EMAIL_ERROR_NONE;
+       int task_id = 0;
+       int task_parameter_length = 0;
+       char *task_parameter = NULL;
+
+       /* task_parameter_length */;
+       task_parameter_length = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+       EM_DEBUG_LOG("task_parameter_length [%d]", task_parameter_length);
+
+       /* task_parameter */
+       if(task_parameter_length > 0)    {
+               task_parameter = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+       }
+
+       if(is_async_task) {
+               /* add async task */
+               if((err = emcore_add_task_to_task_table(task_type, EMAIL_TASK_PRIORITY_MID, task_parameter, task_parameter_length, &task_id)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_add_task_to_task_pool failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+       }
+       else {
+               /* do sync task */
+       }
+
+FINISH_OFF:
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if(is_async_task) {
+               if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &task_id, sizeof(int)))
+                       EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+       }
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       em_flush_memory();
+       EM_DEBUG_FUNC_END("err [%d]", err);
+}
+
+void* thread_func_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT(void *input_param)
+{
+       EM_DEBUG_FUNC_BEGIN("input_param [%p]", input_param);
+       int err = EMAIL_ERROR_NONE;
+       int err_for_signal = EMAIL_ERROR_NONE;
+       int i = 0;
+       int task_id = THREAD_SELF();
+       task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT *task_param = input_param;
+
+       /* Send start signal */
+       if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT, task_id, EMAIL_TASK_STATUS_STARTED, EMAIL_ERROR_NONE, 0)) != EMAIL_ERROR_NONE)
+               EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+
+       for(i = 0; i < task_param->mail_id_count; i++) {
+               if((err = emcore_move_mail_to_another_account(task_param->mail_id_array[i], task_param->source_mailbox_id, task_param->target_mailbox_id, task_id)) != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("emcore_move_mail_to_another_account failed [%d]", err);
+                       goto FINISH_OFF;
+               }
+
+               /* Send progress signal */
+               if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT, task_id, EMAIL_TASK_STATUS_IN_PROGRESS, i, task_param->mail_id_count)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+       }
+
+FINISH_OFF:
+       /* Send finish signal */
+       if(err == EMAIL_ERROR_NONE) {
+               if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT, task_id, EMAIL_TASK_STATUS_FINISHED, EMAIL_ERROR_NONE, 0)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+       }
+       else {
+               if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT, task_id, EMAIL_TASK_STATUS_FAILED, err, 0)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+       }
+
+       /* Free task parameter */
+       EM_SAFE_FREE(task_param->mail_id_array);
+       EM_SAFE_FREE(task_param);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return SUCCESS;
+}
+
+void stb_move_mails_to_mailbox_of_another_account(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int param_index = 0;
+       int err = EMAIL_ERROR_NONE;
+       int task_parameter_length = 0;
+       int thread_error;
+       thread_t task_id;
+       char *task_parameter = NULL;
+       task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT *decoded_parameter = NULL;
+
+       /* task_parameter_length */;
+       task_parameter_length = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+
+       if(task_parameter_length <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM : task_parameter_length [%d]", task_parameter_length);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* task_parameter */
+       task_parameter = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+
+       if((err = email_decode_task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT(task_parameter, task_parameter_length, (void**)&decoded_parameter)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("email_decode_task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       THREAD_CREATE(task_id, thread_func_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT, (void*)decoded_parameter, thread_error);
+
+       if(thread_error != 0) {
+               EM_DEBUG_EXCEPTION("THREAD_CREATE failed [%d]", thread_error);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       THREAD_DETACH(task_id);
+
+FINISH_OFF:
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &task_id, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+}
+
+void* thread_func_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX(void *input_param)
+{
+       EM_DEBUG_FUNC_BEGIN("input_param [%p]", input_param);
+       int err = EMAIL_ERROR_NONE;
+       int err_for_signal = EMAIL_ERROR_NONE;
+       int task_id = THREAD_SELF();
+       task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX *task_param = input_param;
+
+       /* Send start signal */
+       if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX, task_id, EMAIL_TASK_STATUS_STARTED, EMAIL_ERROR_NONE, 0)) != EMAIL_ERROR_NONE)
+               EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+
+       if((err = emcore_delete_mailbox_ex(task_param->account_id, task_param->mailbox_id_array, task_param->mailbox_id_count, task_param->on_server)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_delete_mailbox_ex failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+       /* Send finish signal */
+       if(err == EMAIL_ERROR_NONE) {
+               if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX, task_id, EMAIL_TASK_STATUS_FINISHED, EMAIL_ERROR_NONE, 0)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+       }
+       else {
+               if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX, task_id, EMAIL_TASK_STATUS_FAILED, err, 0)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+       }
+
+       /* Free task parameter */
+       EM_SAFE_FREE(task_param->mailbox_id_array);
+       EM_SAFE_FREE(task_param);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return SUCCESS;
+}
+
+void stb_delete_mailbox_ex(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int param_index = 0;
+       int err = EMAIL_ERROR_NONE;
+       int task_parameter_length = 0;
+       int thread_error = 0;
+       thread_t task_id;
+       char *task_parameter = NULL;
+       task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX *decoded_parameter = NULL;
+
+       /* task_parameter_length */;
+       task_parameter_length = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+
+       if(task_parameter_length <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM : task_parameter_length [%d]", task_parameter_length);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* task_parameter */
+       task_parameter = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+
+       if((err = email_decode_task_parameter_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX(task_parameter, task_parameter_length, (void**)&decoded_parameter)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("email_decode_task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       THREAD_CREATE(task_id, thread_func_EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX, (void*)decoded_parameter, thread_error);
+
+       if(thread_error != 0) {
+               EM_DEBUG_EXCEPTION("THREAD_CREATE failed [%d]", thread_error);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       THREAD_DETACH(task_id);
+
+FINISH_OFF:
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &task_id, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+}
+
+void* thread_func_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL(void *input_param)
+{
+       EM_DEBUG_FUNC_BEGIN("input_param [%p]", input_param);
+       int err = EMAIL_ERROR_NONE;
+       int err_for_signal = EMAIL_ERROR_NONE;
+       int task_id = THREAD_SELF();
+       task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL *task_param = input_param;
+
+       /* Send start signal */
+       if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL, task_id, EMAIL_TASK_STATUS_STARTED, EMAIL_ERROR_NONE, 0)) != EMAIL_ERROR_NONE)
+               EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+
+       if((err = emcore_send_mail_with_downloading_attachment_of_original_mail(task_param->mail_id)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_send_mail_with_downloading_attachment_of_original_mail failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+FINISH_OFF:
+       /* Send finish signal */
+       if(err == EMAIL_ERROR_NONE) {
+               if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL, task_id, EMAIL_TASK_STATUS_FINISHED, EMAIL_ERROR_NONE, 0)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+       }
+       else {
+               if((err_for_signal = emcore_send_task_status_signal(EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL, task_id, EMAIL_TASK_STATUS_FAILED, err, 0)) != EMAIL_ERROR_NONE)
+                       EM_DEBUG_LOG("emcore_send_task_status_signal failed [%d]", err_for_signal);
+       }
+
+       /* Free task parameter */
+       EM_SAFE_FREE(task_param);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return SUCCESS;
+}
+
+void stb_send_mail_with_downloading_attachment_of_original_mail(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int param_index = 0;
+       int err = EMAIL_ERROR_NONE;
+       int task_parameter_length = 0;
+       int thread_error = 0;
+       thread_t task_id;
+       char *task_parameter = NULL;
+       task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL *decoded_parameter = NULL;
+
+       /* task_parameter_length */;
+       task_parameter_length = emipc_get_nth_parameter_length(a_hAPI, ePARAMETER_IN, param_index);
+
+       if(task_parameter_length <= 0) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM : task_parameter_length [%d]", task_parameter_length);
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       /* task_parameter */
+       task_parameter = (char*) emipc_get_nth_parameter_data(a_hAPI, ePARAMETER_IN, param_index++);
+
+       if((err = email_decode_task_parameter_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL(task_parameter, task_parameter_length, (void**)&decoded_parameter)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("email_decode_task_parameter_EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT failed[%d]", err);
+               goto FINISH_OFF;
+       }
+
+       THREAD_CREATE(task_id, thread_func_EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL, (void*)decoded_parameter, thread_error);
+
+       if(thread_error != 0) {
+               EM_DEBUG_EXCEPTION("THREAD_CREATE failed [%d]", thread_error);
+               err = EMAIL_ERROR_SYSTEM_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       THREAD_DETACH(task_id);
+
+FINISH_OFF:
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &err, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if(!emipc_add_parameter(a_hAPI, ePARAMETER_OUT, &task_id, sizeof(int)))
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+
+       if (!emipc_execute_stub_api(a_hAPI))
+               EM_DEBUG_EXCEPTION("emipc_execute_stub_api failed");
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+}
+
+void stb_API_mapper(HIPC_API a_hAPI)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int nAPIID = emipc_get_api_id(a_hAPI);
+
+       switch(nAPIID) {
+               case _EMAIL_API_ADD_ACCOUNT:
+                       stb_create_account(a_hAPI);
+                       break;
+
+               case _EMAIL_API_ADD_MAILBOX:
+                       stb_create_mailbox(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DELETE_MAILBOX:
+                       stb_delete_mailbox(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SET_MAILBOX_TYPE:
+                       stb_set_mailbox_type(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SET_LOCAL_MAILBOX:
+                       stb_set_local_mailbox(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SET_MAIL_SLOT_SIZE:
+                       stb_set_mail_slot_size_of_mailbox(a_hAPI);
+                       break;
+
+               case _EMAIL_API_RENAME_MAILBOX:
+                       stb_rename_mailbox(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SEND_MAIL:
+                       stb_send_mail(a_hAPI);
+                       break;
+
+               case _EMAIL_API_GET_MAILBOX_LIST:
+                       stb_get_mailbox_list(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SYNC_HEADER:
+                       stb_sync_header(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DOWNLOAD_BODY:
+                       stb_download_body(a_hAPI);
+                       break;
+
+               case _EMAIL_API_CLEAR_DATA:
+                       stb_clear_mail_data (a_hAPI);
+                       break;
+
+               case _EMAIL_API_DELETE_ALL_MAIL:
+                       stb_delete_all_mails(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DELETE_MAIL:
+                       stb_delete_mail(a_hAPI);
+                       break;
+
+               case _EMAIL_API_ADD_RULE:
+                       stb_add_rule(a_hAPI);
+                       break;
+
+               case _EMAIL_API_GET_RULE:
+                       stb_get_rule(a_hAPI);
+                       break;
+
+               case _EMAIL_API_GET_RULE_LIST:
+                       stb_get_rule_list(a_hAPI);
+                       break;
+
+               case _EMAIL_API_FIND_RULE:
+                       stb_find_rule(a_hAPI);
+                       break;
+
+               case _EMAIL_API_UPDATE_RULE:
+                       stb_update_rule(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DELETE_RULE:
+                       stb_delete_rule(a_hAPI);
+                       break;
+
+               case _EMAIL_API_MOVE_MAIL:
+                       stb_move_mail(a_hAPI);
+                       break;
+
+               case _EMAIL_API_MOVE_ALL_MAIL:
+                       stb_move_all_mails(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SET_FLAGS_FIELD:
+                       stb_set_flags_field(a_hAPI);
+                       break;
+
+               case _EMAIL_API_ADD_MAIL:
+                       stb_add_mail(a_hAPI);
+                       break;
+
+               case _EMAIL_API_UPDATE_MAIL:
+                       stb_update_mail(a_hAPI);
+                       break;
+
+               case _EMAIL_API_MOVE_THREAD_TO_MAILBOX:
+                       stb_move_thread_to_mailbox(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DELETE_THREAD:
+                       stb_delete_thread(a_hAPI);
+                       break;
+
+               case _EMAIL_API_MODIFY_SEEN_FLAG_OF_THREAD:
+                       stb_modify_seen_flag_of_thread(a_hAPI);
+                       break;
+
+               case _EMAIL_API_EXPUNGE_MAILS_DELETED_FLAGGED:
+                       stb_expunge_mails_deleted_flagged(a_hAPI);
+                       break;
+
+               case _EMAIL_API_UPDATE_MAIL_ATTRIBUTE:
+                       stb_update_mail_attribute(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DELETE_ACCOUNT:
+                       stb_delete_account(a_hAPI);
+                       break;
+
+               case _EMAIL_API_UPDATE_ACCOUNT:
+                       stb_update_account(a_hAPI);
+                       break;
+
+               case _EMAIL_API_ADD_ATTACHMENT:
+                       stb_add_attachment(a_hAPI);
+                       break;
+
+               case _EMAIL_API_GET_IMAP_MAILBOX_LIST:
+                       stb_get_imap_mailbox_list(a_hAPI);
+                       break;
+
+               case _EMAIL_API_GET_ATTACHMENT:
+                       stb_get_attachment(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DELETE_ATTACHMENT:
+                       stb_delete_attachment(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DOWNLOAD_ATTACHMENT:
+                       stb_download_attachment(a_hAPI);
+                       break;
+
+               case _EMAIL_API_GET_ACCOUNT_LIST:
+                       stb_get_account_list(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SEND_SAVED:
+                       stb_mail_send_saved(a_hAPI);
+                       break;
+
+               case _EMAIL_API_ADD_READ_RECEIPT:
+                       stb_add_read_receipt(a_hAPI);
+                       break;
+
+               case _EMAIL_API_CANCEL_JOB:
+                       stb_cancel_job(a_hAPI);
+                       break;
+
+               case _EMAIL_API_GET_PENDING_JOB:
+                       stb_get_pending_job(a_hAPI);
+                       break;
+
+               case _EMAIL_API_NETWORK_GET_STATUS:
+                       stb_get_event_queue_status(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SEND_RETRY:
+                       stb_retry_sending_mail(a_hAPI);
+                       break;
+
+               case _EMAIL_API_VALIDATE_ACCOUNT :
+                       stb_validate_account(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SEND_MAIL_CANCEL_JOB :
+                       stb_cancel_send_mail_job(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SEARCH_MAIL_ON_SERVER :
+                       stb_search_mail_on_server(a_hAPI);
+                       break;
+
+               case _EMAIL_API_CLEAR_RESULT_OF_SEARCH_MAIL_ON_SERVER :
+                       stb_clear_result_of_search_mail_on_server(a_hAPI);
+                       break;
+
+               case _EMAIL_API_ADD_ACCOUNT_WITH_VALIDATION :
+                       stb_add_account_with_validation(a_hAPI);
+                       break;
+
+               case _EMAIL_API_BACKUP_ACCOUNTS:
+                       stb_backup_account(a_hAPI);
+                       break;
+
+               case _EMAIL_API_RESTORE_ACCOUNTS:
+                       stb_restore_account(a_hAPI);
+                       break;
+
+               case _EMAIL_API_GET_PASSWORD_LENGTH_OF_ACCOUNT:
+                       stb_get_password_length(a_hAPI);
+                       break;
+
+               case _EMAIL_API_PRINT_RECEIVING_EVENT_QUEUE :
+                       stb_print_receiving_event_queue_via_debug_msg(a_hAPI);
+                       break;
+
+               case _EMAIL_API_ADD_CERTIFICATE:
+                       stb_add_certificate(a_hAPI);
+                       break;
+
+               case _EMAIL_API_DELETE_CERTIFICATE:
+                       stb_delete_certificate(a_hAPI);
+                       break;
+
+               case _EMAIL_API_VERIFY_SIGNATURE:
+                       stb_verify_signature(a_hAPI);
+                       break;
+
+               case _EMAIL_API_VERIFY_CERTIFICATE:
+                       stb_verify_certificate(a_hAPI);
+                       break;
+
+               case _EMAIL_API_PING_SERVICE :
+                       stb_ping_service(a_hAPI);
+                       break;
+
+               case _EMAIL_API_UPDATE_NOTIFICATION_BAR_FOR_UNREAD_MAIL :
+                       stb_update_notification_bar_for_unread_mail(a_hAPI);
+                       break;
+
+               case _EMAIL_API_SHOW_USER_MESSAGE :
+                       stb_show_user_message(a_hAPI);
+                       break;
+
+               case _EMAIL_API_WRITE_MIME_FILE :
+                       stb_write_mime_file(a_hAPI);
+                       break;
+
+               case EMAIL_ASYNC_TASK_MOVE_MAILS_TO_MAILBOX_OF_ANOTHER_ACCOUNT :
+                       stb_move_mails_to_mailbox_of_another_account(a_hAPI);
+                       break;
+
+               case EMAIL_ASYNC_TASK_DELETE_MAILBOX_EX :
+                       stb_delete_mailbox_ex(a_hAPI);
+                       break;
+
+               case EMAIL_ASYNC_TASK_SEND_MAIL_WITH_DOWNLOADING_ATTACHMENT_OF_ORIGINAL_MAIL :
+                       stb_send_mail_with_downloading_attachment_of_original_mail(a_hAPI);
+                       break;
+       }
+       EM_DEBUG_FUNC_END();
+}
+
+GMainLoop *g_mainloop = NULL;
+
+static void callback_for_sigterm(int signum)
+{
+       EM_DEBUG_FUNC_BEGIN("signum [%d]", signum);
+
+       if (g_mainloop)
+               g_main_loop_quit(g_mainloop);
+
+       EM_DEBUG_FUNC_END();
+}
+
+INTERNAL_FUNC int main(int argc, char *argv[])
+{
+       /* Do the email-service Initialization 
+       1. Create all DB tables and load the email engine */
+       EM_DEBUG_LOG("Email service begin");
+       int err = 0, ret;
+       GMainLoop *mainloop;
+
+#ifdef USE_OMA_EMN
+       EM_DEBUG_LOG("emdaemon_initialize_emn Start");
+       emdaemon_initialize_emn();
+#endif
+
+       EM_DEBUG_LOG("ipcEmailStub_Initialize Start");
+       
+       ret = emipc_initialize_stub(stb_API_mapper);
+
+       if(ret == true)
+               EM_DEBUG_LOG("ipcEmailStub_Initialize Success");
+       else
+               EM_DEBUG_EXCEPTION("ipcEmailStub_Initialize failed");
+
+       signal(SIGPIPE, SIG_IGN);              /* to ignore signal 13(SIGPIPE) */
+       signal(SIGTERM, callback_for_sigterm); /* to handle signal 15(SIGTERM) - power off case*/
+
+       emdaemon_initialize(&err);
+
+       /* Start auto polling */
+#ifdef __FEATURE_AUTO_POLLING__
+       emdaemon_start_auto_polling(&err);
+#endif
+
+       mainloop = g_main_loop_new(NULL, 0);
+       g_mainloop = mainloop;
+
+       g_type_init();
+
+       g_main_loop_run(mainloop);
+       
+       /* Clean up resources */
+       g_main_loop_unref(mainloop);
+
+       g_mainloop = NULL;
+
+       emipc_finalize_stub();
+
+       emdaemon_finalize(NULL);
+
+       EM_DEBUG_FUNC_END();
+       return 0;
+}
+
diff --git a/email-ipc/CMakeLists.txt b/email-ipc/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..2747b14
--- /dev/null
@@ -0,0 +1,78 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(email-ipc)
+
+SET(CMAKE_SKIP_BUILD_RPATH TRUE)
+
+IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+       SET(CMAKE_BUILD_TYPE "Debug")
+ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+
+MESSAGE("")
+MESSAGE(">>> current directory: ${CMAKE_CURRENT_SOURCE_DIR}")
+MESSAGE(">>> Build type: ${CMAKE_BUILD_TYPE}")
+
+SET(IPC-LIB "email-ipc")
+SET(IPC-SRCS
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-api.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-build.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-proxy.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-stub.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-api/email-ipc-api-info.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-api/email-ipc-param.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-api/email-ipc-param-list.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-proxy/email-proxy-callback-info.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-proxy/email-proxy-main.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-proxy/email-proxy-socket.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-socket/email-ipc-socket.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-stub/email-stub-main.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-stub/email-stub-socket.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-stub/email-stub-task.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-stub/email-stub-task-manager.c
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-activation/email-dbus-activation.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/email-daemon/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-proxy/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-stub/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-socket/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-ipc-api/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/email-activation/include
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
+       ${CMAKE_SOURCE_DIR}/email-api/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include/
+       ${CMAKE_SOURCE_DIR}/email-core/include/
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(ipc_pkgs REQUIRED dlog dbus-1 glib-2.0 libsystemd-daemon)
+
+FOREACH(flag ${ipc_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+ADD_DEFINITIONS("-DBRSDK_VER=\"2\"")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+MESSAGE("Before DBUS binding")
+
+FIND_PROGRAM(DBUS_BINDING_TOOL NAMES dbus-binding-tool)
+EXEC_PROGRAM("${DBUS_BINDING_TOOL}" ARGS "--prefix=email_service ${CMAKE_CURRENT_SOURCE_DIR}/email-activation/email-service.xml --mode=glib-client --output=${CMAKE_CURRENT_SOURCE_DIR}/email-activation/include/email-service-glue.h")
+EXEC_PROGRAM("${DBUS_BINDING_TOOL}" ARGS "--prefix=email_service ${CMAKE_CURRENT_SOURCE_DIR}/email-activation/email-service.xml --mode=glib-server --output=${CMAKE_CURRENT_SOURCE_DIR}/email-activation/include/email-service-binding.h")
+
+MESSAGE("After DBUS binding")
+
+ADD_LIBRARY(${IPC-LIB} SHARED ${IPC-SRCS})
+TARGET_LINK_LIBRARIES(${IPC-LIB} ${ipc_pkgs_LDFLAGS} email-common-use pthread)
+SET_TARGET_PROPERTIES(${IPC-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${IPC-LIB} PROPERTIES VERSION ${VERSION})
+
+INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/email-activation/email-service.service DESTINATION share/dbus-1/services)
+INSTALL(TARGETS ${IPC-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
+
diff --git a/email-ipc/email-activation/email-dbus-activation.c b/email-ipc/email-activation/email-dbus-activation.c
new file mode 100755 (executable)
index 0000000..1f3d6ca
--- /dev/null
@@ -0,0 +1,177 @@
+/*\r
+*  email-service\r
+*\r
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
+*\r
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
+*\r
+* Licensed under the Apache License, Version 2.0 (the "License");\r
+* you may not use this file except in compliance with the License.\r
+* You may obtain a copy of the License at\r
+*\r
+* http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*\r
+*/\r
+\r
+#include <glib.h>\r
+#include <pthread.h>\r
+#include <dbus/dbus-glib.h>\r
+#include <dbus/dbus-glib-bindings.h>\r
+#include <sys/utsname.h>\r
+#include "email-types.h"\r
+#include "email-debug-log.h"\r
+#include "email-dbus-activation.h"\r
+#include "email-service-binding.h"\r
+#include "email-service-glue.h"\r
+#include <unistd.h>\r
+\r
+GMainLoop *loop = NULL;\r
+GObject *object = NULL;\r
+DBusGConnection *connection = NULL;\r
+\r
+static pid_t launch_by_client = 0;\r
+\r
+void __net_nfc_discovery_polling_cb(int signo);\r
+bool Check_Redwood();\r
+\r
+G_DEFINE_TYPE(EmailService, email_service, G_TYPE_OBJECT)\r
+\r
+#define __G_ASSERT(test, return_val, error, domain, error_code)\\r
+G_STMT_START\\r
+{\\r
+        if G_LIKELY (!(test)) { \\r
+                g_set_error (error, domain, error_code, #test); \\r
+                return (return_val); \\r
+        }\\r
+}\\r
+G_STMT_END\r
+\r
+\r
+static void email_service_init(EmailService *email_service)\r
+{\r
+       EM_DEBUG_LOG("email_service_init entered");\r
+}\r
+\r
+GQuark email_service_error_quark(void)\r
+{\r
+       EM_DEBUG_LOG("email_service_error_quark entered");\r
+       return g_quark_from_static_string("email_service_error");\r
+}\r
+\r
+\r
+static void email_service_class_init(EmailServiceClass *email_service_class)\r
+{\r
+       EM_DEBUG_LOG("email_service_class_init entered");\r
+\r
+       /*\r
+       dbus_g_object_type_install_info(EMAIL_SERVICE_TYPE, &dbus_glib_nfc_service_object_info);\r
+       */\r
+}\r
+\r
+EXPORT_API int emipc_launch_email_service()\r
+{\r
+       EM_DEBUG_FUNC_BEGIN();\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       /*DBUS*/\r
+       DBusGConnection *connection = NULL;\r
+       DBusGProxy *proxy = NULL;\r
+       GError *error = NULL;\r
+       guint dbus_result = 0;\r
+\r
+       //if(!g_thread_supported()) {\r
+       //      g_thread_init(NULL);\r
+       //}\r
+\r
+       //dbus_g_thread_init();\r
+\r
+       g_type_init();\r
+\r
+       //pthread_mutex_lock(&g_client_context.g_client_lock);\r
+\r
+       connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);\r
+       if (error == NULL) {\r
+               proxy = dbus_g_proxy_new_for_name(connection, EMAIL_SERVICE_NAME, EMAIL_SERVICE_PATH, EMAIL_SERVICE_NAME);\r
+\r
+               if (proxy != NULL) {\r
+                       if (org_tizen_email_service_launch(proxy, &dbus_result, &error) == false) {\r
+                               EM_DEBUG_EXCEPTION("email_service_launch failed");\r
+                               if (error != NULL) {\r
+                                       EM_DEBUG_EXCEPTION("message : [%s]", error->message);\r
+                                       g_error_free(error);\r
+                                       return EMAIL_ERROR_IPC_PROTOCOL_FAILURE;\r
+                               }\r
+                       }\r
+                       EM_DEBUG_LOG("org_tizen_email_service_launch");\r
+\r
+                       g_object_unref (proxy);\r
+               }\r
+               else {\r
+                       EM_DEBUG_EXCEPTION("dbus_g_proxy_new_for_name failed");\r
+               }\r
+       }\r
+       else {\r
+               EM_DEBUG_EXCEPTION("ERROR: Can't get on system bus [%s]", error->message);\r
+               g_error_free(error);\r
+       }\r
+\r
+       EM_DEBUG_FUNC_END("ret [%d]", err);\r
+       return err;\r
+}\r
+\r
+\r
+EXPORT_API int emipc_init_dbus_connection()\r
+{\r
+       EM_DEBUG_FUNC_BEGIN();\r
+       int err = EMAIL_ERROR_NONE;\r
+\r
+       GError *error = NULL;\r
+       DBusGProxy *proxy = NULL;\r
+       guint ret = 0;\r
+\r
+       g_type_init();\r
+\r
+       connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);\r
+       if (error == NULL) {\r
+               object = (GObject *)g_object_new(EMAIL_SERVICE_TYPE, NULL);\r
+               dbus_g_connection_register_g_object(connection, EMAIL_SERVICE_PATH, object);\r
+\r
+               // register service\r
+               proxy = dbus_g_proxy_new_for_name(connection, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS);\r
+               if (proxy != NULL) {\r
+                       if (!org_freedesktop_DBus_request_name(proxy, EMAIL_SERVICE_NAME, 0, &ret, &error)) {\r
+                               EM_DEBUG_EXCEPTION("Unable to register service: %s", error->message);\r
+                               g_error_free(error);\r
+                       }\r
+\r
+                       g_object_unref (proxy);\r
+               }\r
+               else {\r
+                       EM_DEBUG_EXCEPTION("dbus_g_proxy_new_for_name failed");\r
+               }\r
+       }\r
+       else {\r
+               EM_DEBUG_EXCEPTION("ERROR: Can't get on system bus [%s]", error->message);\r
+               g_error_free(error);\r
+       }\r
+       EM_DEBUG_FUNC_END("err [%d]", err);\r
+       return err;\r
+}\r
+\r
+gboolean email_service_launch(EmailService *email_service, guint *result_val, GError **error)\r
+{\r
+       EM_DEBUG_LOG("email_service_launch entered");\r
+\r
+       EM_DEBUG_LOG("email_service_launch PID=[%ld]\n" , getpid());\r
+       EM_DEBUG_LOG("email_service_launch TID=[%ld]" , pthread_self());\r
+\r
+       launch_by_client = getpid();\r
+\r
+       return TRUE;\r
+}\r
diff --git a/email-ipc/email-activation/email-service.service b/email-ipc/email-activation/email-service.service
new file mode 100755 (executable)
index 0000000..aac4dcb
--- /dev/null
@@ -0,0 +1,3 @@
+[D-BUS Service]
+Name=org.tizen.email_service
+Exec=/usr/bin/email-service
diff --git a/email-ipc/email-activation/email-service.xml b/email-ipc/email-activation/email-service.xml
new file mode 100755 (executable)
index 0000000..0783757
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<node name="/org/tizen/email_service">
+       <interface name="org.tizen.email_service">
+               <method name="Launch">
+                       <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="email_service_launch"/>
+                       <arg type="u" name="result_val" direction="out"/>
+               </method>
+       </interface>
+</node>
diff --git a/email-ipc/email-activation/include/email-dbus-activation.h b/email-ipc/email-activation/include/email-dbus-activation.h
new file mode 100755 (executable)
index 0000000..1341694
--- /dev/null
@@ -0,0 +1,72 @@
+/*\r
+*  email-service\r
+*\r
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.\r
+*\r
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>\r
+*\r
+* Licensed under the Apache License, Version 2.0 (the "License");\r
+* you may not use this file except in compliance with the License.\r
+* You may obtain a copy of the License at\r
+*\r
+* http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*\r
+*/\r
+\r
+\r
+#ifndef __EMAIL_DBUS_ACTIVATION_H__\r
+#define __EMAIL_DBUS_ACTIVATION_H__\r
+\r
+/* standard library header */\r
+#include <glib-object.h>\r
+\r
+typedef struct _email_service_t EmailService;\r
+typedef struct _email_service_class_t EmailServiceClass;\r
+\r
+\r
+#define EMAIL_SERVICE_NAME "org.tizen.email_service"\r
+#define EMAIL_SERVICE_PATH "/org/tizen/email_service"\r
+\r
+GType email_service_get_type(void);\r
+\r
+struct _email_service_t\r
+{\r
+       GObject parent;\r
+       int status;\r
+};\r
+\r
+struct _email_service_class_t\r
+{\r
+       GObjectClass parent;\r
+};\r
+\r
+#define EMAIL_SERVICE_TYPE              (email_service_get_type())\r
+#define EMAIL_SERVICE(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), EMAIL_SERVICE_TYPE, EmailService))\r
+#define EMAIL_SERVICE_CLASS(klass)      (G_TYPE_CHECK_CLASS_CAST ((klass), EMAIL_SERVICE_TYPE, EmailServiceClass))\r
+#define IS_EMAIL_SERVICE(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), EMAIL_SERVICE_TYPE))\r
+#define IS_EMAIL_SERVICE_CLASS(klass)   (G_TYPE_CHECK_CLASS_TYPE ((klass), EMAIL_SERVICE_TYPE))\r
+#define EMAIL_SERVICE_GET_CLASS(obj)    (G_TYPE_INSTANCE_GET_CLASS ((obj), EMAIL_SERVICE_TYPE, EmailServiceClass))\r
+\r
+typedef enum\r
+{\r
+       NFC_SERVICE_ERROR_INVALID_PRAM\r
+} email_servcie_error;\r
+\r
+GQuark email_service_error_quark(void);\r
+#define EMAIL_SERVICE_ERROR email_service_error_quark()\r
+\r
+/**\r
+ *     launch the email-service\r
+ */\r
+gboolean email_service_launch(EmailService *email_service, guint *result_val, GError **error);\r
+\r
+EXPORT_API int emipc_init_dbus_connection();\r
+EXPORT_API int emipc_launch_email_service();\r
+\r
+#endif /* __EMAIL_DBUS_ACTIVATION_H__ */\r
diff --git a/email-ipc/email-ipc-api.c b/email-ipc/email-ipc-api.c
new file mode 100755 (executable)
index 0000000..33fe936
--- /dev/null
@@ -0,0 +1,249 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <malloc.h>
+
+#include "email-ipc.h"
+#include "email-ipc-build.h"
+#include "email-ipc-api-info.h"
+#include "email-ipc-param-list.h"
+#include "email-ipc-socket.h"
+#include "email-proxy-main.h"
+#include "email-core-task-manager.h"
+
+#include "email-debug-log.h"
+#include "email-errors.h"
+
+EXPORT_API emipc_param_list *emipc_get_api_parameters(HIPC_API api, EPARAMETER_DIRECTION direction)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       emipc_email_api_info *api_info = (emipc_email_api_info *)api;
+
+       return (emipc_param_list *)emipc_get_parameters_of_api_info(api_info, direction);
+}
+
+EXPORT_API HIPC_API emipc_create_email_api(long api_id)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       emipc_email_api_info *api_info = (emipc_email_api_info *)calloc(1, sizeof(emipc_email_api_info));
+       if(api_info == NULL) {
+               EM_DEBUG_EXCEPTION("Malloc failed");
+               return NULL;
+       }
+
+       api_info->api_id = api_id;
+
+       return (HIPC_API)api_info;
+}
+
+EXPORT_API void emipc_destroy_email_api(HIPC_API api)
+{
+       EM_DEBUG_FUNC_BEGIN("API = %p", api);
+       emipc_email_api_info *api_info = (emipc_email_api_info *)api;
+       emipc_free_api_info(api_info);
+       EM_SAFE_FREE(api_info);
+}
+
+EXPORT_API long emipc_get_api_id(HIPC_API api)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       emipc_email_api_info *api_info = (emipc_email_api_info*)api;
+       return api_info->api_id;
+}
+
+EXPORT_API long emipc_get_app_id(HIPC_API api)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       emipc_email_api_info *api_info = (emipc_email_api_info *)api;
+       return api_info->app_id;
+}
+
+/* note: there incurs additional cost (malloc & memcpy). */
+/* if data is a dynamic variable, please use emipc_dynamic_parameter instead */
+EXPORT_API bool emipc_add_parameter(HIPC_API api, EPARAMETER_DIRECTION direction, void *data, int data_length)
+{
+       EM_DEBUG_FUNC_BEGIN("data_length[%d]", data_length);
+
+       emipc_param_list *parameters = emipc_get_api_parameters(api, direction);
+       if (!parameters) {
+               EM_DEBUG_EXCEPTION("emipc_get_api_parameters failed");
+               return false;
+       }
+
+       return emipc_add_param_to_param_list(parameters, data, data_length);
+}
+
+/* caution : data should be a dynamic variable */
+/*           please, do not use a static variable */
+EXPORT_API bool emipc_add_dynamic_parameter(HIPC_API api, EPARAMETER_DIRECTION direction, void *data, int data_length)
+{
+       EM_DEBUG_FUNC_BEGIN("data_length[%d]", data_length);
+       
+       emipc_param_list *parameters = emipc_get_api_parameters(api, direction);
+       if (!parameters) {
+               EM_DEBUG_EXCEPTION("emipc_get_api_parameters failed");
+               return false;
+       }
+
+       emipc_add_dynamic_param_to_param_list(parameters, data, data_length);
+       return true;
+}
+
+
+
+EXPORT_API int emipc_get_parameter(HIPC_API input_api_handle, EPARAMETER_DIRECTION input_parameter_direction,
+                       int input_parameter_index, int input_parameter_buffer_size, void *output_parameter_buffer)
+{
+       EM_DEBUG_FUNC_BEGIN("parameter_index [%d], parameter_buffer_size [%d]", input_parameter_index, input_parameter_buffer_size);
+       emipc_param_list *parameters = NULL;
+       void *local_buffer = NULL;
+
+       if (input_parameter_buffer_size == 0 || output_parameter_buffer == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       parameters = emipc_get_api_parameters(input_api_handle, input_parameter_direction);
+
+       if (parameters == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_IPC_PROTOCOL_FAILURE");
+               return EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
+       }
+
+       local_buffer = emipc_get_param_of_param_list(parameters, input_parameter_index);
+
+       if (local_buffer == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_IPC_PROTOCOL_FAILURE");
+               return EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
+       }
+
+       if (emipc_get_param_len_of_param_list(parameters, input_parameter_index) != input_parameter_buffer_size) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_IPC_PROTOCOL_FAILURE");
+               return EMAIL_ERROR_IPC_PROTOCOL_FAILURE;
+       }
+
+       memcpy(output_parameter_buffer, local_buffer, input_parameter_buffer_size);
+
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+
+EXPORT_API void* emipc_get_nth_parameter_data(HIPC_API api_handle, EPARAMETER_DIRECTION direction, int param_index)
+{
+       EM_DEBUG_FUNC_BEGIN("nth_parameter_index [%d]", param_index);
+       emipc_param_list *parameters = NULL;
+       void *buf = NULL;
+
+       parameters = emipc_get_api_parameters(api_handle, direction);
+
+       if (parameters == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_IPC_PROTOCOL_FAILURE");
+               return NULL;
+       }
+
+       buf = emipc_get_param_of_param_list(parameters, param_index);
+
+       if (!buf) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_IPC_PROTOCOL_FAILURE");
+               return NULL;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return buf;
+}
+
+
+EXPORT_API int emipc_get_parameter_length(HIPC_API api, EPARAMETER_DIRECTION direction, int parameter_index)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       emipc_param_list *parameters = emipc_get_api_parameters(api, direction);
+       if (parameters) {
+               EM_DEBUG_FUNC_END("Suceeded");
+               return emipc_get_param_len_of_param_list(parameters, parameter_index);
+       }
+       EM_DEBUG_FUNC_END("Failed");
+       return -1;
+}
+
+EXPORT_API int emipc_get_nth_parameter_length(HIPC_API api, EPARAMETER_DIRECTION direction, int parameter_index)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       emipc_param_list *parameters = emipc_get_api_parameters(api, direction);
+       if (parameters) {
+               EM_DEBUG_FUNC_END("Suceeded");
+               return emipc_get_param_len_of_param_list(parameters, parameter_index);
+       }
+       EM_DEBUG_FUNC_END("Failed");
+       return -1;
+}
+
+EXPORT_API int emipc_execute_proxy_task(email_task_type_t input_task_type, void *input_task_parameter)
+{
+       EM_DEBUG_FUNC_BEGIN("input_task_type [%d] input_task_parameter [%p]", input_task_type, input_task_parameter);
+
+       int err = EMAIL_ERROR_NONE;
+       int task_parameter_length = 0;
+       char *task_parameter_stream = NULL;
+       HIPC_API hAPI = NULL;
+
+       if(input_task_parameter == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               err = EMAIL_ERROR_INVALID_PARAM;
+               goto FINISH_OFF;
+       }
+
+       if((err = emcore_encode_task_parameter(input_task_type, input_task_parameter, &task_parameter_stream, &task_parameter_length)) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emcore_encode_task_parameter failed [%d]", err);
+               goto FINISH_OFF;
+       }
+
+       hAPI = emipc_create_email_api(input_task_type);
+
+       if(!hAPI) {
+               EM_DEBUG_EXCEPTION("emipc_create_email_api failed");
+               err = EMAIL_ERROR_NULL_VALUE;
+               goto FINISH_OFF;
+       }
+
+       if(!emipc_add_parameter(hAPI, ePARAMETER_IN, (char*)task_parameter_stream, task_parameter_length)) {
+               EM_DEBUG_EXCEPTION("emipc_add_parameter failed");
+               err = EMAIL_ERROR_OUT_OF_MEMORY;
+               goto FINISH_OFF;
+       }
+
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               EM_DEBUG_EXCEPTION("emipc_execute_proxy_api failed");
+               err = EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               goto FINISH_OFF;
+       }
+
+       emipc_get_parameter(hAPI, ePARAMETER_OUT, 0, sizeof(int), &err);
+
+       FINISH_OFF:
+       if(hAPI)
+               emipc_destroy_email_api(hAPI);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
diff --git a/email-ipc/email-ipc-api/email-ipc-api-info.c b/email-ipc/email-ipc-api/email-ipc-api-info.c
new file mode 100755 (executable)
index 0000000..bf8e263
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <string.h>
+#include <unistd.h>
+#include <malloc.h>
+
+#include "email-ipc-api-info.h"
+#include "email-ipc-param-list.h"
+#include "email-ipc-build.h"
+
+#include "email-debug-log.h"
+
+
+/* deserializing data from stream */
+EXPORT_API bool emipc_deserialize_api_info(emipc_email_api_info *api_info, EPARAMETER_DIRECTION direction, void *stream)
+{
+       EM_DEBUG_FUNC_BEGIN("emipc_email_api_info : [%p], direction : [%d]", api_info, direction);
+       
+       if (!api_info || !stream) {
+               EM_DEBUG_EXCEPTION("Invalid parameter.");
+               return false;
+       }
+
+       if (api_info->params[direction] == NULL) {
+               api_info->params[direction] = emipc_create_param_list();
+               if (api_info->params[direction] == NULL) {
+                       EM_DEBUG_EXCEPTION("Malloc failed");
+                       return false;
+               }
+       }
+
+       api_info->api_id = *((long *)stream + eSTREAM_APIID);
+       api_info->app_id = *((long*)stream + eSTREAM_APPID);
+       api_info->response_id = *((long*)stream + eSTREAM_RESID);
+
+       return emipc_parse_stream_of_param_list(api_info->params[direction], stream);
+}
+
+EXPORT_API unsigned char *emipc_serialize_api_info(emipc_email_api_info *api_info, EPARAMETER_DIRECTION direction, int *stream_len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       unsigned char *stream = NULL;
+       
+       if (!api_info) {
+               EM_DEBUG_EXCEPTION("Invalid parameter.");
+               return stream;
+       }
+
+       if (api_info->params[direction] == NULL) {
+               api_info->params[direction] = emipc_create_param_list();
+               if (api_info->params[direction] == NULL) {
+                       EM_DEBUG_EXCEPTION("Malloc failed");
+                       return NULL;
+               }
+       }
+
+       stream = emipc_serialize_param_list(api_info->params[direction], stream_len);
+       if (stream != NULL) {
+               memcpy(stream, &(api_info->api_id), sizeof(api_info->api_id));
+               memcpy(stream+(sizeof(long)*eSTREAM_RESID), &(api_info->response_id), sizeof(api_info->response_id));
+               memcpy(stream+(sizeof(long)*eSTREAM_APPID), &(api_info->app_id), sizeof(api_info->app_id));
+       }
+       EM_DEBUG_FUNC_END();
+       return stream;
+}
+
+EXPORT_API void *emipc_get_parameters_of_api_info(emipc_email_api_info *api_info, EPARAMETER_DIRECTION direction)
+{
+       EM_DEBUG_FUNC_BEGIN("emipc_email_api_info : [%p], direction : [%d]", api_info, direction);
+       
+       if (!api_info) {
+               EM_DEBUG_EXCEPTION("INVALID_PARAM");
+               return NULL;
+       }
+       
+       if (api_info->params[direction] == NULL) {
+               api_info->params[direction] = emipc_create_param_list();
+               if (api_info->params[direction] == NULL) {
+                       EM_DEBUG_EXCEPTION("emipc_create_param_list failed");
+                       return NULL;
+               }
+       }
+
+       return api_info->params[direction];
+}
+
+EXPORT_API bool emipc_free_api_info(emipc_email_api_info *api_info)
+{
+       if (!api_info) {
+               EM_DEBUG_EXCEPTION("Invalid parameter");
+               return false;
+       }
+
+       if (!emipc_destroy_param_list(api_info->params[ePARAMETER_IN])) {
+               EM_DEBUG_EXCEPTION("emipc_destroy_param_list failed : ePARAMETER[%d]", ePARAMETER_IN);
+               return false;
+       }
+
+       if (!emipc_destroy_param_list(api_info->params[ePARAMETER_OUT])) {
+               EM_DEBUG_EXCEPTION("emipc_destroy_param_list failed : ePARAMETER[%d]", ePARAMETER_OUT);
+               return false;
+       }
+
+       return true;
+}
+
+
diff --git a/email-ipc/email-ipc-api/email-ipc-param-list.c b/email-ipc/email-ipc-api/email-ipc-param-list.c
new file mode 100755 (executable)
index 0000000..388eba3
--- /dev/null
@@ -0,0 +1,237 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 <string.h>
+#include <stdlib.h>
+#include <malloc.h>
+
+#include "email-ipc-build.h"
+#include "email-ipc-param-list.h"
+
+#include "email-debug-log.h"
+#include "email-utilities.h"
+
+/*  stream */
+/*  +----------------------------------------------------------------------------------------------------------+ */
+/*  | API ID(4B) | Resp. ID (4B) | Param Count(4B) | Param1 Len | Param1 Data | ... | ParamN Len | ParamN data |  */
+/*  +----------------------------------------------------------------------------------------------------------+ */
+
+
+EXPORT_API emipc_param_list *emipc_create_param_list()
+{
+       emipc_param_list *new_param_list = NULL;
+
+       new_param_list = (emipc_param_list *) em_malloc (sizeof(emipc_param_list));
+       if (new_param_list == NULL) {
+               EM_DEBUG_EXCEPTION("em_malloc failed.");
+               return NULL;
+       }
+       memset(new_param_list, 0x00, sizeof(emipc_param_list));
+
+       return new_param_list;
+}
+
+EXPORT_API bool emipc_destroy_param_list(emipc_param_list *param_list)
+{
+       int count = 10;
+       int index = 0;
+
+       if (!param_list) {
+               EM_DEBUG_EXCEPTION("Invalid parameter.");
+               return false;
+       }
+
+       for (index = 0; index < count; index++) {
+               emipc_free_param(param_list->params[index]);
+       }
+       EM_SAFE_FREE(param_list->byte_stream);
+       EM_SAFE_FREE(param_list);
+       return true;
+}
+
+/* making stream into param length and param data */
+EXPORT_API bool emipc_parse_stream_of_param_list(emipc_param_list *param_list, void *stream)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       long parameter_count = *((long *)stream + eSTREAM_COUNT);
+       if(parameter_count <= 0) {
+               EM_DEBUG_EXCEPTION("INVALID_PARAM : count %d", parameter_count);
+               return false;
+       }
+
+       int stream_len = malloc_usable_size(stream);
+       int remain_len = stream_len - (sizeof(long) * eSTREAM_DATA);
+       EM_DEBUG_LOG("Allocated stream size : %dbyte", stream_len);
+
+       unsigned char* cur = ((unsigned char*)stream) + sizeof(int)*eSTREAM_DATA;
+
+       int i = 0;
+       /* stream is composed of data type which is encoded into length and data field */
+       int len = 0;
+       for(i = 0; i < parameter_count; i++) {
+
+               if (remain_len < sizeof(int)) {
+                       EM_DEBUG_EXCEPTION("Not enough remain stream_len[%d]", remain_len);
+                       return false;
+               }
+
+               /* reading length */
+               memcpy(&len, cur, sizeof(int));
+
+               /* moving from length field to data field */
+               cur += sizeof(int);
+               remain_len -= sizeof(int);
+
+               if (remain_len > 0 && len > 0 && remain_len >= len)
+                       emipc_add_param_to_param_list(param_list, (void*)cur, len);
+               else {
+                       EM_DEBUG_EXCEPTION("data_len[%d] is not in the boundary of remain stream_len", len);
+                       return false;
+               }
+
+               EM_DEBUG_LOG("Parsing stream : element %d is %dbyte long ", i, len);
+
+               /*  move to next parameter       */
+               cur += len;
+               remain_len -= len;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+EXPORT_API unsigned char *emipc_serialize_param_list(emipc_param_list *param_list, int *stream_length)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if(param_list->byte_stream)
+               return param_list->byte_stream;
+
+       int stream_len = emipc_sum_param_list_length (param_list);
+
+       if (stream_len <= 0) {
+               EM_DEBUG_EXCEPTION("stream_len error %d", stream_len);
+               EM_SAFE_FREE(param_list->byte_stream);
+               return NULL;
+       }
+
+       param_list->byte_stream = (unsigned char*)calloc(1, stream_len);
+       int pos = sizeof(long)*eSTREAM_COUNT;
+
+       if (pos + (int)sizeof(param_list->param_count) > stream_len ) {
+               EM_DEBUG_EXCEPTION("%d > stream_len", pos + sizeof(param_list->param_count));
+               EM_SAFE_FREE(param_list->byte_stream);
+               return NULL;
+       }
+
+       memcpy((param_list->byte_stream + pos), &param_list->param_count, sizeof(param_list->param_count));
+
+       pos += sizeof(long);
+       int index = 0, length = 0;
+
+       /* stream format */
+       /* | param1 length | (param1 data) | param2 length | (param2 data) | ... |*/
+       /* if param is 0 long, the param data is omitted */
+       for(index=0; index<param_list->param_count; index++) {
+               length = emipc_get_length(param_list->params[index]);
+               if (length < 0) {
+                       EM_DEBUG_EXCEPTION("index = %d, length = %d", index, length);
+                       EM_SAFE_FREE(param_list->byte_stream);
+                       return NULL;
+               }
+
+               if (pos + (int)sizeof(long) > stream_len) {
+                       EM_DEBUG_EXCEPTION("%d > stream_len", pos + sizeof(long));
+                       EM_SAFE_FREE(param_list->byte_stream);
+                       return NULL;
+               }
+               /* write param i length */
+               memcpy((param_list->byte_stream+pos), &length, sizeof(long));
+               pos += sizeof(long);
+
+               if (pos + length > stream_len) {
+                       EM_DEBUG_EXCEPTION("%d > stream_len", pos + length);
+                       EM_SAFE_FREE(param_list->byte_stream);
+                       return NULL;
+               }
+               /* write param i data if length is greater than 0 */
+               if( length > 0 ) {
+                       memcpy((param_list->byte_stream+pos), emipc_get_data(param_list->params[index]), length);
+                       pos += length;
+               }
+       }
+       *stream_length = stream_len;
+
+       EM_DEBUG_FUNC_END();
+       return param_list->byte_stream;
+}
+
+EXPORT_API int emipc_sum_param_list_length(emipc_param_list *param_list)
+{
+       int length = sizeof(long) * eSTREAM_DATA;
+       int index;
+       for (index = 0; index < param_list->param_count; index++) {
+               length += sizeof(long);
+               length += emipc_get_length(param_list->params[index]);
+       }
+       return length;
+}
+
+EXPORT_API bool emipc_add_param_to_param_list(emipc_param_list *param_list, void *data, int len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (emipc_set_param(&(param_list->params[param_list->param_count]), data, len)) {
+               param_list->param_count++;
+               EM_SAFE_FREE(param_list->byte_stream);
+               return true;
+       }
+       return false;
+}
+
+EXPORT_API void emipc_add_dynamic_param_to_param_list(emipc_param_list *param_list, void *data, int len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       emipc_set_dynamic_param(&(param_list->params[param_list->param_count]), data, len);
+       param_list->param_count++;
+       EM_SAFE_FREE(param_list->byte_stream);
+}
+
+EXPORT_API void *emipc_get_param_of_param_list(emipc_param_list *param_list, int index)
+{
+       EM_DEBUG_FUNC_BEGIN("index [%d]", index);
+       if (index < 0 || index >= param_list->param_count) {
+               EM_DEBUG_EXCEPTION("Index value is not valid");
+               return NULL;
+       }
+       return emipc_get_data(param_list->params[index]);
+}
+
+EXPORT_API int emipc_get_param_len_of_param_list(emipc_param_list *param_list, int index)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (index < 0 || index >= param_list->param_count) {
+               EM_DEBUG_EXCEPTION("Index valud is not valid");
+               return 0;
+       }
+       return emipc_get_length(param_list->params[index]);
+}
+
+
diff --git a/email-ipc/email-ipc-api/email-ipc-param.c b/email-ipc/email-ipc-api/email-ipc-param.c
new file mode 100755 (executable)
index 0000000..2d9543e
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <string.h>
+#include <stdlib.h>
+
+#include "email-ipc-param.h"
+#include "email-debug-log.h"
+
+EXPORT_API bool emipc_set_param(emipc_param *param, void *data, int len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!param) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               return false;
+       }
+
+       if (len == 0)
+               return true;
+       
+       param->data = (void *)malloc(len);
+       if (param->data == NULL) {
+               return false;
+       }
+       memset(param->data, 0x00, len);
+       memcpy(param->data, data, len);
+       param->length = len;
+       return true;
+}
+
+EXPORT_API void emipc_set_dynamic_param(emipc_param *param, void *data, int len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!param) {
+               EM_DEBUG_EXCEPTION("Invalid paramter");
+               return;
+       }
+
+       /* even take care of null data */
+       param->data = data;
+       param->length = len;
+}
+
+EXPORT_API void emipc_free_param(emipc_param param)
+{
+       EM_SAFE_FREE(param.data);
+}
+
+EXPORT_API int emipc_get_length(emipc_param param)
+{
+       return param.length;
+}
+
+EXPORT_API void *emipc_get_data(emipc_param param)
+{
+       return param.data;
+}
diff --git a/email-ipc/email-ipc-api/include/email-ipc-api-info.h b/email-ipc/email-ipc-api/include/email-ipc-api-info.h
new file mode 100755 (executable)
index 0000000..6a0b530
--- /dev/null
@@ -0,0 +1,234 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 _IPC_APIINFO_H_
+#define _IPC_APIINFO_H_
+
+#include <stdio.h>
+
+#include "email-ipc.h"
+#include "email-ipc-api-info.h"
+#include "email-ipc-param-list.h"
+
+typedef struct {
+       long api_id;
+       long response_id;
+       long app_id;
+       emipc_param_list *params[2];
+} emipc_email_api_info;
+
+/*EXPORT_API bool emipc_set_app_id_of_api_info(emipc_email_api_info *api_info, long app_id); */
+
+EXPORT_API bool emipc_deserialize_api_info(emipc_email_api_info *api_info, EPARAMETER_DIRECTION direction, void *stream);
+
+EXPORT_API unsigned char *emipc_serialize_api_info(emipc_email_api_info *api_info, EPARAMETER_DIRECTION direction, int *stream_len);
+
+/*EXPORT_API int emipc_get_stream_length_of_api_info(emipc_email_api_info *api_info, EPARAMETER_DIRECTION direction); */
+
+EXPORT_API void *emipc_get_parameters_of_api_info(emipc_email_api_info *api_info, EPARAMETER_DIRECTION direction);
+
+EXPORT_API bool emipc_free_api_info(emipc_email_api_info *api_info);
+
+/* don't insert empty line */
+#define EM_APIID_TO_STR(nAPIID) \
+       ({\
+               int id=nAPIID;\
+               const char* s=NULL;\
+               switch(id) {\
+                       case _EMAIL_API_ADD_ACCOUNT:\
+                                       s = "_EMAIL_API_ADD_ACCOUNT";\
+                                       break;\
+                       case _EMAIL_API_DELETE_ACCOUNT:\
+                                       s = "_EMAIL_API_DELETE_ACCOUNT";\
+                                       break;\
+                       case _EMAIL_API_UPDATE_ACCOUNT:\
+                                       s = "_EMAIL_API_UPDATE_ACCOUNT";\
+                                       break;\
+                       case _EMAIL_API_ADD_MAILBOX:\
+                                       s = "_EMAIL_API_ADD_MAILBOX";\
+                                       break;\
+                       case _EMAIL_API_DELETE_MAILBOX:\
+                                       s = "_EMAIL_API_DELETE_MAILBOX";\
+                                       break;\
+                       case _EMAIL_API_RENAME_MAILBOX:\
+                                       s = "_EMAIL_API_RENAME_MAILBOX";\
+                                       break;\
+                       case _EMAIL_API_SET_MAILBOX_TYPE:\
+                                       s = "_EMAIL_API_SET_MAILBOX_TYPE";\
+                                       break;\
+                       case _EMAIL_API_SET_LOCAL_MAILBOX:\
+                                       s = "_EMAIL_API_SET_LOCAL_MAILBOX";\
+                                       break;\
+                       case _EMAIL_API_SET_MAIL_SLOT_SIZE:\
+                                       s = "_EMAIL_API_SET_MAIL_SLOT_SIZE";\
+                                       break;\
+                       case _EMAIL_API_SEND_MAIL:\
+                                       s = "_EMAIL_API_SEND_MAIL";\
+                                       break;\
+                       case _EMAIL_API_GET_MAILBOX_COUNT:\
+                                       s = "_EMAIL_API_GET_MAILBOX_COUNT";\
+                                       break;\
+                       case _EMAIL_API_GET_MAILBOX_LIST:\
+                                       s = "_EMAIL_API_GET_MAILBOX_LIST";\
+                                       break;\
+                       case _EMAIL_API_GET_SUBMAILBOX_LIST:\
+                                       s = "_EMAIL_API_GET_SUBMAILBOX_LIST";\
+                                       break;\
+                       case _EMAIL_API_SYNC_HEADER:\
+                                       s = "_EMAIL_API_SYNC_HEADER";\
+                                       break;\
+                       case _EMAIL_API_DOWNLOAD_BODY:\
+                                       s = "_EMAIL_API_DOWNLOAD_BODY";\
+                                       break;\
+                       case _EMAIL_API_CLEAR_DATA:\
+                                       s = "_EMAIL_API_CLEAR_DATA";\
+                                       break;\
+                       case _EMAIL_API_DELETE_ALL_MAIL:\
+                                       s = "_EMAIL_API_DELETE_ALL_MAIL";\
+                                       break;\
+                       case _EMAIL_API_DELETE_MAIL:\
+                                       s = "_EMAIL_API_DELETE_MAIL";\
+                                       break;\
+                       case _EMAIL_API_MODIFY_MAIL_FLAG:\
+                                       s = "_EMAIL_API_MODIFY_MAIL_FLAG";\
+                                       break;\
+                       case _EMAIL_API_ADD_RULE:\
+                                       s = "_EMAIL_API_ADD_RULE";\
+                                       break;\
+                       case _EMAIL_API_GET_RULE:\
+                                       s = "_EMAIL_API_GET_RULE";\
+                                       break;\
+                       case _EMAIL_API_GET_RULE_LIST:\
+                                       s = "_EMAIL_API_GET_RULE";\
+                                       break;\
+                       case _EMAIL_API_FIND_RULE:\
+                                       s = "_EMAIL_API_FIND_RULE";\
+                                       break;\
+                       case _EMAIL_API_UPDATE_RULE:\
+                                       s = "_EMAIL_API_UPDATE_RULE";\
+                                       break;\
+                       case _EMAIL_API_DELETE_RULE:\
+                                       s = "_EMAIL_API_DELETE_RULE";\
+                                       break;\
+                       case _EMAIL_API_MOVE_MAIL:\
+                                       s = "_EMAIL_API_MOVE_MAIL";\
+                                       break;\
+                       case _EMAIL_API_MOVE_ALL_MAIL:\
+                                       s = "_EMAIL_API_MOVE_ALL_MAIL";\
+                                       break;\
+                       case _EMAIL_API_SET_FLAGS_FIELD:\
+                                       s = "_EMAIL_API_SET_FLAGS_FIELD";\
+                                       break;\
+                       case _EMAIL_API_ADD_MAIL:\
+                                       s = "_EMAIL_API_ADD_MAIL";\
+                                       break;\
+                       case _EMAIL_API_UPDATE_MAIL:\
+                                       s = "_EMAIL_API_UPDATE_MAIL";\
+                                       break;\
+                       case _EMAIL_API_MOVE_THREAD_TO_MAILBOX:\
+                                       s = "_EMAIL_API_MOVE_THREAD_TO_MAILBOX";\
+                                       break;\
+                       case _EMAIL_API_DELETE_THREAD:\
+                                       s = "_EMAIL_API_DELETE_THREAD";\
+                                       break;\
+                       case _EMAIL_API_MODIFY_SEEN_FLAG_OF_THREAD:\
+                                       s = "_EMAIL_API_MODIFY_SEEN_FLAG_OF_THREAD";\
+                                       break;\
+                       case _EMAIL_API_ADD_ATTACHMENT:\
+                                       s = "_EMAIL_API_ADD_ATTACHMENT";\
+                                       break;\
+                       case _EMAIL_API_GET_IMAP_MAILBOX_LIST:\
+                                       s = "_EMAIL_API_GET_IMAP_MAILBOX_LIST";\
+                                       break;\
+                       case _EMAIL_API_GET_ATTACHMENT:\
+                                       s = "_EMAIL_API_GET_ATTACHMENT";\
+                                       break;\
+                       case _EMAIL_API_DELETE_ATTACHMENT:\
+                                       s = "_EMAIL_API_DELETE_ATTACHMENT";\
+                                       break;\
+                       case _EMAIL_API_DOWNLOAD_ATTACHMENT:\
+                                       s = "_EMAIL_API_DOWNLOAD_ATTACHMENT";\
+                                       break;\
+                       case _EMAIL_API_GET_ACCOUNT_LIST:\
+                                       s = "_EMAIL_API_GET_ACCOUNT_LIST";\
+                                       break;\
+                       case _EMAIL_API_SEND_SAVED:\
+                                       s = "_EMAIL_API_SEND_SAVED";\
+                                       break;\
+                       case _EMAIL_API_CANCEL_JOB:\
+                                       s = "_EMAIL_API_CANCEL_JOB";\
+                                       break;\
+                       case _EMAIL_API_GET_PENDING_JOB:\
+                                       s = "_EMAIL_API_GET_PENDING_JOB";\
+                                       break;\
+                       case _EMAIL_API_NETWORK_GET_STATUS:\
+                                       s = "_EMAIL_API_NETWORK_GET_STATUS";\
+                                       break;\
+                       case _EMAIL_API_SEND_RETRY:\
+                                       s = "_EMAIL_API_SEND_RETRY";\
+                                       break;\
+                       case _EMAIL_API_VALIDATE_ACCOUNT :\
+                                       s = "_EMAIL_API_VALIDATE_ACCOUNT";\
+                                       break;\
+                       case _EMAIL_API_SEND_MAIL_CANCEL_JOB :\
+                                       s = "_EMAIL_API_SEND_MAIL_CANCEL_JOB";\
+                                       break;\
+                       case _EMAIL_API_SEARCH_MAIL_ON_SERVER :\
+                                       s = "_EMAIL_API_SEARCH_MAIL_ON_SERVER";\
+                                       break;\
+                       case _EMAIL_API_ADD_ACCOUNT_WITH_VALIDATION :\
+                                       s = "_EMAIL_API_ADD_ACCOUNT_WITH_VALIDATION";\
+                                       break;\
+                       case _EMAIL_API_BACKUP_ACCOUNTS :\
+                                       s = "_EMAIL_API_BACKUP_ACCOUNTS";\
+                                       break;\
+                       case _EMAIL_API_RESTORE_ACCOUNTS :\
+                                       s = "_EMAIL_API_RESTORE_ACCOUNTS";\
+                                       break;\
+                       case _EMAIL_API_PRINT_RECEIVING_EVENT_QUEUE :\
+                                       s = "_EMAIL_API_PRINT_RECEIVING_EVENT_QUEUE";\
+                                       break;\
+                       case _EMAIL_API_PING_SERVICE :\
+                                       s = "_EMAIL_API_PING_SERVICE";\
+                                       break;\
+                       case _EMAIL_API_UPDATE_NOTIFICATION_BAR_FOR_UNREAD_MAIL :\
+                                       s = "_EMAIL_API_UPDATE_NOTIFICATION_BAR_FOR_UNREAD_MAIL";\
+                                       break;\
+                       case _EMAIL_API_GET_PASSWORD_LENGTH_OF_ACCOUNT:\
+                                       s = "_EMAIL_API_GET_PASSWORD_LENGTH_OF_ACCOUNT";\
+                                       break;\
+                       case _EMAIL_API_SHOW_USER_MESSAGE:\
+                                       s = "_EMAIL_API_SHOW_USER_MESSAGE";\
+                                       break;\
+                       case _EMAIL_API_WRITE_MIME_FILE:\
+                                       s = "_EMAIL_API_WRITE_MIME_FILE";\
+                                       break;\
+                       default : \
+                                       s = "UNKNOWN_APIID";\
+               }\
+               s;\
+       })
+
+
+#endif /* _IPC_APIINFO_H_ */
+
+
diff --git a/email-ipc/email-ipc-api/include/email-ipc-param-list.h b/email-ipc/email-ipc-api/include/email-ipc-param-list.h
new file mode 100755 (executable)
index 0000000..4706596
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 _IPC_PARAMLIST_H_
+#define _IPC_PARAMLIST_H_
+
+#include "email-ipc-param.h"
+#include "email-types.h"
+
+typedef enum {
+       eSTREAM_APIID = 0,
+       eSTREAM_RESID,
+       eSTREAM_APPID,
+       eSTREAM_COUNT,
+       eSTREAM_DATA,
+       eSTREAM_MAX
+}IPC_STREAM_INFO;
+
+typedef struct {
+       int param_count;
+       emipc_param params[10];
+       unsigned char *byte_stream;
+} emipc_param_list;
+
+EXPORT_API emipc_param_list *emipc_create_param_list();
+
+EXPORT_API bool emipc_destroy_param_list(emipc_param_list *param_list);
+
+EXPORT_API bool emipc_parse_stream_of_param_list(emipc_param_list *param_list, void *stream_data);
+
+EXPORT_API unsigned char *emipc_serialize_param_list(emipc_param_list *param_list, int *stream_length);
+
+EXPORT_API int emipc_sum_param_list_length (emipc_param_list *param_list);
+
+EXPORT_API bool emipc_add_param_to_param_list(emipc_param_list *param_list, void *data, int len);
+
+EXPORT_API void emipc_add_dynamic_param_to_param_list(emipc_param_list *param_list, void *data, int len);
+
+EXPORT_API void *emipc_get_param_of_param_list(emipc_param_list *param_list, int index);
+
+EXPORT_API int emipc_get_param_len_of_param_list(emipc_param_list *param_list, int index);
+
+#endif /* _IPC_PARAMLIST_H_ */
+
+
diff --git a/email-ipc/email-ipc-api/include/email-ipc-param.h b/email-ipc/email-ipc-api/include/email-ipc-param.h
new file mode 100755 (executable)
index 0000000..7e619e1
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 _IPC_PARAM_H_
+#define _IPC_PARAM_H_
+
+#include "email-types.h"
+
+typedef struct {
+       int length;
+       void *data;
+} emipc_param;
+
+EXPORT_API bool emipc_set_param(emipc_param *param, void *data, int len);
+
+EXPORT_API void emipc_set_dynamic_param(emipc_param *param, void *data, int len);
+
+EXPORT_API void emipc_free_param(emipc_param param);
+
+EXPORT_API int emipc_get_length(emipc_param param);
+
+EXPORT_API void *emipc_get_data(emipc_param param);
+
+#endif /* _IPC_PARAM_H_ */
+
+
diff --git a/email-ipc/email-ipc-build.c b/email-ipc/email-ipc-build.c
new file mode 100755 (executable)
index 0000000..3f8d541
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <stdlib.h>
+#include <stdarg.h>
+
+#include "email-ipc-build.h"
+
+
+
diff --git a/email-ipc/email-ipc-proxy.c b/email-ipc/email-ipc-proxy.c
new file mode 100755 (executable)
index 0000000..ed11691
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 "email-ipc-build.h"
+#include "email-ipc.h"
+#include "email-ipc-api-info.h"
+#include "email-ipc-param-list.h"
+#include "email-ipc-socket.h"
+#include "email-proxy-main.h"
+
+#include "email-debug-log.h"
+#include "email-api.h"
+#include "email-types.h"
+#include "email-internal-types.h"
+#include "email-dbus-activation.h"
+
+EXPORT_API int emipc_initialize_proxy()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       int err = EMAIL_ERROR_NONE;
+
+       err = emipc_launch_email_service();
+       EM_DEBUG_LOG("emipc_launch_email_service returns [%d]", err);
+
+       err = emipc_initialize_proxy_main();
+       EM_DEBUG_LOG("emipc_initialize_proxy_main returns [%d]", err);
+
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
+EXPORT_API int emipc_finalize_proxy()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       return emipc_finalize_proxy_main();
+}
+
+EXPORT_API int emipc_execute_proxy_api(HIPC_API api)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret;
+       int err = EMAIL_ERROR_NONE;
+       emipc_email_api_info *api_info = (emipc_email_api_info *)api;
+
+       EM_DEBUG_LOG("API [%p]", api_info);
+
+       if(api_info == NULL) {
+               EM_DEBUG_EXCEPTION("EMAIL_ERROR_INVALID_PARAM");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       EM_DEBUG_LOG("APIID [%s], ResponseID [%d], APPID[%d]",
+                               EM_APIID_TO_STR(api_info->api_id), api_info->response_id, api_info->app_id);
+
+       ret = emipc_execute_api_of_proxy_main(api_info);
+
+       /* connection retry */
+       if (!ret) {
+               EM_DEBUG_LOG("Connection retry");
+               emipc_finalize_proxy();
+
+               err = emipc_initialize_proxy();
+               if (err != EMAIL_ERROR_NONE) {
+                       EM_DEBUG_EXCEPTION("Failed to open the socket : [%d]", err);
+                       err = EMAIL_ERROR_CONNECTION_FAILURE;
+                       goto FINISH_OFF;
+               }
+
+               ret = emipc_execute_api_of_proxy_main(api_info);
+               if (!ret) {
+                       EM_DEBUG_EXCEPTION("emipc_proxy_main : emipc_execute_api failed [%d]", err);
+                       err = EMAIL_ERROR_CONNECTION_FAILURE;
+                       goto FINISH_OFF;
+               }
+       }
+
+FINISH_OFF:
+       EM_DEBUG_FUNC_END("err [%d]", err);
+       return err;
+}
+
diff --git a/email-ipc/email-ipc-stub.c b/email-ipc/email-ipc-stub.c
new file mode 100755 (executable)
index 0000000..2155050
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 "email-ipc.h"
+#include "email-ipc-build.h"
+#include "email-stub-main.h"
+
+#include "email-debug-log.h"
+
+EXPORT_API bool emipc_initialize_stub(PFN_EXECUTE_API api_mapper)
+{
+       EM_DEBUG_LOG("[IPCLib] ipcEmailStub_Initialize ");
+
+       return emipc_initialize_stub_main(api_mapper);
+}
+
+EXPORT_API bool emipc_finalize_stub()
+{
+       emipc_finalize_stub_main();
+       return true;
+}
+
+EXPORT_API bool emipc_execute_stub_api(HIPC_API api)
+{
+       EM_DEBUG_LOG("ipcEmailStub_ExecuteAPI [%x]", api);
+       emipc_email_api_info *api_info = (emipc_email_api_info *)api;
+       if (api_info == NULL)
+               return false;
+
+       return emipc_execute_api_stub_to_proxy(api_info);
+}    
+
diff --git a/email-ipc/email-proxy/email-proxy-callback-info.c b/email-ipc/email-proxy/email-proxy-callback-info.c
new file mode 100755 (executable)
index 0000000..4f28ed6
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 "email-proxy-callback-info.h"
+
+EXPORT_API bool emipc_set_cb_info_value(emipc_email_cb_info *cb_info, int api_id, void *fn_callback)
+{
+       cb_info->api_id = api_id;
+       cb_info->fn_callback = fn_callback;
+       return true;
+}
diff --git a/email-ipc/email-proxy/email-proxy-main.c b/email-ipc/email-proxy/email-proxy-main.c
new file mode 100755 (executable)
index 0000000..5ba193e
--- /dev/null
@@ -0,0 +1,117 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <unistd.h>
+#include <pthread.h>
+#include <malloc.h>
+
+#include "email-ipc.h"
+#include "email-ipc-build.h"
+#include "email-proxy-main.h"
+#include "email-proxy-socket.h"
+#include "email-proxy-callback-info.h"
+
+#include "email-debug-log.h"
+
+
+EXPORT_API int emipc_initialize_proxy_main()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int sock_fd = 0;
+
+       sock_fd = emipc_get_proxy_socket_id();
+       
+       if (sock_fd) {
+               EM_DEBUG_LOG("Socket already initialized");
+               return EMAIL_ERROR_IPC_ALREADY_INITIALIZED;
+       }
+       
+       if (!emipc_start_proxy_socket()) {
+               EM_DEBUG_EXCEPTION("Socket start failed");
+               return EMAIL_ERROR_IPC_CONNECTION_FAILURE;
+       }
+       
+       EM_DEBUG_LOG("Socket ID : %d", emipc_get_proxy_socket_id());
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE; 
+}
+
+EXPORT_API int emipc_finalize_proxy_main()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (!emipc_end_proxy_socket()) {
+               EM_DEBUG_EXCEPTION("emipc_finalize_proxy_main failed");
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return EMAIL_ERROR_NONE;
+}
+
+EXPORT_API bool emipc_execute_api_of_proxy_main(emipc_email_api_info *api_info)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       int ret;
+       unsigned char *in_stream = NULL;
+       int length = 0;
+       bool result = false;
+       int sending_bytes;
+
+       if (!api_info) {
+               EM_DEBUG_EXCEPTION("Invalid Parameter");
+               return false;
+       }
+
+       in_stream = emipc_serialize_api_info(api_info, ePARAMETER_IN, &length);
+       if( !in_stream ) {
+               EM_DEBUG_EXCEPTION("NULL stream");
+               return false;
+       }
+
+       sending_bytes = emipc_send_proxy_socket(in_stream, length);
+
+       EM_DEBUG_LOG("Proxy=>stub sending %d byte.", sending_bytes);
+
+       if (sending_bytes > 0) {
+#ifdef IPCLIB_STREAM_TRACE_ON
+               int index = 0;
+               for (index=0;index<length;index++) 
+                       EM_DEBUG_LOG("in_stream[index] : [%x]", in_stream[index]);
+#endif
+               char *ipc_buf = NULL;
+
+               ret = emipc_recv_proxy_socket(&ipc_buf);
+       
+               EM_DEBUG_LOG("Recv length : %d", ret);
+
+               if (ret > 0)
+                       result = emipc_deserialize_api_info(api_info, ePARAMETER_OUT, ipc_buf);
+               else
+                       result = false; 
+
+               EM_SAFE_FREE(ipc_buf);
+       }
+       
+       EM_DEBUG_FUNC_END();
+       return result;          
+}
diff --git a/email-ipc/email-proxy/email-proxy-socket.c b/email-ipc/email-proxy/email-proxy-socket.c
new file mode 100644 (file)
index 0000000..b4d8a8a
--- /dev/null
@@ -0,0 +1,210 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 <unistd.h>
+#include <sys/select.h>
+
+#include "email-ipc-build.h"
+#include "email-proxy-socket.h"
+#include "email-ipc-socket.h"
+
+#include "email-debug-log.h"
+#include "email-internal-types.h"
+#include "email-utilities.h"
+#include <errno.h>
+#include <glib.h>
+#include <pthread.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+typedef struct {
+       pid_t pid;
+       pthread_t tid;
+       int socket_fd;
+} thread_socket_t;
+
+GList *socket_head = NULL;
+pthread_mutex_t proxy_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+EXPORT_API bool emipc_start_proxy_socket()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int ret = true;
+       int socket_fd = 0;
+
+       ret = emipc_init_email_socket(&socket_fd);
+       if (!ret) {
+               EM_DEBUG_EXCEPTION("emipc_init_email_socket failed");
+               return false;
+       }
+
+       ret = emipc_connect_email_socket(socket_fd);
+       if( !ret ) {
+               EM_DEBUG_EXCEPTION("emipc_connect_email_socket failed");
+               return false;
+       }
+
+       thread_socket_t* cur = (thread_socket_t*) em_malloc(sizeof(thread_socket_t));
+       if(!cur) {
+               EM_DEBUG_EXCEPTION("em_malloc failed");
+               return false;
+       }
+
+       /* add a socket */
+       cur->pid = getpid();
+       cur->tid = pthread_self();
+       cur->socket_fd = socket_fd;
+
+       ENTER_CRITICAL_SECTION(proxy_mutex);
+       socket_head = g_list_prepend(socket_head, cur);
+       LEAVE_CRITICAL_SECTION(proxy_mutex);
+
+       return true;
+}
+
+EXPORT_API bool emipc_end_proxy_socket()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       EM_DEBUG_LOG("[IPCLib] emipc_end_proxy_socket_fd");
+
+       pid_t pid = getpid();
+
+       ENTER_CRITICAL_SECTION(proxy_mutex);
+       GList *cur = socket_head;
+       while( cur ) {
+               thread_socket_t* cur_socket = g_list_nth_data(cur,0);
+
+               /* close all sockets of the pid */
+               if( pid == cur_socket->pid ) {
+                       emipc_close_email_socket(&cur_socket->socket_fd);
+                       EM_SAFE_FREE(cur_socket);
+                       GList *del = cur;
+                       cur = g_list_next(cur);
+                       socket_head = g_list_remove_link(socket_head, del);
+                       continue;
+               }
+
+               cur = g_list_next(cur);
+       }
+       LEAVE_CRITICAL_SECTION(proxy_mutex);
+
+       return true;
+}
+
+/* return result of emipc_send_email_socket
+ * EMAIL_ERROR_IPC_SOCKET_FAILURE, when no IPC connection */
+EXPORT_API int emipc_send_proxy_socket(unsigned char *data, int len)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int socket_fd = emipc_get_proxy_socket_id();
+
+       /* if thread socket is not created */
+       if (!socket_fd) {
+               int ret = emipc_start_proxy_socket();
+               if(!ret ) {
+                       EM_DEBUG_EXCEPTION("[IPCLib] emipc_send_proxy_socket not connected");
+                       return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+               }
+               socket_fd = emipc_get_proxy_socket_id();
+       }
+
+       int send_len = emipc_send_email_socket(socket_fd, data, len);
+       if (send_len == 0) {
+               EM_DEBUG_EXCEPTION("[IPCLib] server closed connection %x", socket_fd);
+               emipc_end_proxy_socket();
+       }
+
+       return send_len;
+}
+
+EXPORT_API int emipc_get_proxy_socket_id()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       pthread_t tid = pthread_self();
+       int socket_fd = 0;
+
+       ENTER_CRITICAL_SECTION(proxy_mutex);
+       GList *cur = socket_head;
+       /* need to acquire lock */
+       for( ; cur ; cur = g_list_next(cur) ) {
+               thread_socket_t* cur_socket = g_list_nth_data(cur,0);
+               if( pthread_equal(tid, cur_socket->tid) ) {
+                       socket_fd = cur_socket->socket_fd;
+                       break;
+               }
+       }
+       LEAVE_CRITICAL_SECTION(proxy_mutex);
+       EM_DEBUG_LOG("tid %d, socket_fd %d", tid, socket_fd);
+       return socket_fd;
+}
+
+/* return true, when event occurred
+ * false, when select error
+ */
+static bool wait_for_reply (int fd)
+{
+       fd_set fds;
+
+       if (fd == 0) {
+               EM_DEBUG_EXCEPTION("Invalid file description : [%d]", fd);
+               return false;
+       }
+
+       FD_ZERO(&fds);
+       FD_SET(fd, &fds);
+
+       if (select(fd + 1, &fds, NULL, NULL, NULL) == -1) {
+               EM_DEBUG_EXCEPTION("[IPCLib] select: %s", strerror(errno) );
+               return false;
+       }
+
+       if (FD_ISSET(fd, &fds)) return true;
+
+       return false;
+}
+
+
+/* return result of emipc_recv_email_socket
+ * EMAIL_ERROR_IPC_SOCKET_FAILURE, when no IPC connection, or wrong fd */
+EXPORT_API int emipc_recv_proxy_socket(char **data)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       int socket_fd = emipc_get_proxy_socket_id();
+       if (!socket_fd) {
+               EM_DEBUG_EXCEPTION("[IPCLib] proxy_socket_fd[%p] is not available or disconnected", socket_fd);
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       if( !wait_for_reply(socket_fd) ) {
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       int recv_len = emipc_recv_email_socket(socket_fd, data);
+       if (recv_len == 0) {
+               EM_DEBUG_EXCEPTION("[IPCLib] server closed connection %x", socket_fd);
+               emipc_end_proxy_socket();
+       }
+
+       return recv_len;
+}
+
diff --git a/email-ipc/email-proxy/include/email-proxy-callback-info.h b/email-ipc/email-proxy/include/email-proxy-callback-info.h
new file mode 100755 (executable)
index 0000000..dbe8642
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 _IPC_CALLBACK_INFO_H_
+#define _IPC_CALLBACK_INFO_H_
+
+#include "email-types.h"
+
+typedef struct {
+       int api_id;
+       void *fn_callback;
+} emipc_email_cb_info;
+
+
+#endif /* _IPC_CALLBACK_INFO_H_ */
+
+
diff --git a/email-ipc/email-proxy/include/email-proxy-main.h b/email-ipc/email-proxy/include/email-proxy-main.h
new file mode 100755 (executable)
index 0000000..b071fd4
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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        _IPC_PROXY_MAIN_H_
+#define        _IPC_PROXY_MAIN_H_
+
+#include "email-ipc-api-info.h"
+#include "email-types.h"
+
+EXPORT_API int emipc_initialize_proxy_main();
+
+EXPORT_API int emipc_finalize_proxy_main();
+
+EXPORT_API bool emipc_execute_api_of_proxy_main(emipc_email_api_info *api_info);
+
+EXPORT_API bool emipc_dispatch_proxy_main();
+
+#endif/* _IPC_PROXY_MAIN_H_ */
+
diff --git a/email-ipc/email-proxy/include/email-proxy-socket.h b/email-ipc/email-proxy/include/email-proxy-socket.h
new file mode 100755 (executable)
index 0000000..cf2244b
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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        _IPC_PROXY_SOCKET_H_
+#define        _IPC_PROXY_SOCKET_H_
+
+#include "email-types.h"
+
+EXPORT_API bool emipc_start_proxy_socket();
+
+EXPORT_API bool emipc_end_proxy_socket();
+
+EXPORT_API int emipc_send_proxy_socket(unsigned char *data, int len);
+
+EXPORT_API int emipc_get_proxy_socket_id();
+
+EXPORT_API int emipc_recv_proxy_socket(char **data);
+
+#endif /* _IPC_PROXY_SOCKET_H_ */
+
+
diff --git a/email-ipc/email-socket/email-ipc-socket.c b/email-ipc/email-socket/email-ipc-socket.c
new file mode 100755 (executable)
index 0000000..55976df
--- /dev/null
@@ -0,0 +1,281 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+*
+* 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 "email-ipc-socket.h"
+#include "email-ipc-build.h"
+
+#include "email-debug-log.h"
+#include "email-types.h"
+
+#include <glib.h>
+
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <malloc.h>
+
+#include <errno.h>
+#include <unistd.h>
+
+#include <systemd/sd-daemon.h>
+
+EXPORT_API bool emipc_init_email_socket(int *fd)
+{
+       bool ret = true;
+
+       *fd = socket(AF_UNIX, SOCK_STREAM, 0);
+
+       if (*fd < 0) {
+               EM_DEBUG_EXCEPTION("socket creation fails!!!: %s", strerror(errno));
+               ret = false;
+       }
+
+       EM_DEBUG_LOG("Socket fd = %d", *fd);
+
+       return ret;
+}
+
+/*  Close */
+EXPORT_API void emipc_close_email_socket(int* fd)
+{
+       EM_DEBUG_LOG("fd %d removal done", *fd);
+       close(*fd);
+       *fd = 0;
+}
+
+/* returns positive write length,
+ * 0, when connection is closed
+ * -1, when send error */
+static int emipc_writen(int fd, const char *buf, int len)
+{
+       int length = len;
+       int passed_len = 0;
+
+       while (length > 0) {
+               passed_len = send(fd, (const void *)buf, length, MSG_NOSIGNAL);
+               if (passed_len == -1) {
+                       EM_DEBUG_LOG("write : %s", EM_STRERROR(errno));
+                       if (errno == EINTR) continue;
+                       else if (errno == EPIPE) return 0; /* connection closed */
+                       else return passed_len; /* -1 */
+               } else if (passed_len == 0)
+                       break;
+               length -= passed_len;
+               buf += passed_len;
+       }
+       return (len - length);
+}
+
+/* returns positive value, when write success,
+ * 0, when socket connection is broken,
+ * EMAIL_ERROR_IPC_SOCKET_FAILURE, when write failure,
+ * EMAIL_ERROR_INVALID_PARAM, when wrong parameter */
+EXPORT_API int emipc_send_email_socket(int fd, unsigned char *buf, int len)
+{
+       EM_DEBUG_FUNC_BEGIN("fd [%d], buffer [%p], buf_len [%d]", fd, buf, len);
+
+       if (!buf || len <= 0) {
+               EM_DEBUG_EXCEPTION("No data to send %p, %d", buf, len);
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       EM_DEBUG_LOG("Sending %dB data to [fd = %d]", len, fd);
+
+       int write_len = emipc_writen(fd, (char*) buf, len);
+       if ( write_len != len) {
+               if ( write_len == 0 ) return 0;
+               EM_DEBUG_LOG("WARNING: buf_size [%d] != write_len[%d]", len, write_len);
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+       EM_DEBUG_FUNC_END();
+       return write_len;
+}
+
+static int emipc_readn(int fd, char *buf, int len)
+{
+       int length = len;
+       int read_len = 0;
+
+       while (length > 0) {
+               read_len = read(fd, (void *)buf, length);
+               if (read_len < 0) {
+                       EM_DEBUG_EXCEPTION("Read : %s", EM_STRERROR(errno));
+                       if (errno == EINTR) continue;
+                       return read_len;
+               } else if (read_len == 0)
+                       break;
+
+               length -= read_len;
+               buf += read_len;
+       }
+       return (len-length);
+}
+
+/* returns positive value when read success,
+ * 0, when socket is closed
+ * EMAIL_ERROR_IPC_SOCKET_FAILURE, when read failed
+ * EMAIL_ERROR_INVALID_PARAM when wrong parameter */
+EXPORT_API int emipc_recv_email_socket(int fd, char **buf)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!buf) {
+               EM_DEBUG_LOG("Buffer must not null");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       int read_len = 0;
+       /* read the size of message. note that ioctl is non-blocking */
+       if (ioctl(fd, FIONREAD, &read_len)) {
+               EM_DEBUG_EXCEPTION("ioctl: %s", strerror(errno));
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+       /* when server or client closed socket */
+       if ( read_len == 0 ) {
+               EM_DEBUG_LOG("[IPC Socket] connection is closed");
+               return 0;
+       }
+
+       *buf = (char *) malloc(read_len);
+       if (*buf == NULL) {
+               EM_DEBUG_EXCEPTION("Malloc failed");
+               return EMAIL_ERROR_OUT_OF_MEMORY;
+       }
+       memset(*buf, 0x00, read_len);
+
+       EM_DEBUG_LOG("[IPC Socket] Receiving [%d] bytes", read_len);
+       int len = emipc_readn(fd, *buf, read_len);
+       if (read_len != len) {
+               EM_SAFE_FREE(*buf);
+               EM_DEBUG_LOG("WARNING: buf_size [%d] != read_len[%d]", read_len, len);
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       EM_DEBUG_LOG("[IPC Socket] Receiving [%d] bytes Completed", len);
+
+       return len;
+}
+
+EXPORT_API int emipc_accept_email_socket(int fd)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (fd == -1) {
+               EM_DEBUG_LOG("Server_socket not init");
+               return EMAIL_ERROR_INVALID_PARAM;
+       }
+
+       struct sockaddr_un remote;
+       int remote_len = sizeof(remote);
+       int client_fd = accept(fd, (struct sockaddr *)&remote, (socklen_t*) &remote_len);
+       if (client_fd == -1) {
+               EM_DEBUG_LOG("accept: %s", EM_STRERROR(errno));
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       EM_DEBUG_LOG("%d is added", client_fd);
+
+       EM_DEBUG_FUNC_END();
+       return client_fd;
+}
+
+EXPORT_API int emipc_open_email_socket(int fd, const char *path)
+{
+       EM_DEBUG_FUNC_BEGIN("path [%s]", path);
+       int sock_fd = 0;
+
+       if (strcmp(path, EM_SOCKET_PATH) == 0 &&
+               sd_listen_fds(1) == 1 &&
+               sd_is_socket_unix(SD_LISTEN_FDS_START, SOCK_STREAM, -1, EM_SOCKET_PATH, 0) > 0) {
+               close(fd);
+               sock_fd = SD_LISTEN_FDS_START + 0;
+               return sock_fd;
+       }
+
+       if (!path || EM_SAFE_STRLEN(path) > 108) {
+               EM_DEBUG_LOG("Path is null");
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       if (fd <= 0) {
+               EM_DEBUG_LOG("Socket not created %d", fd);
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       struct sockaddr_un local;
+       local.sun_family = AF_UNIX;
+       strcpy(local.sun_path, path);
+       unlink(local.sun_path);
+
+       int len = EM_SAFE_STRLEN(local.sun_path) + sizeof(local.sun_family);
+
+       if (bind(fd, (struct sockaddr *)&local, len) == -1) {
+               EM_DEBUG_LOG("bind: %s", EM_STRERROR(errno));
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       /**
+        * determine permission of socket file
+        *
+        *  - S_IRWXU : for user, allow read and write and execute
+        *  - S_IRWXG : for group, allow read and write and execute
+        *  - S_IRWXO : for other, allow read and write and execute
+        *
+        *  - S_IRUSR, S_IWUSR, S_IXUSR : for user, allow only read, write, execute respectively
+        *  - S_IRGRP, S_IWGRP, S_IXGRP : for group, allow only read, write, execute respectively
+        *  - S_IROTH, S_IWOTH, S_IXOTH : for other, allow only read, write, execute respectively
+        */
+       mode_t sock_mode = (S_IRWXU | S_IRWXG | S_IRWXO); /*  has 777 permission */
+
+       if (chmod(path, sock_mode) == -1) {
+               EM_DEBUG_LOG("chmod: %s", EM_STRERROR(errno));
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       if (listen(fd, 10) == -1) {
+               EM_DEBUG_LOG("listen: %s", EM_STRERROR(errno));
+               return EMAIL_ERROR_IPC_SOCKET_FAILURE;
+       }
+
+       EM_DEBUG_FUNC_END();
+       return fd;
+}
+
+EXPORT_API bool emipc_connect_email_socket(int fd)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       struct sockaddr_un server;
+       server.sun_family = AF_UNIX;
+       strcpy(server.sun_path, EM_SOCKET_PATH);
+
+       int len = EM_SAFE_STRLEN(server.sun_path) + sizeof(server.sun_family);
+
+       if (connect(fd, (struct sockaddr *)&server, len) == -1) {
+               EM_DEBUG_LOG("Cannot connect server %s", EM_STRERROR(errno));
+               return false;
+       }
+
+       return true;
+}
+
diff --git a/email-ipc/email-socket/include/email-ipc-socket.h b/email-ipc/email-socket/include/email-ipc-socket.h
new file mode 100755 (executable)
index 0000000..10bfff7
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 _IPC_SOCKET_H_ 
+#define _IPC_SOCKET_H_ 
+
+#include "email-types.h"
+
+#define SOCKET_IP              "127.0.0.1"
+#define SOCKET_PORT            9000
+
+#define BUF_SIZE                       204800
+#define OPT_USEC               100000
+
+
+#define EM_SOCKET_PATH "/tmp/.emailfw_socket"
+
+EXPORT_API bool emipc_init_email_socket(int *fd);
+
+EXPORT_API void emipc_close_email_socket(int *fd);
+
+EXPORT_API int emipc_send_email_socket(int fd, unsigned char *buf, int len);
+
+EXPORT_API int emipc_recv_email_socket(int fd, char **buf);
+
+EXPORT_API int emipc_accept_email_socket(int fd);
+
+EXPORT_API int emipc_open_email_socket(int fd, const char *path);
+
+EXPORT_API bool emipc_connect_email_socket(int fd);
+
+#endif /*  _IPC_SOCKET_H_               */
+
+
+
+       
+
+
diff --git a/email-ipc/email-stub/email-stub-main.c b/email-ipc/email-stub/email-stub-main.c
new file mode 100755 (executable)
index 0000000..523f762
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <glib.h>
+
+#include "email-stub-main.h"
+#include "email-ipc.h"
+#include "email-ipc-param-list.h"
+#include "email-ipc-build.h"
+#include "email-dbus-activation.h"
+#include "email-stub-socket.h"
+
+#include "email-api.h"
+#include "email-debug-log.h"
+
+static bool stub_socket = false;
+static PFN_EXECUTE_API this_fn_api_mapper = NULL;
+
+EXPORT_API bool emipc_initialize_stub_main(PFN_EXECUTE_API fn_api_mapper)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (!fn_api_mapper) {
+               EM_DEBUG_EXCEPTION("Invalid Param");
+               return false;
+       }
+
+       this_fn_api_mapper = fn_api_mapper;
+
+       /* Initialize the socket */
+       stub_socket = emipc_start_stub_socket();
+       if (!stub_socket) {
+               EM_DEBUG_EXCEPTION("Socket did not create");
+               return false;
+       }
+
+       emipc_init_dbus_connection();
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+EXPORT_API bool emipc_finalize_stub_main()
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       if (stub_socket) {
+               emipc_end_stub_socket();
+               stub_socket = false;
+       }
+       
+       if (this_fn_api_mapper)
+               this_fn_api_mapper = NULL;
+               
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+EXPORT_API bool emipc_execute_api_proxy_to_stub(emipc_email_api_info *api_info)
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (!api_info) {
+               EM_DEBUG_EXCEPTION("Invalid Param");
+               return false;
+       }
+       
+       if (this_fn_api_mapper) {
+               this_fn_api_mapper(api_info);
+       }
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
+
+EXPORT_API bool emipc_execute_api_stub_to_proxy(emipc_email_api_info *api_info)
+{
+       EM_DEBUG_FUNC_BEGIN("api_info [%p]", api_info);
+       EM_IF_NULL_RETURN_VALUE(api_info, false);
+       EM_DEBUG_LOG("APIID [%s], response Socket ID [%d], APPID [%d]",
+                               EM_APIID_TO_STR(api_info->api_id), api_info->response_id, api_info->app_id);
+       
+       unsigned char *stream = NULL;
+       int stream_length = 0;
+       
+       stream = emipc_serialize_api_info(api_info, ePARAMETER_OUT, &stream_length);
+       EM_DEBUG_LOG("Stub => Proxy Sending %dB", stream_length);
+
+       emipc_send_stub_socket(api_info->response_id, stream, stream_length);
+       
+#ifdef IPCLIB_STREAM_TRACE_ON
+       int index = 0;
+       for (index = 0; index < stream_length; index++)
+               EM_DEBUG_LOG("Stream[index] : [%d]", stream[index]);
+#endif
+
+       EM_DEBUG_FUNC_END();
+       return true;
+}
diff --git a/email-ipc/email-stub/email-stub-socket.c b/email-ipc/email-stub/email-stub-socket.c
new file mode 100755 (executable)
index 0000000..2a788db
--- /dev/null
@@ -0,0 +1,216 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <malloc.h>
+#include <sys/epoll.h>
+#include <pthread.h>
+
+#include "email-ipc-build.h"
+#include "email-ipc-api-info.h"
+#include "email-ipc-socket.h"
+#include "email-stub-task.h"
+#include "email-stub-task-manager.h"
+#include "email-stub-socket.h"
+
+#include "email-debug-log.h"
+
+#define MAX_EPOLL_EVENT 50
+
+static int stub_socket = 0;
+static pthread_t stub_socket_thread = 0;
+static bool stop_thread = false;
+
+static void *emipc_stub_socket_thread_proc();
+
+EXPORT_API bool emipc_start_stub_socket()
+{
+       bool ret = true;
+
+       ret = emipc_init_email_socket(&stub_socket);
+       if (!ret) {
+               EM_DEBUG_EXCEPTION("emipc_init_email_socket failed");
+               return ret;
+       }
+
+       ret = emipc_start_stub_socket_thread();
+       if (!ret) {
+               EM_DEBUG_EXCEPTION("emipc_start_stub_socket_thread failed");
+               return ret;
+       }
+
+       ret = emipc_start_task_thread();
+       if (!ret) {
+               EM_DEBUG_EXCEPTION("emipc_start_task_thread failed");
+               return ret;
+       }
+
+       return ret;
+}
+
+EXPORT_API bool emipc_start_stub_socket_thread()
+{
+       EM_DEBUG_LOG("[IPCLib] emipc_email_stub_socket_thread start");
+       if (stub_socket_thread)
+               return true;
+               
+       pthread_attr_t thread_attr;
+       pthread_attr_init(&thread_attr);
+       pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
+       if (pthread_create(&stub_socket_thread, &thread_attr, &emipc_stub_socket_thread_proc, NULL) != 0) {
+               EM_DEBUG_EXCEPTION("[IPCLib] emipc_start_stub_socket_thread() - fail to create a thread");
+               return false;
+       }
+       return true;
+}
+
+EXPORT_API bool emipc_stop_stub_socket_thread()
+{
+       if (stub_socket_thread)
+               stop_thread = true;
+
+       return true;
+}
+
+static void *emipc_stub_socket_thread_proc()
+{
+       emipc_wait_for_ipc_request();
+       stub_socket_thread = 0;
+       return NULL;
+}
+
+EXPORT_API void emipc_wait_for_ipc_request()
+{
+       struct epoll_event ev = {0};
+       struct epoll_event events[MAX_EPOLL_EVENT] = {{0}, };
+       int epfd = 0;
+       int event_num = 0;
+
+       if (!stub_socket) {
+               EM_DEBUG_EXCEPTION("Server Socket is not initialized");
+               return;
+       }
+
+       emipc_open_email_socket(stub_socket, EM_SOCKET_PATH);
+       
+       epfd = epoll_create(MAX_EPOLL_EVENT);
+       if (epfd < 0) {
+               EM_DEBUG_EXCEPTION("epoll_ctl: %s[%d]", strerror(errno), errno);
+               EM_DEBUG_CRITICAL_EXCEPTION("epoll_create: %s[%d]", strerror(errno), errno);
+               abort();
+       }
+
+       ev.events = EPOLLIN;
+       ev.data.fd = stub_socket;
+       
+       if (epoll_ctl(epfd, EPOLL_CTL_ADD, stub_socket, &ev) == -1) {
+               EM_DEBUG_EXCEPTION("epoll_ctl: %s[%d]", strerror(errno), errno);
+               EM_DEBUG_CRITICAL_EXCEPTION("epoll_ctl:%s[%d]", strerror(errno), errno);        
+       }
+       while (1) {
+               int i = 0;
+
+               event_num = epoll_wait(epfd, events, MAX_EPOLL_EVENT, -1);
+               
+               if (event_num == -1) {
+                       EM_DEBUG_EXCEPTION("epoll_wait: %s[%d]", strerror(errno), errno);
+                       EM_DEBUG_CRITICAL_EXCEPTION("epoll_wait: %s[%d]", strerror(errno), errno);
+                       if (errno == EINTR) continue; /* resume when interrupted system call*/
+                       else abort();
+               } else {
+                       for (i = 0; i < event_num; i++) {
+                               int event_fd = events[i].data.fd;
+
+                               if (event_fd == stub_socket) { /*  if it is socket connection request */
+                                       int cfd = emipc_accept_email_socket(stub_socket);
+                                       if (cfd < 0) {
+                                               EM_DEBUG_EXCEPTION("accept error: %s[%d]", strerror(errno), errno);
+                                               EM_DEBUG_CRITICAL_EXCEPTION("accept error: %s[%d]", strerror(errno), errno);
+                                               /*  abort(); */
+                                       }
+                                       ev.events = EPOLLIN;
+                                       ev.data.fd = cfd;
+                                       epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev);
+                               } else {
+                                       int recv_len;
+                                       char *sz_buf = NULL;
+                                       
+                                       recv_len = emipc_recv_email_socket(event_fd, &sz_buf);
+                                       
+                                       if(recv_len > 0) {
+                                               EM_DEBUG_LOG("====================================================================");
+                                               EM_DEBUG_LOG("[IPCLib]Stub Socket Recv [Socket ID = %d], [recv_len = %d]", event_fd, recv_len);
+                                               EM_DEBUG_LOG("====================================================================");
+
+                                               /* IPC request stream is at least 16byte */
+                                               if (recv_len >= sizeof(long) * eSTREAM_DATA) {
+                                                       emipc_create_task((unsigned char *)sz_buf, event_fd);
+                                               } else
+                                                       EM_DEBUG_LOG("[IPCLib] Stream size is less than default size");
+                                       } else if( recv_len == 0 ) {
+                                               EM_DEBUG_LOG("[IPCLib] Client closed connection [%d]", event_fd);
+                                               epoll_ctl(epfd, EPOLL_CTL_DEL, event_fd, events);
+                                               close(event_fd);
+                                       } 
+                                       EM_SAFE_FREE(sz_buf);
+                               }
+                       }
+               }
+       }       
+}
+
+EXPORT_API bool emipc_end_stub_socket()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       if (stub_socket) {
+               emipc_close_email_socket(&stub_socket);
+       }
+
+       if (stub_socket_thread) {
+               emipc_stop_stub_socket_thread(stub_socket_thread);
+               pthread_cancel(stub_socket_thread);
+               stub_socket_thread = 0;
+       }
+
+       if (!emipc_stop_task_thread()) {
+               EM_DEBUG_EXCEPTION("emipc_stop_task_thread failed");
+               return false;   
+       }
+               
+       return true;
+}
+
+EXPORT_API int emipc_send_stub_socket(int sock_fd, void *data, int len)
+{
+       EM_DEBUG_FUNC_BEGIN("Stub socket sending %d bytes", len);
+
+       int sending_bytes = emipc_send_email_socket(sock_fd, data, len);
+       
+       EM_DEBUG_FUNC_END("sending_bytes = %d", sending_bytes);
+       return sending_bytes;
+}
+/* stub socket accpet, recv, send */
+
diff --git a/email-ipc/email-stub/email-stub-task-manager.c b/email-ipc/email-stub/email-stub-task-manager.c
new file mode 100755 (executable)
index 0000000..28ebba4
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <string.h>
+#include <pthread.h>
+#include <errno.h>
+#include <glib.h>
+
+#include "email-stub-task-manager.h"
+#include "email-stub-task.h"
+#include "email-ipc-build.h"
+
+#include "email-debug-log.h"
+#include "email-api.h"
+#include "email-internal-types.h"
+
+static pthread_t task_thread = 0;
+static bool stop_flag = false;
+static GQueue *task_queue = NULL;
+
+pthread_mutex_t ipc_task_mutex = PTHREAD_MUTEX_INITIALIZER;
+pthread_cond_t ipc_task_cond = PTHREAD_COND_INITIALIZER;
+
+EXPORT_API bool emipc_start_task_thread()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       if (task_thread)
+               return true;
+
+       task_queue = g_queue_new();
+
+       if (pthread_create(&task_thread, NULL, &emipc_do_task_thread, NULL) != 0) {
+               EM_DEBUG_LOG("Worker thread creation failed: %s", strerror(errno));
+               return false;   
+       }
+
+       return true;
+}
+
+EXPORT_API void emipc_terminate_task_thread()
+{
+       emipc_stop_task_thread();
+       pthread_cancel(task_thread);
+
+       emipc_email_task *task = (emipc_email_task *)g_queue_pop_head(task_queue);
+       while (task) {
+               EM_SAFE_FREE(task);
+               task = (emipc_email_task *)g_queue_pop_head(task_queue);
+       }
+       g_queue_free(task_queue);
+}
+
+EXPORT_API bool emipc_stop_task_thread()
+{
+       stop_flag = true;
+       return true;
+}
+
+EXPORT_API void *emipc_do_task_thread()
+{
+       EM_DEBUG_FUNC_BEGIN();
+       
+       emipc_email_task *task = NULL;
+
+       while (!stop_flag) {
+               ENTER_CRITICAL_SECTION(ipc_task_mutex);
+               while (g_queue_is_empty(task_queue)) {
+                       EM_DEBUG_LOG("Blocked until new task arrives %p.", &ipc_task_cond);
+                       SLEEP_CONDITION_VARIABLE(ipc_task_cond, ipc_task_mutex);
+               }
+               
+               task = (emipc_email_task *)g_queue_pop_head(task_queue);
+               LEAVE_CRITICAL_SECTION(ipc_task_mutex);
+
+               if (task) {
+                       emipc_run_task(task);
+                       emipc_free_email_task(task);
+               }
+       }
+       
+       return NULL;                    
+}
+
+/* code for ipc handler */
+EXPORT_API bool emipc_create_task(unsigned char *task_stream, int response_channel)
+{
+       emipc_email_task *task = NULL;
+       bool ret = true;
+
+       task = (emipc_email_task *)malloc(sizeof(emipc_email_task));
+       if (task == NULL) {
+               EM_DEBUG_EXCEPTION("Malloc failed.");
+               ret = false;
+       } else {
+               if (!emipc_parse_stream_email_task(task, task_stream, response_channel)) {
+                       EM_DEBUG_EXCEPTION("emipc_parse_stream_email_task failed");
+                       return false;
+               }
+               
+               EM_DEBUG_LOG("[IPCLib] ======================================================");
+               EM_DEBUG_LOG("[IPCLib] Register new task : %p", task);
+               EM_DEBUG_LOG("[IPCLib] Task API ID : %s (%d)", EM_APIID_TO_STR(task->api_info->api_id), task->api_info->api_id);
+               EM_DEBUG_LOG("[IPCLib] Task Response ID : %d", task->api_info->response_id);
+               EM_DEBUG_LOG("[IPCLib] Task APP ID : %d", task->api_info->app_id);
+               EM_DEBUG_LOG("[IPCLib] ======================================================");
+
+               ENTER_CRITICAL_SECTION(ipc_task_mutex);
+               g_queue_push_head(task_queue, (void *)task);
+               
+               WAKE_CONDITION_VARIABLE(ipc_task_cond);
+               LEAVE_CRITICAL_SECTION(ipc_task_mutex);
+       }
+       return ret;
+}
diff --git a/email-ipc/email-stub/email-stub-task.c b/email-ipc/email-stub/email-stub-task.c
new file mode 100755 (executable)
index 0000000..eaa4c1b
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 <sys/socket.h>
+#include <malloc.h>
+
+#include "email-ipc.h"
+#include "email-ipc-param-list.h"
+#include "email-ipc-build.h"
+#include "email-stub-task.h"
+#include "email-stub-main.h"
+
+#include "email-api.h"
+#include "email-debug-log.h"
+
+EXPORT_API void emipc_free_email_task(emipc_email_task *task)
+{
+       EM_DEBUG_FUNC_BEGIN("task [%p]", task);
+       
+       if (!task) {
+               EM_DEBUG_EXCEPTION("Invalid parameter.");
+               return;
+       }
+
+       emipc_free_api_info(task->api_info);
+       EM_SAFE_FREE(task);
+}
+
+EXPORT_API bool emipc_parse_stream_email_task(emipc_email_task *task, void *stream, int response_id)
+{
+       EM_DEBUG_FUNC_BEGIN();
+
+       task->api_info = (emipc_email_api_info *)malloc(sizeof(emipc_email_api_info));
+       if (task->api_info == NULL) {
+               EM_DEBUG_EXCEPTION("Malloc failed.");
+               return false;
+       }
+       memset(task->api_info, 0x00, sizeof(emipc_email_api_info));
+       
+       if (task->api_info) {
+               if (!emipc_deserialize_api_info(task->api_info, ePARAMETER_IN, stream)) {
+                       EM_DEBUG_EXCEPTION("emipc_deserialize_api_info failed");
+                       return false;
+               }
+               task->api_info->response_id = response_id;
+               return true;
+       }
+       return false;
+}
+
+EXPORT_API emipc_email_api_info *emipc_get_api_info(emipc_email_task *task)
+{
+       return task->api_info;
+}
+
+EXPORT_API int emipc_get_response_channel(emipc_email_task *task)
+{
+       return task->response_channel;
+}
+
+EXPORT_API bool emipc_run_task(emipc_email_task *task)
+{
+       EM_DEBUG_LOG("[IPCLib] starting a new task...");
+
+       int api_id = task->api_info->api_id;
+       int app_id = task->api_info->app_id;
+
+       EM_DEBUG_LOG("[IPCLib] This task (%s) is for async. App id [%d], Response ID [%d]", EM_APIID_TO_STR(api_id), app_id, api_id);
+
+       if (!emipc_execute_api_proxy_to_stub(task->api_info)) {
+               EM_DEBUG_EXCEPTION("emipc_execute_api_proxy_to_stub failed");
+               return false;
+       }
+       
+       return true;
+}
+
diff --git a/email-ipc/email-stub/include/email-stub-main.h b/email-ipc/email-stub/include/email-stub-main.h
new file mode 100755 (executable)
index 0000000..4d26d5f
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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        _IPC_STUB_MAIN_H_
+#define        _IPC_STUB_MAIN_H_
+
+#include "email-ipc.h"
+#include "email-ipc-api-info.h"
+
+EXPORT_API bool emipc_initialize_stub_main(PFN_EXECUTE_API fn_api_mapper);
+
+EXPORT_API bool emipc_finalize_stub_main();
+
+EXPORT_API bool emipc_execute_api_proxy_to_stub(emipc_email_api_info *api_info);
+
+EXPORT_API bool emipc_execute_api_stub_to_proxy(emipc_email_api_info *api_info);
+
+EXPORT_API bool emipc_set_response_info(long app_id, long api_id);
+
+#endif /* _IPC_STUB_MAIN_H_ */
+
+
diff --git a/email-ipc/email-stub/include/email-stub-socket.h b/email-ipc/email-stub/include/email-stub-socket.h
new file mode 100755 (executable)
index 0000000..403f1d5
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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        _IPC_STUB_SOCKET_H_
+#define        _IPC_STUB_SOCKET_H_
+
+#include "email-types.h"
+/*
+typedef struct {
+       emipc_email_socket sock_fd;
+       pthread_t       stub_socket_thread;
+       bool            stop_thread;
+       emipc_email_task_manager        *task_manager;
+} emipc_email_stub_socket;
+*/
+
+EXPORT_API bool emipc_start_stub_socket();
+
+EXPORT_API bool emipc_start_stub_socket_thread();
+
+EXPORT_API bool emipc_stop_stub_socket();
+
+EXPORT_API void emipc_wait_for_ipc_request();
+
+EXPORT_API bool emipc_end_stub_socket();
+
+EXPORT_API int emipc_send_stub_socket(int sock_fd, void *data, int len);
+
+#endif /* _IPC_STUB_SOCKET_H_ */
+
+
diff --git a/email-ipc/email-stub/include/email-stub-task-manager.h b/email-ipc/email-stub/include/email-stub-task-manager.h
new file mode 100755 (executable)
index 0000000..95c17df
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 _IPC_TASK_MANAGER_H_
+#define _IPC_TASK_MANAGER_H_
+
+#include "email-types.h"
+
+#define IPC_TASK_MAX   64
+
+EXPORT_API bool emipc_start_task_thread();
+
+EXPORT_API void emipc_terminate_task_thread();
+
+EXPORT_API bool emipc_stop_task_thread();
+
+EXPORT_API void *emipc_do_task_thread();
+
+EXPORT_API bool emipc_create_task(unsigned char *task_stream, int response_channel);
+
+#endif /* _IPC_TASK_MANAGER_H_ */
+
+
diff --git a/email-ipc/email-stub/include/email-stub-task.h b/email-ipc/email-stub/include/email-stub-task.h
new file mode 100755 (executable)
index 0000000..d1d532a
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 _IPC_TASK_H_
+#define _IPC_TASK_H_
+
+#include "email-ipc-api-info.h"
+#include "email-types.h"
+
+typedef struct {
+       int response_channel;
+       emipc_email_api_info *api_info;
+} emipc_email_task;
+
+EXPORT_API void emipc_free_email_task(emipc_email_task *task);
+
+EXPORT_API bool emipc_parse_stream_email_task(emipc_email_task *task, void *stream, int response_id);
+
+EXPORT_API emipc_email_api_info *emipc_get_api_info(emipc_email_task *task);
+
+EXPORT_API int emipc_get_response_channel(emipc_email_task *task);
+
+EXPORT_API bool emipc_run_task(emipc_email_task *task);
+
+#endif /* _IPC_TASK_H */
+
+
diff --git a/email-ipc/include/email-ipc-build.h b/email-ipc/include/email-ipc-build.h
new file mode 100755 (executable)
index 0000000..f441d5d
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 __IPC_LIBRARY_BUILD_H_
+#define __IPC_LIBRARY_BUILD_H_
+
+#include <stdio.h>
+/* #include "MessagingFramework/msBuild.h */
+/* #include "EFCInterface/Common/SDKInterface.h */
+
+
+#endif /*  __IPC_LIBRARY_BUILD_H */
+
+
diff --git a/email-ipc/include/email-ipc.h b/email-ipc/include/email-ipc.h
new file mode 100755 (executable)
index 0000000..f18ca3c
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 __IPC_LIBRARY_H
+#define __IPC_LIBRARY_H
+
+#include "email-types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define EM_PROXY_IF_NULL_RETURN_VALUE(expr1, expr2, val) {     \
+       if (!expr1&& expr2) {   \
+               EM_DEBUG_LOG ("EM_PROXY_IF_NULL_RETURN_VALUE : PARAM IS NULL \n");      \
+               emipc_destroy_email_api(expr2); \
+               return val;     \
+       }; }
+
+       
+/*  ------------------------------------------------------------------------------------------------------------ */
+/*     Type Definitio */
+/*  ------------------------------------------------------------------------------------------------------------ */
+typedef enum {
+       ePARAMETER_IN = 0,
+       ePARAMETER_OUT,
+} EPARAMETER_DIRECTION;
+
+typedef void* HIPC_API;
+typedef void* HIPC_PARAMETER;
+typedef void (*PFN_PROXY_CALLBACK)     (HIPC_API input_api_handle, void* pParam1, void* pParam2);
+typedef void (*PFN_EXECUTE_API)                (HIPC_API input_api_handle);
+
+/*  ------------------------------------------------------------------------------------------------------------ */
+/*     Proxy API */
+/*  ------------------------------------------------------------------------------------------------------------ */
+EXPORT_API int emipc_initialize_proxy();
+EXPORT_API int emipc_finalize_proxy();
+EXPORT_API int emipc_execute_proxy_api(HIPC_API input_api_handle);
+
+/*  ------------------------------------------------------------------------------------------------------------ */
+/*     Stub API */
+/*  ------------------------------------------------------------------------------------------------------------ */
+EXPORT_API bool emipc_initialize_stub(PFN_EXECUTE_API input_api_mapper);
+EXPORT_API bool emipc_finalize_stub();
+EXPORT_API bool emipc_execute_stub_api(HIPC_API input_api_handle);
+
+/*  ------------------------------------------------------------------------------------------------------------ */
+/*     API */
+/*  ------------------------------------------------------------------------------------------------------------ */
+EXPORT_API HIPC_API emipc_create_email_api(long api_id);
+EXPORT_API void emipc_destroy_email_api(HIPC_API input_api_handle);
+
+EXPORT_API long emipc_get_api_id(HIPC_API input_api_handle);
+EXPORT_API long emipc_get_app_id(HIPC_API input_api_handle);
+
+EXPORT_API bool emipc_add_parameter(HIPC_API api, EPARAMETER_DIRECTION direction, void *data, int data_length);
+EXPORT_API bool emipc_add_dynamic_parameter(HIPC_API api, EPARAMETER_DIRECTION direction, void *data, int data_length);
+EXPORT_API int emipc_get_parameter(HIPC_API input_api_handle, EPARAMETER_DIRECTION input_parameter_direction, int input_parameter_index, int input_parameter_buffer_size, void *output_parameter);
+EXPORT_API void* emipc_get_nth_parameter_data(HIPC_API api_handle, EPARAMETER_DIRECTION direction, int param_index);
+EXPORT_API int emipc_get_parameter_length(HIPC_API input_api_handle, EPARAMETER_DIRECTION input_parameter_direction, int input_parameter_index);
+EXPORT_API int emipc_get_nth_parameter_length(HIPC_API input_api_handle, EPARAMETER_DIRECTION input_parameter_direction, int input_parameter_index);
+
+EXPORT_API int emipc_execute_proxy_task(email_task_type_t input_task_type, void *input_task_parameter);
+#ifdef __cplusplus
+}
+#endif
+#endif
+
+
diff --git a/email-service.manifest b/email-service.manifest
new file mode 100644 (file)
index 0000000..d04664e
--- /dev/null
@@ -0,0 +1,26 @@
+<manifest>
+        <define>
+                <domain name="email-service"/>
+                <provide>
+                        <label name="email-service::db"/>
+                </provide>
+                <request>
+                        <smack request="email-service::db" type="rw"/>
+                        <smack request="system::use_internet" type="w"/>
+                </request>
+                <permit>
+                        <smack permit="system::use_internet" type="rwx"/>
+                        <smack permit="webkit2-efl" type="rx"/>
+                </permit>
+        </define>
+        <assign>
+                <filesystem path="/usr/lib/libemail-api.so.1.1.0" label="_"/>
+                <filesystem path="/usr/lib/libemail-api.so.1" label="_"/>
+                       <filesystem path="/etc/rc.d/init.d/email-service" label="_" exec_label="none"/>
+                       <filesystem path="/usr/lib/systemd/user/email.service" label="_"/>
+                       <filesystem path="/usr/lib/systemd/user/tizen-middleware.target.wants/email.service" label="_"/>
+        </assign>
+        <request>
+                <domain name="email-service"/>
+        </request>
+</manifest>
index 9458dd5..45af536 100755 (executable)
@@ -2,8 +2,8 @@ prefix=/usr
 libdir=${prefix}/lib\r
 includedir=${prefix}/include\r
  \r
-Name: Email Engine Library\r
-Description: Email Engine Library 1.0\r
+Name: email-service library\r
+Description: email-service library 1.0\r
 Version: $version\r
-Libs: -L${libdir} -lemail-storage -lemail-core -lemail-base -lemail-ipc -lemail-api -lemail-network \r
-Cflags: -I${includedir}/email-service -D_PREVIEW_IN_MAILIST \r
+Libs: -L${libdir} -lemail-storage -lemail-core -lemail-common-use -lemail-ipc -lemail-api -lemail-network \r
+Cflags: -I${includedir}/email-service \r
diff --git a/email-service_PG.h b/email-service_PG.h
new file mode 100755 (executable)
index 0000000..4e6f2a4
--- /dev/null
@@ -0,0 +1,1141 @@
+/**
+ *
+ * @ingroup   SLP_PG
+ * @defgroup   EMAILSVC Email Service
+@{
+<h1 class="pg">Introduction</h1>
+       <h2 class="pg">Overview </h2>
+Electronic mail, most commonly abbreviated email or e-mail, is a method of exchanging digital messages. E-mail systems are based on a store-and-forward model in which e-mail server computer systems accept, forward, deliver and store messages on behalf of users, who only need to connect to the e-mail infrastructure, typically an e-mail server, with a network-enabled device for the duration of message submission or retrieval.
+
+       <h2 class="pg">Purpose of Programming Guide</h2>
+This document is mainly aimed at the core functionality of the Email Service.  The EMail Service component is implemented by Samsung to provide EMail service to applications that make use of EMail Engine. Email Engine provides functionality for the user like composing mail, saving mail, sending mail, and creating user mailbox according to the settings. Mobile subscribers can use the Email Engine to perform storage opearations such as save, update, get, delete and transport operations such as send, download and other email operations.
+
+This programming guide is prepared for application developers who will use the email-service. It contains: 
+- List of features offered by email-service
+- Information on How to use APIs provided by the email-service
+- Examples 
+
+       <h2 class="pg">Target Domain / Application</h2>
+The Email Service Layer can be utilized by any component in the application layer which allow the end user to perform the email related operations such as save, send, download email message and others.
+
+For Example, the Email Service APIs shall be invoked by 
+@li Multimedia application when user opts to send media file through email 
+@li Email application when user tries to send an email message 
+
+       <h2 class="pg">Terminology & Acronyms</h2>
+<table>
+<tr><th>Terminology</th><th>Description</th></tr>
+<tr><td>Email </td><td>Electronic mail</td></tr>
+<tr><td>IMAP</td><td>Internet Message Access Protocol</td></tr>
+<tr><td>SMTP</td><td>Simple mail transfer protocol for sending mails</td></tr>
+<tr><td>POP3</td><td>Post office protocol for receiving mails</td></tr>
+<tr><td>RFC822</td><td>Describes mail header, to address, cc, bcc etc. formats and decoding and encoding standards. </td></tr>
+<tr><td>OMA </td><td>Open Moblie Alliance</td></tr>
+</table> 
+
+
+@}
+
+@defgroup Email_Architecture 1. Email Service Architecture
+@ingroup EMAILSVC
+@{
+<h1 class="pg">Email-service Architecture</h1>
+       <h2 class="pg">System Architecture</h2>
+@image html email_image001.png
+       <h2 class="pg">Process Architecture</h2>
+@image html email_image002.png email-service Process view
+
+@image html email_image003.png email-service Process architecture
+
+Whenever an application wants to use email-service, it will call APIs from Email MAPI layer. Email MAPI layer APIs will internally call APIs provided by email framework module.
+@}
+
+@defgroup Email_Feature 2. Email Service Feature
+@ingroup EMAILSVC
+@{
+<h1 class="pg">Email-service Features</h1>
+<table>
+<tr><th>Feature </th><th>API Reference</th></tr>
+<tr><td>Account Operation</td>
+<td>
+@n email_add_account()
+@n email_delete_account() 
+@n email_update_account() 
+@n email_get_account() 
+@n email_get_account_list() 
+@n email_free_account() 
+@n email_validate_account()
+</td></tr>
+<tr><td>mailbox Operation </td>
+<td>
+@n email_add_mailbox()
+@n email_delete_mailbox()
+@n email_update_mailbox()
+@n email_get_mailbox_list()
+@n email_get_mailbox_by_name()
+@n email_get_child_mailbox_list()
+@n email_get_mailbox_by_mailbox_type()
+</td></tr>
+<tr><td>Message Operation </td>
+<td>
+@n email_add_message()  
+@n email_update_message()
+@n email_count_mail()  
+@n email_delete_mail()  
+@n email_delete_all_mails_in_mailbox()
+@n email_clear_mail_data()
+@n email_add_attachment()
+@n email_delete_attachment() 
+@n email_get_info()
+@n email_free_mail_info()
+@n email_get_header_info()  
+@n email_free_header_info()  
+@n email_get_body_info()
+@n email_free_body_info()
+@n email_get_attachment_data() 
+@n email_free_attachment_info()  
+@n email_get_mail() 
+@n email_modify_mail_flag()
+@n email_modify_seen_flag()
+@n email_modify_extra_mail_flag()
+@n email_move_mail_to_mailbox()
+@n email_move_all_mails_to_mailbox()
+@n email_count_message_with_draft_flag()
+@n email_count_message_on_sending()
+@n email_get_mailbox_list()
+@n email_free_mailbox()
+@n email_free_mail()
+@n email_get_mail_flag()
+@n email_free_mail_list()
+@n email_release_mail()
+@n email_retry_sending_mail()
+@n email_make_db_full()
+@n email_get_mailbox_name_by_mail_id()
+@n email_cancel_sending_mail()
+@n email_count_message_all_mailboxes()
+@n email_get_latest_unread_mail_id()
+@n email_get_max_mail_count()
+@n email_get_disk_space_usage()
+</td></tr>
+<tr><td>Network Operation </td>
+<td>
+@n email_send_mail()
+@n email_sync_header()
+@n email_download_body()
+@n email_download_attachment()
+@n email_cancel_job()
+@n email_get_pending_job()
+@n email_get_network_status()
+@n email_send_report()
+@n email_send_saved()
+@n email_sync_imap_mailbox_list()
+@n email_sync_local_activity()
+</td></tr>
+<tr><td>Rule Operation </td>
+<td>
+@n email_get_rule()
+@n email_get_rule_list()
+@n email_add_rule()
+@n email_update_rule()
+@n email_delete_rule()
+@n email_free_rule()
+</td></tr>
+<tr><td>Control Operation </td>
+<td>
+@n email_init_storage()
+@n email_open_db()
+@n email_close_db()
+@n email_service_begin()
+@n email_service_end()
+</td></tr>
+</table>
+@}
+
+
+
+@defgroup Use_Case1_account Account Operation
+@ingroup EMAIL_USECASES
+@{
+       <h2 class="pg">Account Operation </h2>
+Account Operations are a set of operations to manage email accounts like add, update, delete or get account related details.
+
+Structure:
+email_account_t - refer to doxygen (SLP-SDK: http:/* slp-sdk.sec.samsung.net) */
+<table>
+<tr><td>API</td>
+<td>Return Value / Exceptions</td></tr>
+
+<tr><td>int email_add_account(email_account_t* account)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param email_account_t* account should be allocated and deallocated by Application</td></tr>
+
+<tr><td>int email_delete_account(int account_id) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+  
+<tr><td>int email_update_account(int account_id , email_account_t* new_account) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks:  - Memory for param email_account_t* new_account should be allocated and deallocated by Application</td></tr>
+  
+<tr><td>int email_get_account(int account_id, int pulloption, email_account_t** account) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory allocation for param account will happen in email_get_account (). To free this memory, application should call email_free_account ()</td></tr>
+  
+<tr><td>int email_get_account_list(email_account_t** account_list, int* count) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: Memory allocation for param ccount_list will happen in email_get_account_list (). To free this memory, application should call email_free_account () </td></tr>
+  
+<tr><td>int email_free_account(email_account_t** account_list, int count) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+  
+<tr><td>int email_validate_account(int account_id, int *handle)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+</table> 
+
+<b>Sample Code</b>
+@li Add account
+@code
+/* Add account */       
+
+/*  Assign values for new account */
+email_account_t *account = NULL;
+account = malloc(sizeof(email_account_t));
+memset(account, 0x00, sizeof(email_account_t));
+account->retrieval_mode               = 1;
+account->incoming_server_secure_connection                 = 1;
+account->outgoing_server_type          = EMAIL_SERVER_TYPE_SMTP;
+account->outgoing_server_port_number             = EMAIL_SMTP_PORT;
+account->outgoing_server_need_authentication                 = 1;
+account->account_name                 = strdup("gmail");
+account->display_name                 = strdup("Tom");
+account->user_email_address                   = strdup("tom@gmail.com");
+account->reply_to_addr                = strdup("tom@gmail.com");
+account->return_addr                  = strdup("tom@gmail.com");
+account->incoming_server_type        = EMAIL_SERVER_TYPE_POP3;
+account->incoming_server_address        = strdup("pop3.gmail.com");
+account->incoming_server_port_number                     = 995;
+account->incoming_server_secure_connection                 = 1;
+account->retrieval_mode               = EMAIL_IMAP4_RETRIEVAL_MODE_ALL;
+account->incoming_server_user_name                    = strdup("tom");
+account->password                     = strdup("tioimi");
+account->outgoing_server_type          = EMAIL_SERVER_TYPE_SMTP;
+account->outgoing_server_address          = strdup("smtp.gmail.com");
+account->outgoing_server_port_number             = 587;
+account->outgoing_server_secure_connection             = 0x02;
+account->outgoing_server_need_authentication                 = 1;
+account->outgoing_server_user_name                 = strdup("tom@gmail.com");
+account->sending_password             = strdup("tioimi");
+account->pop_before_smtp              = 0;
+account->incoming_server_requires_apop                         = 0;
+account->flag1                        = 2;
+account->flag2                        = 1;
+account->is_preset_account            = 1;
+account->logo_icon_path               = strdup("Logo Icon Path");
+account->options.priority             = 3;
+account->options.keep_local_copy      = 0;
+account->options.req_delivery_receipt = 0;   
+account->options.req_read_receipt     = 0;
+account->options.download_limit       = 0;
+account->options.block_address        = 0;
+account->options.block_subject        = 0;
+account->options.display_name_from    = strdup("Display name from");
+account->options.reply_with_body      = 0;
+account->options.forward_with_files   = 0;
+account->options.add_myname_card      = 0;
+account->options.add_signature        = 0;
+account->options.signature            = strdup("Signature");
+account->check_interval               = 0;
+      
+if(EMAIL_ERROR_NONE != email_add_account(account))
+       /* failure */
+else
+{
+       /* success     */
+       if(account_id)
+               *account_id = account->account_id;              /*  Use this returned account id when calling APIs which need it */
+}
+
+/* free account */
+email_free_account(&account, 1);
+@endcode 
+
+@li Get account
+@code
+/* Get account */
+email_account_t *account = NULL;
+int account_id = 1;            /*  account id to be gotten */
+if(EMAIL_ERROR_NONE != email_get_account(account_id,GET_FULL_DATA,&account))
+       /* failure */
+else
+       /* success */
+/* free account */
+email_free_account(&account, 1);
+@endcode
+
+@li Update account
+@code
+/* Update account */               
+
+email_account_t *new_account = NULL;
+int account_id = 1;            /*  account id to be updated */
+/*  Get account to be updated */
+if(EMAIL_ERROR_NONE != email_get_account(account_id,GET_FULL_DATA,&new_account))
+       /* failure */
+else
+       /* success */
+/*  Set the new values */
+new_account->flag1                   = 1;
+new_account->account_name            = strdup("gmail");
+new_account->display_name            = strdup("Tom001");
+new_account->options.keep_local_copy = 1;   
+new_account->check_interval          = 55;
+if(EMAIL_ERROR_NONE != email_update_account(account_id,new_account))
+       /* failure */
+else
+       /* success */
+/* free account */
+email_free_account(&new_account, 1);
+
+@endcode
+
+@li Delete account
+@code 
+/* Delete account */
+
+int account_id = 1;            /*  account id to be deleted */
+if(EMAIL_ERROR_NONE != email_delete_account(account_id))
+      /* failure */
+else
+      /* success */
+@endcode
+
+
+@li Get list of accounts
+@code
+/* Get list of accounts */
+
+email_account_t *account_list = NULL;
+int count = 0;         
+int i;
+if(EMAIL_ERROR_NONE != email_get_account_list(&account_list,&count))
+       /* failure */
+else
+{
+       /* success */
+       for ( i = 0; i < count; i++ )
+       {
+               /*  Do something with each account */
+               printf("account id : %d\n", account_list[i].account_id);
+       }
+}      
+/* free account */
+email_free_account(&account_list,count);
+
+@endcode
+
+@li Validate account - try to connect to server
+@code
+/* Validate account - try to connect to server */
+unsigned account_handle = 0;
+int account_id = 1;
+if(EMAIL_ERROR_NONE != email_validate_account(account_id,&account_handle))
+       /* failure */
+else
+       /* success */
+@endcode
+<b>Flow Diagram</b>
+@image html email_image004.png
+@}
+
+@defgroup Use_Case2_folder mailbox Operation
+@ingroup EMAIL_USECASES
+@{
+       <h2 class="pg">mailbox Operation </h2>
+mailbox Operations are a set of operations to manage email mailboxes like add, update, delete or get mailbox related details.
+
+Structure:
+email_mailbox_t - refer to doxygen (SLP-SDK: http:/* slp-sdk.sec.samsung.net) */
+
+<table>
+<tr><td>API</td><td>Return Value / Exceptions</td></tr>
+<tr><td>int email_add_mailbox(email_mailbox_t* new_mailbox, int on_server, int *handle) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: -  Memory for param email_mailbox_t* new_mailbox should be allocated and deallocated by Application </td></tr>
+<tr><td>int email_delete_mailbox(email_mailbox_t* mailbox, int on_server,  int *handle) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param email_mailbox_t* mailbox should be allocated and deallocated by Application</td></tr>
+
+<tr><td>int email_update_mailbox(email_mailbox_t*old_mailbox, email_mailbox_t* new_mailbox)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for params email_mailbox_t* old_mailbox and  email_mailbox_t* new_mailbox should be allocated and deallocated by Application</td></tr>
+
+<tr><td>int email_get_mailbox_list(int account_id, int local_yn, email_mailbox_t** mailbox_list, int* count)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory allocation for param mailbox_list will happen in email_get_mailbox_list (). To free this memory application should call email_free_mailbox</td></tr>
+<tr><td>int email_get_mailbox_by_name(int account_id, const char *pMailboxName, email_mailbox_t **pMailbox)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory allocation for param pMailbox will happen in email_get_mailbox_by_name (). To free this memory application should call email_free_mailbox</td></tr>
+<tr><td>int email_get_child_mailbox_list(int account_id, const char *parent_mailbox,  email_mailbox_t** mailbox_list, int* count)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory allocation for param mailbox_list will happen in email_get_child_mailbox_list (). To free this memory application should call email_free_mailbox</td></tr>
+<tr><td>int email_get_mailbox_by_mailbox_type(int account_id, email_mailbox_type_e mailbox_type,  email_mailbox_t** mailbox)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory allocation for param mailbox_list will happen in email_get_mailbox_by_mailbox_type (). To free this memory application should call email_free_mailbox</td></tr>
+</table>
+<b>Sample Code</b>
+
+@li Create new mailbox
+@code
+email_mailbox_t *mailbox = NULL, *new_mailbox = NULL;
+int handle = 0;
+int on_server = 0;
+mailbox = malloc(sizeof(email_mailbox_t));
+memset(mailbox, 0x00, sizeof(email_mailbox_t));
+mailbox->mailbox_name           = strdup("Personal"); 
+mailbox->alias          = strdup("selfuse");            
+mailbox->account_id     = 1; 
+mailbox->local          = on_server; 
+mailbox->mailbox_type    = 7;  
+      
+/* create new mailbox */           
+if(EMAIL_ERROR_NONE != email_add_mailbox(mailbox,on_server,&handle))
+      /* failure */
+else
+      /* success   */
+
+@endcode
+
+
+@li Update and Delete mailbox
+@code
+email_mailbox_t *mailbox = NULL, *new_mailbox = NULL;
+int on_server = 0;
+int handle = 0;
+
+new_mailbox = malloc(sizeof(email_mailbox_t));
+memset(new_mailbox, 0x00, sizeof(email_mailbox_t));
+new_mailbox->mailbox_name =  strdup("Personal001");
+/* update mailbox */
+if(EMAIL_ERROR_NONE != email_update_mailbox(mailbox,new_mailbox))
+      /* failure */
+else
+      /* success   */
+/* delete mailbox */
+if(EMAIL_ERROR_NONE != email_delete_mailbox(mailbox,on_server,&handle))
+      /* failure */
+else
+      /* success   */
+email_free_mailbox(&mailbox, 1);
+email_free_mailbox(&new_mailbox, 1);
+@endcode
+
+@li Get list of mailboxes
+@code
+int account_id = 1;
+int local_yn = 0;
+email_mailbox_t* mailbox_list = NULL;
+int count = 0;
+/*get list of mailboxes */
+if(EMAIL_ERROR_NONE != email_get_mailbox_list(account_id, local_yn, &mailbox_list, &count))
+      /* failure */
+else
+{
+      /* success   */
+      email_free_mailbox(&mailbox_list,count);
+}
+@endcode
+
+<b>Flow Diagram</b>
+@image html email_image005.png
+@}
+
+@defgroup Use_Case3_message Message Operation
+@ingroup EMAIL_USECASES
+@{
+       <h2 class="pg">Message Operation </h2>
+Message Operations are a set of operations to manage email messages like add, update, delete or get message related details.
+
+Structure:
+email_mail_data_t
+<table>
+<tr><td>API</td>
+<td>Return Value / Exceptions</td></tr>
+<tr><td>int email_add_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: -  Memory for params email_mail_data_t* input_mail_data and email_attachment_data_t *input_attachment_data_list and email_meeting_request_t* input_meeting_request should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_update_mail(email_mail_data_t *input_mail_data, email_attachment_data_t *input_attachment_data_list, int input_attachment_count, email_meeting_request_t* input_meeting_request, int input_from_eas)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: -  Memory for params email_mail_data_t* input_mail_data and email_attachment_data_t *input_attachment_data_list and email_meeting_request_t* input_meeting_request should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_count_mail(email_mailbox_t* mailbox, int* total, int* unseen)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param email_mailbox_t* mailbox should be allocated and deallocated by Application</td></tr>
+
+<tr><td>int email_delete_mail(email_mailbox_t* mailbox, int *mail_ids, int num, int from_server)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for params int *mail_ids and mf_mailbox_t* mailbox should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_delete_all_mails_in_mailbox(email_mailbox_t* mailbox, int from_server)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param mf_mailbox_t* mailbox should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_clear_mail_data()  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+
+<tr><td>int email_add_attachment(email_mailbox_t* mailbox, int mail_id, email_attachment_data_t* attachment)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param mf_mailbox_t* mailbox and mf_attachment_info_t* attachment hould be allocated and deallocated by Application</td></tr>
+<tr><td>int email_delete_attachment(email_mailbox_t * mailbox, int mail_id, const char * attachment_id)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param email_mailbox_t* mailbox should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_get_attachment_data(email_mailbox_t* mailbox, int mail_id, const char* attachment_id, email_attachment_data_t** attachment)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure.@n Remarks:
+-# Memory for param email_mailbox_t* mailbox should be allocated and deallocated by Application 
+-# Memory allocation for param email_attachment_data_t** attachment will happen in email_get_attachment_data (). To free this memory, application should call email_free_attachment_info () </td></tr>
+<tr><td>int email_free_attachment_info(email_attachment_data_t** atch_info)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure.</td></tr>
+<tr><td>int email_modify_seen_flag(int *mail_ids, int num, int seen_flag, int onserver)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param int *mail_ids should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_move_mail_to_mailbox(int *mail_ids, int num, email_mailbox_t* new_mailbox)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for params int *mail_ids and email_mailbox_t* new_mailbox should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_move_all_mails_to_mailbox(email_mailbox_t* src_mailbox, email_mailbox_t* new_mailbox)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for params email_mailbox_t* src_mailbox and email_mailbox_t* new_mailbox should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_count_message_with_draft_flag(email_mailbox_t* mailbox, int* total)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param email_mailbox_t* mailbox should be allocated and deallocated by Application</td></tr>
+<tr><td>int email_count_message_on_sending(email_mailbox_t* mailbox, int* total)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory for param email_mailbox_t* mailbox should be allocated and deallocated by Application</td></tr>
+  
+<tr><td>int email_get_mailbox_list(int account_id, email_mailbox_t** mailbox_list, int* count ) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: - Memory allocation for param email_mailbox_t** mailbox_list will happen in email_get_mailbox_list (). To free this memory, application should call email_free_mailbox ()</td></tr>
+<tr><td>int email_free_mailbox(email_mailbox_t** mailbox_list, int count)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_retry_sending_mail( int mail_id, int timeout_in_sec)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_make_db_full()</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_get_mailbox_name_by_mail_id(int mail_id, char **pMailbox_name)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_cancel_sending_mail( int mail_id)  </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_count_message_all_mailboxes(email_mailbox_t* mailbox, int* total, int* unseen) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_get_latest_unread_mail_id(int account_id, int *pMailID) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_get_max_mail_count(int *Count) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_get_disk_space_usage(unsigned long *total_size)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+</table>
+<b>Sample Code</b>
+
+@li Add, Update, Count and Delete message
+@code
+email_mailbox_t *mailbox = NULL;
+int on_server = 0, account_id = 0, mail_id = 0;
+char *pFilePath = "/tmp/mail.txt";
+int                    i = 0;
+int                    account_id = 0;
+int                    from_eas = 0;
+int                    attachment_count = 0;
+int                    err = EMAIL_ERROR_NONE;
+char                   arg[50] = { 0 , };
+char                  *body_file_path = MAILHOME"/tmp/mail.txt";
+email_mailbox_t         *mailbox_data = NULL;
+email_mail_data_t       *test_mail_data = NULL;
+email_attachment_data_t *attachment_data = NULL;
+email_meeting_request_t *meeting_req = NULL;
+FILE                  *body_file;
+
+printf("\n > Enter account id : ");
+scanf("%d", &account_id);
+
+memset(arg, 0x00, 50);
+printf("\n > Enter mailbox name : ");
+scanf("%s", arg);
+
+email_get_mailbox_by_name(account_id, arg, &mailbox_data);
+
+test_mail_data = malloc(sizeof(email_mail_data_t));
+memset(test_mail_data, 0x00, sizeof(email_mail_data_t));
+
+printf("\n From EAS? [0/1]> ");
+scanf("%d", &from_eas);
+
+test_mail_data->account_id        = account_id;
+test_mail_data->save_status       = 1;
+test_mail_data->flags_seen_field  = 1;
+test_mail_data->file_path_plain   = strdup(body_file_path);
+test_mail_data->mailbox_name      = strdup(mailbox_data->mailbox_name);
+test_mail_data->mailbox_type      = mailbox_data->mailbox_type;
+test_mail_data->full_address_from = strdup("<test1@test.com>");
+test_mail_data->full_address_to   = strdup("<test2@test.com>");
+test_mail_data->full_address_cc   = strdup("<test3@test.com>");
+test_mail_data->full_address_bcc  = strdup("<test4@test.com>");
+test_mail_data->subject           = strdup("Meeting request mail");
+
+body_file = fopen(body_file_path, "w");
+
+for(i = 0; i < 500; i++)
+       fprintf(body_file, "X2 X2 X2 X2 X2 X2 X2");
+fflush(body_file);
+ fclose(body_file);
+
+
+if((err = email_add_mail(test_mail_data, attachment_data, attachment_count, meeting_req, from_eas)) != EMAIL_ERROR_NONE)
+       printf("email_add_mail failed. [%d]\n", err);
+else
+       printf("email_add_mail success.\n");
+/* Update message */
+/*  variable 'mail' should be filled with data on DB. */
+/*  And change values you want to update. */
+mail->head->subject = strdup("save.mailbox again...");
+if(EMAIL_ERROR_NONE != email_update_message(mail_id,mail))
+       /* failure */
+else
+       /* success   */
+/* Count message */
+int total = 0, unseen = 0;
+/*  Get the total number of mails and the number of unseen mails */
+if(EMAIL_ERROR_NONE != email_count_mail(mailbox,&total,&unseen))
+       /* failure */
+else
+       /* success   */
+/* Delete message */
+int *mail_ids, num = 0;
+if(EMAIL_ERROR_NONE != email_delete_mail(mailbox,mail_ids,num,on_server))
+       /* failure */
+else
+       /* success   */
+@endcode 
+@li Delete all message in a specific mailbox
+@code 
+/* Delete all message in mailbox */
+email_mailbox_t *mailbox = NULL;
+int on_server = 0;
+
+mailbox = malloc(sizeof(email_mailbox_t));
+memset(mailbox, 0x00, sizeof(email_mailbox_t));
+
+mailbox->account_id = 1;
+mailbox->mailbox_name = strdup("INBOX");               
+
+if( EMAIL_ERROR_NONE != email_delete_all_mails_in_mailbox(mailbox, on_server))
+      /* failure */
+else
+
+      /* success   */
+@endcode
+
+
+@li Clear all messages
+@code
+/* clear mail data */
+if(EMAIL_ERROR_NONE !=  email_clear_mail_data())
+      /* failure */
+else
+      /* success   */
+@endcode
+
+
+@li Move mail
+@code 
+int mail_id[],account_id = 1;
+email_mailbox_t *mailbox = NULL;
+char *mailbox_name = "INBOX";
+mailbox = malloc(sizeof(email_mailbox_t));
+memset(mailbox, 0x00, sizeof(email_mailbox_t));
+mailbox->account_id = account_id;
+mailbox->mailbox_name = mailbox_name;
+/* Move mail to given mailbox*/
+if(EMAIL_ERROR_NONE !=  email_move_mail_to_mailbox(/*mail_id*/,/*num*/,mailbox))
+      /* failure */
+else
+      /* success   */
+/* free mailbox*/
+email_free_mailbox(&mailbox,1);
+email_mailbox_t *src_mailbox = NULL,*dest_mailbox = NULL;
+int src_account_id = 0, dest_account_id = 0;
+char * src_mailbox_name = NULL, *dest_mailbox_name = NULL;
+src_mailbox = malloc(sizeof(email_mailbox_t));
+memset(src_mailbox, 0x00, sizeof(email_mailbox_t));
+dest_mailbox = malloc(sizeof(email_mailbox_t));
+memset(dest_mailbox, 0x00, sizeof(email_mailbox_t));
+src_mailbox->account_id = /*src_account_id*/;
+src_mailbox->mailbox_name = /*src_mailbox_name*/
+dest_mailbox->account_id = /*dest_account_id*/;
+dest_mailbox->mailbox_name = /*dest_mailbox_name*/
+/*move all mails to given mailbox*/
+if(EMAIL_ERROR_NONE !=  email_move_all_mails_to_mailbox(src_mailbox,dest_mailbox))
+      /* failure */
+else
+      /* success   */
+/* free mailbox*/
+email_free_mailbox(&src_mailbox,1);
+email_free_mailbox(&dest_mailbox,1);
+int account_id = 0, total = 0;
+email_mailbox_t *mailbox = NULL;
+char *mailbox_name = NULL;
+mailbox = malloc(sizeof(email_mailbox_t));
+memset(mailbox, 0x00, sizeof(email_mailbox_t));
+mailbox->account_id = /*account_id*/;
+mailbox->mailbox_name = /*mailbox_name*/
+/*count of draft msgs*/
+if(EMAIL_ERROR_NONE !=  email_count_message_with_draft_flag(mailbox,&total))
+      /* failure */
+else
+      /* success   */
+/* free mailbox*/
+email_free_mailbox(&mailbox,1);
+@endcode
+@li Count of msgs sent from given folde
+@code
+int account_id = 0, total = 0;
+email_mailbox_t *mailbox = NULL;
+char *mailbox_name = NULL;
+mailbox = malloc(sizeof(email_mailbox_t));
+memset(mailbox, 0x00, sizeof(email_mailbox_t));
+mailbox->account_id = /*account_id*/;
+mailbox->mailbox_name = /*mailbox_name*/
+/*count of msgs sent from given mailbox*/
+if(EMAIL_ERROR_NONE != email_count_message_on_sending(mailbox,&total))
+      /* failure */
+else
+      /* success   */
+/* free mailbox*/
+email_free_mailbox(&mailbox,1);
+
+@endcode
+
+
+@li Get mailbox list 
+@code
+email_mailbox_t* mailbox_list = NULL;
+int account_id = 1, count = 0;
+/* Get mailbox list*/
+if(EMAIL_ERROR_NONE != email_get_mailbox_list(account_id,&mailbox_list,&count))
+      /* failure */
+else
+      /* success   */
+/* free mailbox list*/
+email_free_mailbox(&mailbox,count);
+@endcode
+
+
+@li Get mailBox name by mailID
+@code
+/* Get mailBox name by mailID*/
+int mail_id = 1;
+char *pMailbox_name=strdup("INBOX");
+err = email_get_mailbox_name_by_mail_id(mail_id,&pMailbox_name);
+
+free(pMailbox_name);
+
+@endcode
+
+
+@li Cancel sending mail
+@code 
+/* email_cancel_sending_mail*/
+int mail_id = 1;       /*  mail id of a mail which is on sending */
+err = email_cancel_sending_mail(mail_id);
+@endcode
+
+
+
+@li Get the Total count and Unread count of all mailboxes
+@code 
+/* Get the Total count and Unread count of all mailboxes */
+email_mailbox_t* mailbox = NULL;
+int account_id = 1, total = 0, unseen = 0;
+char *mailbox_name = NULL;
+mailbox = malloc(sizeof(email_mailbox_t));
+memset(mailbox, 0x00, sizeof(email_mailbox_t));
+mailbox->account_id = /*account_id*/;
+mailbox->mailbox_name = /*mailbox_name*/
+err = email_count_message_all_mailboxes(mailbox,&total,&unseen);
+@endcode
+
+<b>Flow Diagram</b>s
+@image html email_image006.png
+
+@image html email_image007.png
+@image html email_image008.png 
+@}
+
+@defgroup Use_Case4_network Network Operation
+@ingroup EMAIL_USECASES
+@{
+       <h2 class="pg">Network Operation </h2>
+Network Operations are a set of operations to manage email send, receive and cancel related details.
+
+Structure:
+email_option_t - refer to doxygen (SLP-SDK: http:/* slp-sdk.sec.samsung.net) */
+<table>
+<tr><td>API</td>
+<td>Return Value / Exceptions</td></tr>
+<tr><td>int email_send_mail( email_mailbox_t* mailbox, int mail_id, int *handle)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: 
+-# Memory allocation and de-allocation for input param is to be done by application.</td></tr>
+<tr><td>int email_sync_header(email_mailbox_t* mailbox, int *handle)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks:
+-# Memory allocation and de-allocation for input param is to be done by application.</td></tr>
+<tr><td>int email_download_body(email_mailbox_t* mailbox, int mail_id, int with_attachment, int *handle) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks:
+-# Memory allocation and de-allocation for input param is to be done by application.</td></tr>
+<tr><td>int email_download_attachment(email_mailbox_t* mailbox, int mail_id, const char* nth,  int *handle)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure.</td></tr>
+
+<tr><td>int email_cancel_job(int account_id, int handle)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure.</td></tr>
+<tr><td>int email_get_pending_job(email_action_t action, int account_id, int mail_id, email_event_status_type_t * status)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure.</td></tr>
+<tr><td>void email_get_network_status(int* on_sending, int* on_receiving) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_send_saved(int account_id, email_option_t* sending_option, int *handle)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks:
+-# Memory allocation and de-allocation for input param is to be done by application.</td></tr>
+<tr><td>int email_sync_imap_mailbox_list(int account_id, const char* mailbox, int *handle)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure.</td></tr>
+<tr><td>int email_sync_local_activity(int account_id)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure.</td></tr>
+</table>
+
+<b>Sample Code</b>
+@li Send a mail
+@code
+/* TODO : Write sample to send a mail. */
+@endcode
+
+@li Download header of new emails from mail server
+@code
+/* Download header of new emails from mail server*/
+email_mailbox_t mailbox;
+int account_id = 1;
+int err = EMAIL_ERROR_NONE;
+int handle = 0;
+memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+mailbox.account_id = account_id;
+mailbox.mailbox_name = strdup("INBOX");
+err = email_sync_header (&mailbox,&handle);
+@endcode
+
+
+@li Download email body from server
+@code
+/*Download email body from server*/
+email_mailbox_t mailbox;
+int mail_id = 1;
+int account_id = 1;
+int handle = 0;
+int err = EMAIL_ERROR_NONE;
+memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+mailbox.account_id = account_id;
+mailbox.mailbox_name = strdup("INBOX");
+err= email_download_body (&mailbox,mail_id,0,&handle);
+@li Download a email nth-attachment from server
+@code
+/*Download a email nth-attachment from server*/
+email_mailbox_t mailbox;
+int mail_id = 1;
+int account_id = 1;     
+char arg[50]; /* Input attachment number need to be download */
+int handle = 0;
+int err = EMAIL_ERROR_NONE;
+memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+mailbox.mailbox_name = "INBOX";
+mailbox.account_id = account_id;
+err=email_download_attachment(&mailbox,mail_id,arg,&handle);
+@endcode
+
+<b>Flow Diagram</b>
+@image html email_image009.png
+@}
+
+@defgroup Use_Case5_rule Rule Operation
+@ingroup EMAIL_USECASES
+@{
+       <h2 class="pg">Rule Operation</h2>
+Rule Operations are a set of operations to manage email rules like add, get, delete or update rule related details.
+
+Structure:
+email_rule_t- refer to doxygen (SLP-SDK: http:/* slp-sdk.sec.samsung.net) */
+<table>
+<tr><td>API</td>
+<td>Return Value / Exceptions</td></tr>
+<tr><td>int email_get_rule(int filter_id, email_rule_t** filtering_set)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks: 
+-# Memory allocation for the param email_rule_t** filtering_set will be done in this api.
+-# De-allocation is to be done by application.</td></tr>
+<tr><td>int email_get_rule_list(email_rule_t** filtering_set, int* count)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks:
+-# Memory allocation for the param email_rule_t** filtering_set will be done in this api.
+-# De-allocation is to be done by application.</td></tr>
+<tr><td>int email_add_rule(email_rule_t* filtering_set) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks:
+-# Memory allocation and de-allocation is to be done by application.
+-# Use email_free_rule to free allocated memory.</td></tr>
+<tr><td>int email_update_rule(int filter_id, email_rule_t* new_set) </td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure@n Remarks:
+-# Memory allocation and de-allocation is to be done by application.</td></tr>
+-# Use email_free_rule to free allocated memory.
+<tr><td>int email_delete_rule(int filter_id)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure.</td></tr>
+<tr><td>int email_free_rule(email_rule_t** filtering_set, int count)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+</table>
+
+<b>Sample Code</b>
+@li Filter Operation
+@code
+int err = EMAIL_ERROR_NONE;
+email_rule_t*  rule = NULL;
+int filter_id = 1;
+/* Get a information of filtering*/
+err = email_get_rule (filter_id,&rule);
+err = email_free_rule (&rule,1);
+/* Get all filterings */
+int count = 0;
+err = email_get_rule_list(&rule,&count);
+/* Add a filter information */
+err = email_add_rule (rule);
+err = email_free_rule (&rule,1);
+/* Change a filter information */
+err = email_update_rule (filter_id,rule);
+err = email_free_rule (&rule,1);
+/* Delete a filter information*/
+err = email_delete_rule (filter_id);
+/* Free allocated memory */
+err = email_free_rule (&rule,1);
+@endcode
+
+<b>Flow Diagram</b>
+@image html email_image010.png
+@}
+
+@defgroup Use_Case6_control Control Operation
+@ingroup EMAIL_USECASES
+@{
+       <h2 class="pg">Control Operation</h2>
+Control Operations are a set of operations to manage Email MAPI Layer  initialization.
+The Application which will use the MAPIs MUST initialize IPC proxy and conntect to Email FW database before calling other APIs.
+And it MUST finalize IPC proxy and disconnect to the DB if the application doesn't use APIs.
+
+<table>
+<tr><td>API</td>
+<td>Return Value / Exceptions</td></tr>
+<tr><td>int email_init_storage(void)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_open_db(void)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure
+@n Remarks:
+@n Application should call email_close_db once db operation is over</td></tr>
+<tr><td>int email_close_db(void)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure
+@n Remarks: - 
+@n This API should be called only if email_open_db () is called.</td></tr>
+<tr><td>int email_service_begin(void)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure</td></tr>
+<tr><td>int email_service_end(void)</td>
+<td>Returns EMAIL_ERROR_NONE on success or negative value on failure
+@n Remarks:
+@n This API should be called only if email_service_begin () is called.</td></tr>
+</table>
+<b>Sample Code</b>
+@li Initialize and Finalize Email MAPI Layer
+@code
+int err = EMAIL_ERROR_NONE;
+/*  Initialize Email MAPI Layer before calling other MAPIs */
+if(EMAIL_ERROR_NONE == email_service_begin())
+{
+       if(EMAIL_ERROR_NONE != email_open_db())
+       {
+               return false;
+       }
+       if(EMAIL_ERROR_NONE != email_init_storage())      
+       {
+               return false;
+       }
+}
+
+/*  Call other MAPIs */
+
+......
+
+/*  Finalize Email MAPI Layer when finishing application */
+err = email_close_db();
+err = email_service_end();
+@endcode
+
+<b>Flow Diagram</b>
+@image html email_image011.png
+@}
+
+@addtogroup Email_Feature
+@{
+<h1 class="pg">System Configuration</h1>
+       <h2 class="pg">Files to be included</h2>
+email-api.h
+@n email-types.h
+
+       <h2 class="pg">System Initialization and De-Initialization</h2>
+email_service_begin is used to initialize email-service at boot time.
+@n email_service_end is used to deinitialize email-service at shutdown. 
+@n These two are separate executables.
+
+       <h2 class="pg">Variable Configuration</h2>
+NA
+
+       <h2 class="pg">Build Environment</h2>
+If the Application wants to use email-service Module, make sure that the following package should be included in the Makefile.
+
+email-service-dev
+
+       <h2 class="pg">Runtime Environment</h2>
+NA
+@}
+
+@defgroup EMAL_Appendix 4. Reference
+@ingroup EMAILSVC
+@{
+<h1 class="pg">Appendix</h1>
+       <h2 class="pg">Email</h2>
+@image html email_image012.png
+
+- Alice composed a message using MUA (Mail User Agent). Alice enters the e-mail address of her correspondent, and hits the "send" button.
+- MUA format the message using MIME and uses Simple mail Transfer Protocol to send the message to local MTA (Mail Transfer Agent) i,e smtp.a.org run by Alices ISP (Internet Service provider).
+- The MTA looks at the destination address provided in the SMTP protocol i,e bob@b.org. An Internet e-mail address is a string of the form localpart@exampledomain. The part before the @ sign is the local part of the address, often the username of the recipient, and the part after the @ sign is a domain name. The MTA resolves a domain name to determine the fully qualified domain name of the mail exchange server in the Domain Name System (DNS).
+- The DNS Server for the b.org domain, ns.b.org, responds with an MX Records listing the mail exchange servers for that domain, in this case mx.b.org, a server run by Bob's ISP. 
+- smtp.a.org sends the message to mx.b.org using SMTP, which delivers it to the mailbox of the user bob. 
+- Bob presses the "get mail" button in his MUA, which picks up the message using the Post Office Protocol (POP3).
+
+       <h2 class="pg">RFC</h2>
+-# RFC 2821-SMTP(Simple Mail Transfer Protocol)
+-# RFC 1939-POP3(Post Office Protocol)
+-# RFC 3501-IMAP4(Internate message protocol)
+@}
+
+*/
+
+/**
+* @defgroup  EMAILSVC
+ @{
+*      @defgroup EMAIL_USECASES 3. API Description
+*
+@{
+<h1 class="pg">API Description</h1>
+This section describes APIs and shows the example of using them.
+@}
+ @}
+*/
+
old mode 100644 (file)
new mode 100755 (executable)
index c6d50b8..292bdd6
@@ -1,40 +1,50 @@
 Name:       email-service
 Summary:    E-mail Framework Middleware package
-Version:    0.2.9
-Release:    3
+Version:    0.10.85
+Release:    1
 Group:      System/Libraries
 License:    TBD
 Source0:    %{name}-%{version}.tar.gz
+Source1:    email.service
+Requires: connman
+Requires: webkit2-efl
 Requires(post):    /sbin/ldconfig
+Requires(post):    systemd
 Requires(post):    /usr/bin/sqlite3
 Requires(post):    /usr/bin/vconftool
+Requires(preun):   systemd
 Requires(postun):  /sbin/ldconfig
+Requires(postun):  systemd
 BuildRequires:  cmake
 BuildRequires:  pkgconfig(glib-2.0)
 BuildRequires:  pkgconfig(gthread-2.0)
 BuildRequires:  pkgconfig(aul)
+BuildRequires:  pkgconfig(vconf-internal-keys)
 BuildRequires:  pkgconfig(vconf)
-BuildRequires:  pkgconfig(heynoti)
 BuildRequires:  pkgconfig(dlog)
 BuildRequires:  pkgconfig(db-util)
-BuildRequires:  pkgconfig(dnet)
 BuildRequires:  pkgconfig(dbus-1)
 BuildRequires:  pkgconfig(dbus-glib-1)
-BuildRequires:  pkgconfig(contacts-service)
+BuildRequires:  pkgconfig(contacts-service2)
 BuildRequires:  pkgconfig(uw-imap-toolkit)
-BuildRequires:  pkgconfig(drm-service)
+BuildRequires:  pkgconfig(drm-client)
 BuildRequires:  pkgconfig(openssl)
 BuildRequires:  pkgconfig(alarm-service)
 BuildRequires:  pkgconfig(mm-player)
-BuildRequires:  pkgconfig(devman_haptic)
+BuildRequires:  pkgconfig(mm-session)
 BuildRequires:  pkgconfig(secure-storage)
-BuildRequires:  pkgconfig(quickpanel)
 BuildRequires:  pkgconfig(notification)
 BuildRequires:  pkgconfig(accounts-svc)
+BuildRequires:  pkgconfig(libsystemd-daemon)
+BuildRequires:  pkgconfig(capi-base-common)
 BuildRequires:  pkgconfig(libcurl)
+BuildRequires:  pkgconfig(libxml-2.0)
+BuildRequires:  pkgconfig(gconf-2.0)
+BuildRequires:  pkgconfig(cert-svc)
+BuildRequires:  pkgconfig(badge)
+BuildRequires:  pkgconfig(feedback)
 
 
-BuildRoot:  %{_tmppath}/%{name}-%{version}-build
 
 %description
 E-mail Framework Middleware Library/Binary package
@@ -49,15 +59,6 @@ Requires:   %{name} = %{version}-%{release}
 E-mail Framework Middleware Development package
 
 
-%package tools
-Summary:    Tools for use with email-service
-Group:      Development/Libraries
-Requires:   %{name} = %{version}-%{release}
-
-%description tools
-Tools for use with email-service
-
-
 %prep
 %setup -q
 
@@ -69,15 +70,16 @@ export LDFLAGS="${LDFLAGS} -Wl,--hash-style=both -Wl,--rpath=%{_prefix}/lib -Wl,
 
 cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix}
 
-# Call make instruction with smp support
-#make %{?jobs:-j%jobs}
-make
+make %{?_smp_mflags}
 
 %install
+mkdir -p %{buildroot}/usr/share/license
 %make_install
 
-%clean
-rm -rf %{buildroot}
+mkdir -p %{buildroot}%{_libdir}/systemd/user/tizen-middleware.target.wants
+install -m 0644 %SOURCE1 %{buildroot}%{_libdir}/systemd/user/
+ln -sf ../email.service %{buildroot}%{_libdir}/systemd/user/tizen-middleware.target.wants/
+
 
 %post
 /sbin/ldconfig
@@ -85,186 +87,41 @@ rm -rf %{buildroot}
 #################################################################
 # Add preset account information
 #################################################################
-echo "[EMAIL-SERVICE] Start adding preset account information..."
-
-#################################################################
-# Email Settings
-#################################################################
+echo "[EMAIL-SERVICE] Start adding preset account information..." 
 
-## Setting
-# Sending
-vconftool set -g 5000 -t bool   db/Services/Email/Sending/KeepCopy                      "1"
-vconftool set -g 5000 -t bool   db/Services/Email/Sending/SendMeCopy            "1"
-vconftool set -g 5000 -t bool   db/Services/Email/Sending/ReqDeliveryRep        "0"
-vconftool set -g 5000 -t bool   db/Services/Email/Sending/ReqReadRep            "0"
-vconftool set -g 5000 -t int    db/Services/Email/Sending/Priority                      "1"
-vconftool set -g 5000 -t string db/Services/Email/Sending/ActiveAccount         ""
-vconftool set -g 5000 -t bool   db/Services/Email/Sending/IncBodyReply          "1"
-vconftool set -g 5000 -t bool   db/Services/Email/Sending/IncAttachFwd          "1"
-# Receiving
-vconftool set -g 5000 -t int    db/Services/Email/Receiving/AutoPoll            "0"
-vconftool set -g 5000 -t int    db/Services/Email/Receiving/PollTime            "0"
-vconftool set -g 5000 -t int    db/Services/Email/Receiving/SendReadRep         "2"
-vconftool set -g 5000 -t int    db/Services/Email/Receiving/Reclimit            "0"
-vconftool set -g 5000 -t int    db/Services/Email/Receiving/FetchOption         "0"
-vconftool set -g 5000 -t bool   db/Services/Email/Receiving/KeepServer          "1"
-vconftool set -g 5000 -t int    db/Services/Email/Receiving/ServDelOption       "1"
-
-vconftool set -g 5000 -t int    db/Services/Email/NbAccount                     "6"
-
-## Accounts
-
-# Gmail
-vconftool set -g 5000 -t string db/Services/Email/1/General/NetworkName         "default"
-vconftool set -g 5000 -t string db/Services/Email/1/General/AccountName         "Gmail"
-vconftool set -g 5000 -t string db/Services/Email/1/General/EmailAddr           ""
-vconftool set -g 5000 -t string db/Services/Email/1/General/UserId                      ""
-vconftool set -g 5000 -t string db/Services/Email/1/General/Password            ""
-vconftool set -g 5000 -t string db/Services/Email/1/General/LoginType           "username_type"
-
-# MailboxType : pop3(0), imap4(1) -> pop3(1), imap4(2) in email-service
-vconftool set -g 5000 -t int    db/Services/Email/1/Incoming/MailboxType        "1"
-vconftool set -g 5000 -t string db/Services/Email/1/Incoming/ServAddr       "imap.gmail.com"
-vconftool set -g 5000 -t int    db/Services/Email/1/Incoming/Port           "993"
-vconftool set -g 5000 -t int    db/Services/Email/1/Incoming/Secure         "1"
-vconftool set -g 5000 -t bool   db/Services/Email/1/Incoming/Apop                       "0"
-vconftool set -g 5000 -t bool   db/Services/Email/1/Incoming/AutoEmailSync      "0"
-vconftool set -g 5000 -t bool   db/Services/Email/1/Incoming/IncludeAttach      "0"
-vconftool set -g 5000 -t int    db/Services/Email/1/Incoming/ImapFetchOpt       "1"
-
-vconftool set -g 5000 -t string db/Services/Email/1/Outgoing/ServAddr           "smtp.gmail.com"
-vconftool set -g 5000 -t int    db/Services/Email/1/Outgoing/Port                       "465"
-vconftool set -g 5000 -t bool   db/Services/Email/1/Outgoing/SmtpAuth           "0"
-vconftool set -g 5000 -t int    db/Services/Email/1/Outgoing/Secure                     "1"
-vconftool set -g 5000 -t bool   db/Services/Email/1/Outgoing/SameIdPwd          "1"
-vconftool set -g 5000 -t bool   db/Services/Email/1/Outgoing/PopBeforeSmtp      "0"
-
-# Hotmail
-vconftool set -g 5000 -t string db/Services/Email/2/General/NetworkName         "default"
-vconftool set -g 5000 -t string db/Services/Email/2/General/AccountName         "Hotmail"
-vconftool set -g 5000 -t string db/Services/Email/2/General/EmailAddr           ""
-vconftool set -g 5000 -t string db/Services/Email/2/General/UserId                      ""
-vconftool set -g 5000 -t string db/Services/Email/2/General/Password            ""
-vconftool set -g 5000 -t string db/Services/Email/2/General/LoginType           "username_type"
-
-# MailboxType : pop3(0), imap4(1) -> pop3(1), imap4(2) in email-service
-vconftool set -g 5000 -t int    db/Services/Email/2/Incoming/MailboxType        "0"
-vconftool set -g 5000 -t string db/Services/Email/2/Incoming/ServAddr       "pop3.live.com"
-vconftool set -g 5000 -t int    db/Services/Email/2/Incoming/Port           "995"
-vconftool set -g 5000 -t int    db/Services/Email/2/Incoming/Secure         "1"
-vconftool set -g 5000 -t bool   db/Services/Email/2/Incoming/Apop                       "0"
-vconftool set -g 5000 -t bool   db/Services/Email/2/Incoming/AutoEmailSync      "0"
-vconftool set -g 5000 -t bool   db/Services/Email/2/Incoming/IncludeAttach      "0"
-vconftool set -g 5000 -t int    db/Services/Email/2/Incoming/ImapFetchOpt       "1"
-
-vconftool set -g 5000 -t string db/Services/Email/2/Outgoing/ServAddr           "smtp.live.com"
-vconftool set -g 5000 -t int    db/Services/Email/2/Outgoing/Port                       "587"
-vconftool set -g 5000 -t bool   db/Services/Email/2/Outgoing/SmtpAuth           "0"
-vconftool set -g 5000 -t int    db/Services/Email/2/Outgoing/Secure                     "2"
-vconftool set -g 5000 -t bool   db/Services/Email/2/Outgoing/SameIdPwd          "1"
-vconftool set -g 5000 -t bool   db/Services/Email/2/Outgoing/PopBeforeSmtp      "0"
-
-# AOL
-vconftool set -g 5000 -t string db/Services/Email/3/General/NetworkName         "default"
-vconftool set -g 5000 -t string db/Services/Email/3/General/AccountName         "AOL"
-vconftool set -g 5000 -t string db/Services/Email/3/General/EmailAddr           ""
-vconftool set -g 5000 -t string db/Services/Email/3/General/UserId                      ""
-vconftool set -g 5000 -t string db/Services/Email/3/General/Password            ""
-vconftool set -g 5000 -t string db/Services/Email/3/General/LoginType           "username_type"
-
-# MailboxType : pop3(0), imap4(1) -> pop3(1), imap4(2) in email-service
-vconftool set -g 5000 -t int    db/Services/Email/3/Incoming/MailboxType        "1"
-vconftool set -g 5000 -t string db/Services/Email/3/Incoming/ServAddr       "imap.aol.com"
-vconftool set -g 5000 -t int    db/Services/Email/3/Incoming/Port           "143"
-vconftool set -g 5000 -t int    db/Services/Email/3/Incoming/Secure         "0"
-vconftool set -g 5000 -t bool   db/Services/Email/3/Incoming/Apop                       "0"
-vconftool set -g 5000 -t bool   db/Services/Email/3/Incoming/AutoEmailSync      "0"
-vconftool set -g 5000 -t bool   db/Services/Email/3/Incoming/IncludeAttach      "0"
-vconftool set -g 5000 -t int    db/Services/Email/3/Incoming/ImapFetchOpt       "0"
-
-vconftool set -g 5000 -t string db/Services/Email/3/Outgoing/ServAddr           "smtp.aol.com"
-vconftool set -g 5000 -t int    db/Services/Email/3/Outgoing/Port                       "587"
-vconftool set -g 5000 -t bool   db/Services/Email/3/Outgoing/SmtpAuth           "0"
-vconftool set -g 5000 -t int    db/Services/Email/3/Outgoing/Secure                     "0"
-vconftool set -g 5000 -t bool   db/Services/Email/3/Outgoing/SameIdPwd          "1"
-vconftool set -g 5000 -t bool   db/Services/Email/3/Outgoing/PopBeforeSmtp      "0"
-
-# Yahoo
-vconftool set -g 5000 -t string db/Services/Email/6/General/NetworkName         "default"
-vconftool set -g 5000 -t string db/Services/Email/6/General/AccountName         "Yahoomail"
-vconftool set -g 5000 -t string db/Services/Email/6/General/EmailAddr           ""
-vconftool set -g 5000 -t string db/Services/Email/6/General/UserId                      ""
-vconftool set -g 5000 -t string db/Services/Email/6/General/Password            ""
-vconftool set -g 5000 -t string db/Services/Email/6/General/LoginType           "username_type"
-
-# MailboxType : pop3(0), imap4(1) -> pop3(1), imap4(2) in email-service
-vconftool set -g 5000 -t int    db/Services/Email/6/Incoming/MailboxType        "0"
-vconftool set -g 5000 -t string db/Services/Email/6/Incoming/ServAddr       "pop.mail.yahoo.co.kr"
-vconftool set -g 5000 -t int    db/Services/Email/6/Incoming/Port           "995"
-vconftool set -g 5000 -t int    db/Services/Email/6/Incoming/Secure         "1"
-vconftool set -g 5000 -t bool   db/Services/Email/6/Incoming/Apop                       "0"
-vconftool set -g 5000 -t bool   db/Services/Email/6/Incoming/AutoEmailSync      "0"
-vconftool set -g 5000 -t bool   db/Services/Email/6/Incoming/IncludeAttach      "0"
-vconftool set -g 5000 -t int    db/Services/Email/6/Incoming/ImapFetchOpt       "1"
-
-vconftool set -g 5000 -t string db/Services/Email/6/Outgoing/ServAddr           "smtp.mail.yahoo.co.kr"
-vconftool set -g 5000 -t int    db/Services/Email/6/Outgoing/Port                       "465"
-vconftool set -g 5000 -t bool   db/Services/Email/6/Outgoing/SmtpAuth           "0"
-vconftool set -g 5000 -t int    db/Services/Email/6/Outgoing/Secure                     "1"
-vconftool set -g 5000 -t bool   db/Services/Email/6/Outgoing/SameIdPwd          "1"
-vconftool set -g 5000 -t bool   db/Services/Email/6/Outgoing/PopBeforeSmtp      "0"
-
-vconftool set -t string db/email/preset_account/aol/sending_address   "smtp.aol.com"
-vconftool set -t int    db/email/preset_account/aol/sending_port      "587"
-vconftool set -t int    db/email/preset_account/aol/sending_ssl       "0"
-vconftool set -t int    db/email/preset_account/aol/receiving_type    "2"
-vconftool set -t string db/email/preset_account/aol/receiving_address "imap.aol.com"
-vconftool set -t int    db/email/preset_account/aol/receiving_port    "143"
-vconftool set -t int    db/email/preset_account/aol/receiving_ssl     "0"
-
-vconftool set -t string db/email/preset_account/gmail/sending_address   "smtp.gmail.com"
-vconftool set -t int    db/email/preset_account/gmail/sending_port      "465"
-vconftool set -t int    db/email/preset_account/gmail/sending_ssl       "1"
-vconftool set -t int    db/email/preset_account/gmail/receiving_type    "2"
-# for POP3 server
-#vconftool set -t string db/email/preset_account/gmail/receiving_address "pop.gmail.com"
-#vconftool set -t int    db/email/preset_account/gmail/receiving_port    "995"
-# for IMAP4 server
-vconftool set -t string db/email/preset_account/gmail/receiving_address "imap.gmail.com"
-vconftool set -t int    db/email/preset_account/gmail/receiving_port    "993"
-vconftool set -t int    db/email/preset_account/gmail/receiving_ssl     "1"
-
-vconftool set -t string db/email/preset_account/yahoo/sending_address   "smtp.mail.yahoo.co.kr"
-vconftool set -t int    db/email/preset_account/yahoo/sending_port      "465"
-vconftool set -t int    db/email/preset_account/yahoo/sending_ssl       "1"
-vconftool set -t int    db/email/preset_account/yahoo/receiving_type    "1"
-vconftool set -t string db/email/preset_account/yahoo/receiving_address "pop.mail.yahoo.co.kr"
-vconftool set -t int    db/email/preset_account/yahoo/receiving_port    "995"
-vconftool set -t int    db/email/preset_account/yahoo/receiving_ssl     "1"
-
-vconftool set -t string db/email/preset_account/hotmail/sending_address   "smtp.live.com"
-vconftool set -t int    db/email/preset_account/hotmail/sending_port      "587"
-vconftool set -t int    db/email/preset_account/hotmail/sending_ssl       "2"
-vconftool set -t int    db/email/preset_account/hotmail/receiving_type    "1"
-vconftool set -t string db/email/preset_account/hotmail/receiving_address "pop3.live.com"
-vconftool set -t int    db/email/preset_account/hotmail/receiving_port    "995"
-vconftool set -t int    db/email/preset_account/hotmail/receiving_ssl     "1"
-
-# for Active Sync       - Let email app create this key
-#vconftool set -t int    db/email_handle/active_sync_handle     "0"
-
-# for contact sync - sync from the first contact change
-vconftool set -t int    db/email/last_sync_time "0"
-
-# for contact sync - sync from the first contact change
-vconftool set -t int    db/email/slot_size "100"
+################################################################################################
 
-# for badge
-vconftool set -t int    db/badge/org.tizen.email "0"
+# for default mail slot szie
+vconftool set -t int    db/private/email-service/slot_size "100"        -g 6514
 
+# for latest mail id
+vconftool set -t int    db/private/email-service/latest_mail_id "0"     -g 6514
 
-echo "[EMAIL-SERVICE] Finish adding preset account information"
+# for default account id
+vconftool set -t int    db/private/email-service/default_account_id "0" -g 6514
 
+# for badge
+vconftool set -t int    db/badge/com.samsung.email "0" -g 6514
+
+# for default account id
+vconftool set -t int    memory/sync/email "0" -i -g 6514
+
+# for priority send 
+vconftool set -t string db/private/email-service/noti_ringtone_path "Whistle.mp3" -g 6514
+vconftool set -t int    db/private/email-service/noti_rep_type "0" -g 6514
+vconftool set -t bool   db/private/email-service/noti_notification_ticker "0" -g 6514
+vconftool set -t bool   db/private/email-service/noti_display_content_ticker "0" -g 6514
+vconftool set -t bool   db/private/email-service/noti_badge_ticker "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/1 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/2 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/3 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/4 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/5 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/6 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/7 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/8 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/9 "0" -i -g 6514
+vconftool set -t int    db/private/email-service/noti_private_id/10 "0" -i -g 6514
 
 #################################################################
 # Set executin script
@@ -274,11 +131,20 @@ EMAIL_SERVICE_EXEC_SCRIPT=/etc/rc.d/init.d/email-service
 EMAIL_SERVICE_BOOT_SCRIPT=/etc/rc.d/rc3.d/S70email-service
 EMAIL_SERVICE_FASTBOOT_SCRIPT=/etc/rc.d/rc5.d/S70email-service
 echo '#!/bin/sh' > ${EMAIL_SERVICE_EXEC_SCRIPT}
-echo '/usr/bin/email-service &' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo 'account_count=$(sqlite3 /opt/usr/dbspace/.email-service.db "select COUNT(*) from mail_account_tbl")' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo 'if [ "$(echo "$account_count" | cut -c0-1)" == "0" ]' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo 'then' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo ' echo 'There is no account'' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo 'elif [ "$(echo "$account_count" | cut -c0-1)" == "" ]' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo 'then' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo ' echo 'DB failure'' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo 'else' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo ' /usr/bin/email-service & ' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
+echo 'fi' >> ${EMAIL_SERVICE_EXEC_SCRIPT}
 chmod 755 ${EMAIL_SERVICE_EXEC_SCRIPT}
 rm -rf ${EMAIL_SERVICE_BOOT_SCRIPT}
 rm -rf ${EMAIL_SERVICE_FASTBOOT_SCRIPT}
-ln -s ${EMAIL_SERVICE_EXEC_SCRIPT} ${EMAIL_SERVICE_BOOT_SCRIPT}
+ln -s ${EMAIL_SERVICE_EXEC_SCRIPT} ${EMAIL_SERVICE_BOOT_SCRIPT} 
 ln -s ${EMAIL_SERVICE_EXEC_SCRIPT} ${EMAIL_SERVICE_FASTBOOT_SCRIPT}
 echo "[EMAIL-SERVICE] Finish executing script ..."
 
@@ -286,289 +152,291 @@ echo "[EMAIL-SERVICE] Finish executing script ..."
 # Create DB file and tables.
 #################################################################
 echo "[EMAIL-SERVICE] Creating Email Tables ..."
-sqlite3 /opt/dbspace/.email-service.db 'PRAGMA journal_mode = PERSIST;
-CREATE TABLE mail_account_tbl
-(
-        account_bind_type INTEGER,
-        account_name varchar(51),
-        receiving_server_type INTEGER,
-        receiving_server_addr varchar(51),
-        email_addr varchar(129),
-        user_name varchar(51),
-        password varchar(51),
-        retrieval_mode INTEGER,
-        port_num INTEGER,
-        use_security INTEGER,
-        sending_server_type INTEGER,
-        sending_server_addr varchar(51),
-        sending_port_num INTEGER,
-        sending_auth INTEGER,
-        sending_security INTEGER,
-        sending_user varchar(51),
-        sending_password varchar(51),
-        display_name varchar(31),
-        reply_to_addr varchar(129),
-        return_addr varchar(129),
-        account_id INTEGER,
-        keep_on_server INTEGER,
-        flag1 INTEGER,
-        flag2 INTEGER,
-        pop_before_smtp INTEGER,
-        apop INTEGER,
-        logo_icon_path varchar(256),
-        preset_account INTEGER,
-        target_storage INTEGER,
-        check_interval INTEGER,
-        priority INTEGER,
-        keep_local_copy INTEGER,
-        req_delivery_receipt INTEGER,
-        req_read_receipt INTEGER,
-        download_limit INTEGER,
-        block_address INTEGER,
-        block_subject INTEGER,
-        display_name_from varchar(256),
-        reply_with_body INTEGER,
-        forward_with_files INTEGER,
-        add_myname_card INTEGER,
-        add_signature INTEGER,
-        signature varchar(256),
-        add_my_address_to_bcc INTEGER,
-        my_account_id INTEGER,
-        index_color INTEGER
+mkdir -p /opt/usr
+mkdir -p /opt/usr/dbspace
+sqlite3 /opt/usr/dbspace/.email-service.db 'PRAGMA journal_mode = PERSIST;
+CREATE TABLE mail_account_tbl 
+( 
+       account_id                               INTEGER PRIMARY KEY,
+       account_name                             VARCHAR(51),
+       logo_icon_path                           VARCHAR(256),
+       user_data                                BLOB,
+       user_data_length                         INTEGER,
+       account_svc_id                           INTEGER,
+       sync_status                              INTEGER,
+       sync_disabled                            INTEGER,
+       default_mail_slot_size                   INTEGER,
+       user_display_name                        VARCHAR(31),
+       user_email_address                       VARCHAR(129),
+       reply_to_address                         VARCHAR(129),
+       return_address                           VARCHAR(129),
+       incoming_server_type                     INTEGER,
+       incoming_server_address                  VARCHAR(51),
+       incoming_server_port_number              INTEGER,
+       incoming_server_user_name                VARCHAR(51),
+       incoming_server_password                 VARCHAR(51),
+       incoming_server_secure_connection        INTEGER,
+       retrieval_mode                           INTEGER,
+       keep_mails_on_pop_server_after_download  INTEGER,
+       check_interval                           INTEGER,
+       auto_download_size                       INTEGER,
+       outgoing_server_type                     INTEGER,
+       outgoing_server_address                  VARCHAR(51),
+       outgoing_server_port_number              INTEGER,
+       outgoing_server_user_name                VARCHAR(51),
+       outgoing_server_password                 VARCHAR(51),
+       outgoing_server_secure_connection        INTEGER,
+       outgoing_server_need_authentication      INTEGER,
+       outgoing_server_use_same_authenticator   INTEGER,
+       priority                                 INTEGER,
+       keep_local_copy                          INTEGER,
+       req_delivery_receipt                     INTEGER,
+       req_read_receipt                         INTEGER,
+       download_limit                           INTEGER,
+       block_address                            INTEGER,
+       block_subject                            INTEGER,
+       display_name_from                        VARCHAR(256),
+       reply_with_body                          INTEGER,
+       forward_with_files                       INTEGER,
+       add_myname_card                          INTEGER,
+       add_signature                            INTEGER,
+       signature                                VARCHAR(256),
+       add_my_address_to_bcc                    INTEGER,
+       pop_before_smtp                          INTEGER,
+       incoming_server_requires_apop            INTEGER,
+       smime_type                               INTEGER,
+       certificate_path                         VARCHAR(256),
+       cipher_type                              INTEGER,
+       digest_type                              INTEGER
 );
 
-CREATE TABLE mail_attachment_tbl
-(
-        attachment_id       INTEGER PRIMARY KEY,
-        attachment_name     varchar(257),
-        attachment_path     varchar(257),
-        attachment_size     INTEGER,
-        mail_id             INTEGER,
-        account_id          INTEGER,
-        mailbox_name        varchar(129),
-        file_yn             INTEGER,
-        flag1               INTEGER,
-        flag2               INTEGER,
-        flag3               INTEGER
+CREATE TABLE mail_attachment_tbl 
+( 
+       attachment_id                            INTEGER PRIMARY KEY,
+       attachment_name                          VARCHAR(257),
+       attachment_path                          VARCHAR(257),
+       attachment_size                          INTEGER,
+       mail_id                                  INTEGER,
+       account_id                               INTEGER,
+       mailbox_id                               INTEGER,
+       attachment_save_status                   INTEGER,
+       attachment_drm_type                      INTEGER,
+       attachment_drm_method                    INTEGER,
+       attachment_inline_content_status         INTEGER,
+       attachment_mime_type                     VARCHAR(257)
 );
 
-CREATE TABLE mail_box_tbl
-(
-        mailbox_id                  INTEGER,
-        account_id                  INTEGER,
-        local_yn                    INTEGER,
-        mailbox_name                varchar(256),
-        mailbox_type                INTEGER,
-        alias                       varchar(256),
-        sync_with_server_yn         INTEGER,
-        modifiable_yn               INTEGER,
-        total_mail_count_on_server  INTEGER,
-        has_archived_mails          INTEGER,
-        mail_slot_size              INTEGER
+CREATE TABLE mail_box_tbl 
+(    
+       mailbox_id                       INTEGER PRIMARY KEY,
+       account_id                       INTEGER,
+       local_yn                         INTEGER,
+       mailbox_name                     VARCHAR(256),    
+       mailbox_type                     INTEGER,    
+       alias                            VARCHAR(256),    
+       deleted_flag                     INTEGER,    
+       modifiable_yn                    INTEGER,    
+       total_mail_count_on_server       INTEGER,
+       has_archived_mails               INTEGER,    
+       mail_slot_size                   INTEGER,
+       no_select                        INTEGER,
+       last_sync_time                   DATETIME
 );
-CREATE TABLE mail_read_mail_uid_tbl
-(
-        account_id            INTEGER ,
-        local_mbox                 varchar(129)  ,
-        local_uid             INTEGER ,
-        mailbox_name       varchar(129)  ,
-        s_uid                       varchar(129)  ,
-        data1                       INTEGER ,
-        data2                        varchar(257)  ,
-        flag                    INTEGER ,
-        idx_num              INTEGER  PRIMARY KEY
+
+CREATE TABLE mail_read_mail_uid_tbl          
+(    
+       account_id                       INTEGER ,
+       mailbox_id                       INTEGER ,
+       local_uid                        INTEGER ,
+       mailbox_name                     VARCHAR(256) ,
+       s_uid                            VARCHAR(129) ,
+       data1                            INTEGER ,
+       data2                            VARCHAR(257) ,
+       flag                             INTEGER ,
+       idx_num                          INTEGER PRIMARY KEY
 );
-CREATE TABLE mail_rule_tbl
-(
-        account_id     INTEGER ,
-        rule_id        INTEGER  PRIMARY KEY,
-        type           INTEGER ,
-        value          varchar(257)  ,
-        action_type    INTEGER ,
-        dest_mailbox   varchar(129),
-        flag1          INTEGER  ,
-        flag2          INTEGER
+
+CREATE TABLE mail_rule_tbl          
+(    
+       account_id                       INTEGER ,
+       rule_id                          INTEGER PRIMARY KEY,
+       type                             INTEGER ,
+       value                            VARCHAR(257)  ,
+       action_type                      INTEGER ,
+       target_mailbox_id                INTEGER ,
+       flag1                            INTEGER ,
+       flag2                            INTEGER    
 );
+
 CREATE TABLE mail_tbl
 (
-        mail_id                   INTEGER,
-        account_id                INTEGER,
-        mailbox_name              VARCHAR(129),
-        mailbox_type              INTEGER,
-        subject                   UCS2TEXT,
-        date_time                 VARCHAR(129),
-        server_mail_status        INTEGER,
-        server_mailbox_name       VARCHAR(129),
-        server_mail_id            VARCHAR(129),
-        message_id                VARCHAR(257),
-        full_address_from         UCS2TEXT,
-        full_address_reply        UCS2TEXT,
-        full_address_to           UCS2TEXT,
-        full_address_cc           UCS2TEXT,
-        full_address_bcc          UCS2TEXT,
-        full_address_return       UCS2TEXT,
-        email_address_sender      UCS2TEXT collation user1,
-        email_address_recipient   UCS2TEXT collation user1,
-        alias_sender              UCS2TEXT,
-        alias_recipient           UCS2TEXT,
-        body_download_status      INTEGER,
-        file_path_plain           VARCHAR(257),
-        file_path_html            VARCHAR(257),
-        mail_size                 INTEGER,
-        mail_status               INTEGER,
-        DRM_status                INTEGER,
-        priority                  INTEGER,
-        save_status               INTEGER,
-        lock_status               INTEGER,
-        report_status             INTEGER,
-        attachment_count          INTEGER,
-        inline_content_count      INTEGER,
-        thread_id                 INTEGER,
-        thread_item_count         INTEGER,
-        preview_text              UCS2TEXT,
-        meeting_request_status    INTEGER
+       mail_id                          INTEGER PRIMARY KEY,
+       account_id                       INTEGER,
+       mailbox_id                       INTEGER,
+       mailbox_name                     VARCHAR(129),
+       mailbox_type                     INTEGER,
+       subject                          TEXT,
+       date_time                        DATETIME,
+       server_mail_status               INTEGER,
+       server_mailbox_name              VARCHAR(129),
+       server_mail_id                   VARCHAR(129),
+       message_id                       VARCHAR(257),
+       reference_mail_id                INTEGER,
+       full_address_from                TEXT,
+       full_address_reply               TEXT,
+       full_address_to                  TEXT,
+       full_address_cc                  TEXT,
+       full_address_bcc                 TEXT,
+       full_address_return              TEXT,
+       email_address_sender             TEXT collation user1,
+       email_address_recipient          TEXT collation user1,
+       alias_sender                     TEXT,
+       alias_recipient                  TEXT,
+       body_download_status             INTEGER,
+       file_path_plain                  VARCHAR(257),
+       file_path_html                   VARCHAR(257),
+       file_path_mime_entity            VARCHAR(257),
+       mail_size                        INTEGER,
+       flags_seen_field                 BOOLEAN,
+       flags_deleted_field              BOOLEAN,
+       flags_flagged_field              BOOLEAN,
+       flags_answered_field             BOOLEAN,
+       flags_recent_field               BOOLEAN,
+       flags_draft_field                BOOLEAN,
+       flags_forwarded_field            BOOLEAN,
+       DRM_status                       INTEGER,
+       priority                         INTEGER,
+       save_status                      INTEGER,
+       lock_status                      INTEGER,
+       report_status                    INTEGER,
+       attachment_count                 INTEGER,
+       inline_content_count             INTEGER,
+       thread_id                        INTEGER,
+       thread_item_count                INTEGER,
+       preview_text                     TEXT, 
+       meeting_request_status           INTEGER,
+       message_class                    INTEGER,
+       digest_type                      INTEGER,
+       smime_type                       INTEGER,
+       FOREIGN KEY(account_id)          REFERENCES mail_account_tbl(account_id)
 );
+
 CREATE TABLE mail_meeting_tbl
 (
-        mail_id             INTEGER PRIMARY KEY,
-        account_id          INTEGER,
-        mailbox_name        UCS2TEXT ,
-        meeting_response        INTEGER,
-        start_time          INTEGER,
-        end_time            INTEGER,
-        location            UCS2TEXT ,
-        global_object_id    UCS2TEXT ,
-        offset              INTEGER,
-        standard_name       UCS2TEXT ,
-        standard_time_start_date          INTEGER,
-        standard_bias       INTEGER,
-        daylight_name       UCS2TEXT ,
-        daylight_time_start_date          INTEGER,
-        daylight_bias       INTEGER
+       mail_id                          INTEGER PRIMARY KEY,
+       account_id                       INTEGER,
+       mailbox_id                       INTEGER,
+       meeting_response                 INTEGER,
+       start_time                       INTEGER,
+       end_time                         INTEGER,
+       location                         TEXT ,
+       global_object_id                 TEXT ,
+       offset                           INTEGER,
+       standard_name                    TEXT ,
+       standard_time_start_date         INTEGER,
+       standard_bias                    INTEGER,
+       daylight_name                    TEXT ,
+       daylight_time_start_date         INTEGER,
+       daylight_bias                    INTEGER
 );
-CREATE TABLE mail_local_activity_tbl
-(
-        activity_id              INTEGER,
-        account_id       INTEGER,
-        mail_id                  INTEGER,
-        activity_type    INTEGER,
-        server_mailid    VARCHAR(129),
-        src_mbox                 VARCHAR(129),
-        dest_mbox                VARCHAR(129)
+
+CREATE TABLE mail_local_activity_tbl  
+(  
+       activity_id                      INTEGER,
+       account_id                       INTEGER,
+       mail_id                          INTEGER,
+       activity_type                    INTEGER, 
+       server_mailid                    VARCHAR(129),
+       src_mbox                         VARCHAR(129),
+       dest_mbox                        VARCHAR(129) 
 );
 
+CREATE TABLE mail_certificate_tbl 
+( 
+       certificate_id                   INTEGER,
+       issue_year                       INTEGER,
+       issue_month                      INTEGER,
+       issue_day                        INTEGER,
+       expiration_year                  INTEGER,
+       expiration_month                 INTEGER,
+       expiration_day                   INTEGER,
+       issue_organization_name          VARCHAR(256),
+       email_address                    VARCHAR(129),
+       subject_str                      VARCHAR(256),
+       filepath                         VARCHAR(256),
+       password                         VARCHAR(51)
+);
 
-CREATE UNIQUE INDEX mail_account_idx1 ON mail_account_tbl (account_bind_type, account_id);
+CREATE TABLE mail_task_tbl  
+(  
+       task_id                          INTEGER PRIMARY KEY,
+       task_type                        INTEGER,
+       task_status                      INTEGER,
+       task_priority                    INTEGER,
+       task_parameter_length            INTEGER, 
+       task_parameter                   BLOB,
+       date_time                        DATETIME
+);
+
+
+CREATE UNIQUE INDEX mail_account_idx1 ON mail_account_tbl (account_id);
 CREATE UNIQUE INDEX mail_attachment_idx1 ON mail_attachment_tbl (mail_id, attachment_id);
-CREATE UNIQUE INDEX mail_box_idx1 ON mail_box_tbl (account_id, local_yn, mailbox_name);
+CREATE UNIQUE INDEX mail_box_idx1 ON mail_box_tbl (mailbox_id);
 CREATE UNIQUE INDEX mail_idx1 ON mail_tbl (mail_id, account_id);
-CREATE UNIQUE INDEX mail_read_mail_uid_idx1 ON mail_read_mail_uid_tbl (account_id, local_mbox, local_uid, mailbox_name, s_uid);
+CREATE UNIQUE INDEX mail_read_mail_uid_idx1 ON mail_read_mail_uid_tbl (account_id, mailbox_id, local_uid, mailbox_name, s_uid);
 CREATE UNIQUE INDEX mail_meeting_idx1 ON mail_meeting_tbl (mail_id);
+CREATE UNIQUE INDEX task_idx1 ON mail_task_tbl (task_id);
 CREATE INDEX mail_idx_date_time ON mail_tbl (date_time);
 CREATE INDEX mail_idx_thread_item_count ON mail_tbl (thread_item_count);
 '
 
 echo "[EMAIL-SERVICE] Finish Creating Email Tables."
 
+chgrp 6006 /opt/usr/dbspace/.email-service.db*
+chmod 664 /opt/usr/dbspace/.email-service.db
+chmod 664 /opt/usr/dbspace/.email-service.db-journal
 
-#################################################################
-# Change file permission
-#################################################################
-#echo "[EMAIL-SERVICE] Start setting permission ..."
-# 1. libraries
-#chmod 644 /usr/lib/libemail-ipc.so.0.0.0
-#chmod 644 /usr/lib/libemail-core.so.0.0.0
-#chmod 644 /usr/lib/libemail-emn-storage.so.0.0.0
-#chmod 644 /usr/lib/libemail-base.so.0.0.0
-#chmod 644 /usr/lib/libem-storage.so.0.0.0
-#chmod 644 /usr/lib/libem-network.so.0.0.0
-#chmod 644 /usr/lib/libemail-mapi.so.0.0.0
-#chmod 644 /usr/lib/libem-storage.so
-#chmod 644 /usr/lib/libemail-base.so.0
-#chmod 644 /usr/lib/libem-network.so.0
-#chmod 644 /usr/lib/libemail-core.so.0
-#chmod 644 /usr/lib/libemail-emn-storage.so
-#chmod 644 /usr/lib/libemail-ipc.so
-#chmod 644 /usr/lib/libemail-mapi.so.0
-#chmod 644 /usr/lib/libem-storage.so.0
-#chmod 644 /usr/lib/libem-network.so
-#chmod 644 /usr/lib/libemail-ipc.so.0
-#chmod 644 /usr/lib/libemail-core.so
-#chmod 644 /usr/lib/libemail-base.so
-#chmod 644 /usr/lib/libemail-mapi.so
-#chmod 644 /usr/lib/libemail-emn-storage.so.0
-
-# 2. executables
-#chmod 700 /usr/bin/email-service_initDB
-#chmod 700 /usr/bin/email-service
-
-# 3. DB files
-chmod 644 /opt/dbspace/.email-service.db
-chmod 644 /opt/dbspace/.email-service.db-journal
+mkdir -m775 -p /opt/usr/data/email/.email_data
+chgrp 6006 /opt/usr/data/email/.email_data
 
+mkdir -m775 -p /opt/usr/data/email/.email_data/tmp
+chgrp 6006 /opt/usr/data/email/.email_data/tmp
 
-#################################################################
-# Change file owner
-#################################################################
-#echo "[EMAIL-SERVICE] Start setting owner ..."
-
-        # 1. libraries
-#       chown root:root /usr/lib/libemail-ipc.so.0.0.0
-#       chown root:root /usr/lib/libemail-core.so.0.0.0
-#       chown root:root /usr/lib/libemail-emn-storage.so.0.0.0
-#       chown root:root /usr/lib/libemail-base.so.0.0.0
-#       chown root:root /usr/lib/libem-storage.so.0.0.0
-#       chown root:root /usr/lib/libem-network.so.0.0.0
-#       chown root:root /usr/lib/libemail-mapi.so.0.0.0
-#       chown root:root /usr/lib/libem-storage.so
-#       chown root:root /usr/lib/libemail-base.so.0
-#       chown root:root /usr/lib/libem-network.so.0
-#       chown root:root /usr/lib/libemail-core.so.0
-#       chown root:root /usr/lib/libemail-emn-storage.so
-#       chown root:root /usr/lib/libemail-ipc.so
-#       chown root:root /usr/lib/libemail-mapi.so.0
-#       chown root:root /usr/lib/libem-storage.so.0
-#       chown root:root /usr/lib/libem-network.so
-#       chown root:root /usr/lib/libemail-ipc.so.0
-#       chown root:root /usr/lib/libemail-core.so
-#       chown root:root /usr/lib/libemail-base.so
-#       chown root:root /usr/lib/libemail-mapi.so
-#       chown root:root /usr/lib/libemail-emn-storage.so.0
-
-        # 2. executables
-#       chown root:root /usr/bin/email-service_initDB
-#       chown root:root /usr/bin/email-service
-
-        # 3. DB files
-chown root:root /opt/dbspace/.email-service.db
-chown root:root /opt/dbspace/.email-service.db-journal
-
-%postun -p /sbin/ldconfig
+mkdir -p /opt/share/cert-svc/certs/trusteduser/email
+chgrp 6006 /opt/share/cert-svc/certs/trusteduser/email
 
+if [ -f /opt/usr/dbspace/.email-service.db ]
+then
+       chsmack -a 'email-service::db' /opt/usr/dbspace/.email-service.db*
+fi
+
+systemctl daemon-reload
+if [ $1 == 1 ]; then
+    systemctl restart email.service
+fi
+
+%preun
+if [ $1 == 0]; then
+    systemctl stop email.service
+fi
+
+%postun
+/sbin/ldconfig
+systemctl daemon-reload
 
 
 %files
-%defattr(-,root,root,-)
-%exclude /opt/dbspace/.email-service.db
-%exclude /opt/dbspace/.email-service.db-journal
-%exclude %{_bindir}/email-test-app
-%{_libdir}/libemail-api.so.*
-%{_libdir}/libemail-base.so.*
-%{_libdir}/libemail-core.so.*
-%{_libdir}/libemail-ipc.so.*
-%{_libdir}/libemail-network.so.*
-%{_libdir}/libemail-storage.so.*
+%manifest email-service.manifest
+%exclude /usr/bin/email-test-app
 %{_bindir}/email-service
-
+/opt/usr/data/email/res/*
+%{_libdir}/lib*.so.*
+%{_libdir}/systemd/user/email.service
+%{_libdir}/systemd/user/tizen-middleware.target.wants/email.service
+/usr/share/dbus-1/services/email-service.service
+/usr/share/license/email-service/LICENSE
 
 %files devel
-%defattr(-,root,root,-)
 %{_includedir}/email-service/*.h
-%{_libdir}/libemail-api.so
-%{_libdir}/libemail-base.so
-%{_libdir}/libemail-core.so
-%{_libdir}/libemail-ipc.so
-%{_libdir}/libemail-network.so
-%{_libdir}/libemail-storage.so
+%{_libdir}/lib*.so
 %{_libdir}/pkgconfig/*.pc
-
diff --git a/packaging/email.service b/packaging/email.service
new file mode 100644 (file)
index 0000000..8d0cf15
--- /dev/null
@@ -0,0 +1,12 @@
+
+[Unit]
+Description=Start the Email service
+
+[Service]
+ExecStart=/usr/bin/email-service
+Nice=5
+OOMScoreAdjust=100
+
+[Install]
+WantedBy=tizen-middleware.target
+
diff --git a/res/Q02_Notification_email.png b/res/Q02_Notification_email.png
new file mode 100755 (executable)
index 0000000..f2c4701
Binary files /dev/null and b/res/Q02_Notification_email.png differ
index dca696f..fc4e1a5 100755 (executable)
@@ -20,27 +20,27 @@ SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${VISIBILITY} -fvisibility=hidden")
 
 
 SET(TEST-APP-SRCS
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/emf-test-main.c
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/emf-test-utility.c
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/emf-test-message.c
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/emf-test-mailbox.c
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/emf-test-account.c
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/emf-test-rule.c
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/emf-test-thread.c
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/emf-test-others.c
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/main.c
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/testapp-utility.c
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/testapp-mail.c
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/testapp-mailbox.c
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/testapp-account.c
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/testapp-rule.c
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/testapp-thread.c
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/testapp-others.c
 )
 
 INCLUDE_DIRECTORIES(
-       ${CMAKE_SOURCE_DIR}/utilities/email-service-test-application/email-service-test-application/include
-       ${CMAKE_SOURCE_DIR}/MAPI/include
-       ${CMAKE_SOURCE_DIR}/include
-       ${CMAKE_SOURCE_DIR}/email-core/em-storage/include
+       ${CMAKE_SOURCE_DIR}/utilities/test-application/include
+       ${CMAKE_SOURCE_DIR}/email-api/include
+       ${CMAKE_SOURCE_DIR}/email-common-use/include
        ${CMAKE_SOURCE_DIR}/email-core/include
-       ${CMAKE_SOURCE_DIR}/ipc/include
+       ${CMAKE_SOURCE_DIR}/email-core/email-storage/include
+       ${CMAKE_SOURCE_DIR}/email-ipc/include
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(test_app_pkgs REQUIRED glib-2.0 gthread-2.0 vconf db-util uw-imap-toolkit contacts-service)
+pkg_check_modules(test_app_pkgs REQUIRED glib-2.0 gthread-2.0 vconf db-util uw-imap-toolkit contacts-service2 drm-client)
 
 FOREACH(flag ${test_app_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
diff --git a/utilities/test-application/include/testapp-account.h b/utilities/test-application/include/testapp-account.h
new file mode 100755 (executable)
index 0000000..1c19e78
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 EMAIL_TEST_ACCOUNT_H
+#define EMAIL_TEST_ACCOUNT_H
+
+/* export API */
+void testapp_account_main();
+
+#endif
diff --git a/utilities/test-application/include/testapp-mail.h b/utilities/test-application/include/testapp-mail.h
new file mode 100755 (executable)
index 0000000..3bd21fd
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 EMAIL_TEST_MESSAGE_H
+#define EMAIL_TEST_MESSAGE_H
+
+#include <glib.h>
+
+
+/* export API */
+void           testapp_mail_main               (void);
+
+#endif /* EMAIL_TEST_MESSAGE_H */
+
diff --git a/utilities/test-application/include/testapp-mailbox.h b/utilities/test-application/include/testapp-mailbox.h
new file mode 100755 (executable)
index 0000000..e3aae25
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 EMAIL_TEST_MAILBOX_H
+#define EMAIL_TEST_MAILBOX_H
+
+/* export API */
+void email_test_mailbox_main   (void);
+#endif
diff --git a/utilities/test-application/include/testapp-others.h b/utilities/test-application/include/testapp-others.h
new file mode 100755 (executable)
index 0000000..9e4ce9e
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 EMAIL_TEST_OTHERS_H
+#define EMAIL_TEST_OTHERS_H
+
+/* export API */
+void testapp_others_main(void);
+
+#endif
+
diff --git a/utilities/test-application/include/testapp-rule.h b/utilities/test-application/include/testapp-rule.h
new file mode 100755 (executable)
index 0000000..9fb79b7
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 EMAIL_TEST_RULE_H
+#define EMAIL_TEST_RULE_H
+
+/* export API */
+void           email_test_rule_main                                    (void);
+
+#endif
+
diff --git a/utilities/test-application/include/testapp-thread.h b/utilities/test-application/include/testapp-thread.h
new file mode 100755 (executable)
index 0000000..4e8a8ec
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 EMAIL_TEST_THREAD_H
+#define EMAIL_TEST_THREAD_H
+
+#include <glib.h>
+
+
+/* export API */
+void testapp_thread_main();
+
+#endif /* EMAIL_TEST_THREAD_H */
\ No newline at end of file
diff --git a/utilities/test-application/include/testapp-utility.h b/utilities/test-application/include/testapp-utility.h
new file mode 100755 (executable)
index 0000000..45f14e2
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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 EMAIL_TEST_UTILITY_H
+#define EMAIL_TEST_UTILITY_H
+
+#include <glib.h>
+
+typedef enum
+{
+       EMAIL_MAIN_MENU = 0x0,
+       EMAIL_ACCOUNT_MENU,
+       EMAIL_MAIL_MENU,
+       EMAIL_MAILBOX_MENU,
+       EMAIL_RULE_MENU,
+       EMAIL_THREAD_MENU,
+       EMAIL_OTHERS_MENU,
+} eEMAIL_MENU;
+
+
+void testapp_print(char *fmt, ...);
+void testapp_show_menu(eEMAIL_MENU menu);
+void testapp_show_prompt(eEMAIL_MENU menu);
+
+#endif
+
diff --git a/utilities/test-application/main.c b/utilities/test-application/main.c
new file mode 100755 (executable)
index 0000000..7cdec48
--- /dev/null
@@ -0,0 +1,200 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/* common header */
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+/* open header */
+#include <glib.h>
+
+#include "email-api-init.h"
+
+/* internal header */
+#include "testapp-utility.h"
+#include "testapp-account.h"
+#include "testapp-mail.h"
+#include "testapp-mailbox.h"
+#include "testapp-rule.h"
+#include "testapp-thread.h"
+#include "testapp-others.h"
+#include "db-util.h"
+
+/* function prototype */
+static void testapp_system_signal_handler (int signal_number);
+
+
+/* implementation */
+static gboolean testapp_initialize_testing ()
+{
+       struct timeval tv_1, tv_2;
+       int interval;
+       int error;
+       
+       /* register signal handler */
+       if ( signal (SIGINT, testapp_system_signal_handler) == SIG_ERR ) {
+               testapp_print ("register signal handler fail\n");
+               return FALSE;
+       }
+
+       if ( signal (SIGQUIT, testapp_system_signal_handler) == SIG_ERR ) {
+               testapp_print ("register signal handler fail\n");
+               return FALSE;
+       }
+
+       if ( signal (SIGTSTP, testapp_system_signal_handler) == SIG_ERR ) {
+               testapp_print ("register signal handler fail\n");
+               return FALSE;
+       }
+
+       if ( signal (SIGTERM, testapp_system_signal_handler) == SIG_ERR ) {
+               testapp_print ("register signal handler fail\n");
+               return FALSE;
+       }
+
+       
+       gettimeofday(&tv_1, NULL);
+       
+       if ( email_service_begin() != EMAIL_ERROR_NONE ) {
+               testapp_print ("unexpected error: opening email service fail\n");
+               return FALSE;
+       }
+       gettimeofday(&tv_2, NULL);
+       interval = tv_2.tv_usec - tv_1.tv_usec;
+       testapp_print("\t email_service_begin Proceed time %d us\n",interval);
+
+       gettimeofday(&tv_1, NULL);
+       if ( (error = email_open_db()) != EMAIL_ERROR_NONE) {
+               testapp_print("email_open_db failed [%d]\n", error);
+       }
+       gettimeofday(&tv_2, NULL);
+       interval = tv_2.tv_usec - tv_1.tv_usec;
+       testapp_print("\t email_open_db Proceed time %d us\n",interval);
+
+       return TRUE;
+}
+
+static gboolean testapp_finalize_testing ()
+{
+       int error;
+
+       if ( (error = email_close_db()) != EMAIL_ERROR_NONE) {
+               testapp_print("email_close_db failed [%d]\n", error);
+       }       
+
+       if ( email_service_end() != EMAIL_ERROR_NONE) {
+               testapp_print ("unexpected error: closing email service fail \n");
+       }
+
+       return TRUE;
+}
+
+static void testapp_system_signal_handler (int signal_number)
+{
+       testapp_print ("signal:%d\n", signal_number);
+       switch (signal_number) {
+               case SIGQUIT:
+               case SIGINT:
+               case SIGTSTP:
+               case SIGTERM:
+                       testapp_finalize_testing();
+                       break;
+
+               default:
+                       testapp_print ("unhandled signal:%d\n", signal_number);
+                       break;
+       }
+       exit(0);
+}
+
+
+static gboolean testapp_interpret_command (int menu_number)
+{
+       gboolean go_to_loop = TRUE;
+
+       switch (menu_number) {
+               case 1:
+                       testapp_account_main();
+                       break;
+                       
+               case 2:
+                       testapp_mail_main();
+                       break;
+                       
+               case 3:
+                       email_test_mailbox_main();
+                       break;
+                       
+               case 4:
+                       break;
+                       
+               case 5:
+                       email_test_rule_main();
+                       break;
+                       
+               case 6:
+                       testapp_thread_main();
+                       break;
+                       
+               case 7:
+                       testapp_others_main();
+                       break;
+               case 0:
+                       go_to_loop = FALSE;
+                       break;
+               default:
+                       break;
+       }
+
+       return go_to_loop;
+}
+
+int main (int argc, char *argv[])
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+       int result_from_scanf = 0;
+
+       if ( testapp_initialize_testing() == FALSE ) {
+               testapp_print ("email-serivce is not ready\n");
+               exit(0);
+       }
+
+       while (go_to_loop) {
+               testapp_show_menu (EMAIL_MAIN_MENU);
+               testapp_show_prompt (EMAIL_MAIN_MENU);
+
+               result_from_scanf = scanf ("%d", &menu_number);
+
+               go_to_loop = testapp_interpret_command (menu_number);
+       }
+
+       testapp_finalize_testing();
+
+       exit(0);
+}
+
+
diff --git a/utilities/test-application/testapp-account.c b/utilities/test-application/testapp-account.c
new file mode 100755 (executable)
index 0000000..b6e2fee
--- /dev/null
@@ -0,0 +1,897 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+/* common header */
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+/* open header */
+#include <glib.h>
+
+#include "email-api.h"
+#include "email-api-account.h"
+#include "email-api-network.h"
+
+/* internal header */
+#include "testapp-utility.h"
+#include "testapp-account.h"
+#include <sys/time.h>
+#include <sys/times.h>
+
+/* internal defines */
+
+#define GWB_RECV_SERVER_ADDR       "pop.gawab.com"
+#define GWB_SMTP_SERVER_ADDR       "smtp.gawab.com"
+
+#define VDF_RECV_SERVER_ADDR  "imap.email.vodafone.de"
+#define VDF_SMTP_SERVER_ADDR  "smtp.email.vodafone.de"
+
+/*  SAMSUNG 3G TEST */
+#define S3G_RECV_SERVER_ADDR               "165.213.73.235"
+#define S3G_RECV_SERVER_PORT               EMAIL_POP3_PORT
+#define S3G_RECV_USE_SECURITY              0
+#define S3G_RECV_IMAP_USE_SECURITY     1
+#define S3G_SMTP_SERVER_ADDR               "165.213.73.235"
+#define S3G_SMTP_SERVER_PORT               465
+#define S3G_SMTP_AUTH                                  1
+#define S3G_SMTP_USE_SECURITY        1
+#define S3G_KEEP_ON_SERVER                   1
+
+gboolean testapp_test_create_account_by_account_type(int account_type,int *account_id) 
+{
+       email_account_t *account = NULL;
+       char id_string[100] = { 0, }, password_string[100] = { 0, }, address_string[100]  = { 0, };
+       int err_code = EMAIL_ERROR_NONE, samsung3g_account_index;
+       int result_from_scanf = 0;
+       int handle;
+
+       switch(account_type) {
+               case 4 : 
+               case 5 :
+                       do {
+                               testapp_print("Enter your account index [1~10] : ");
+                               result_from_scanf = scanf("%d",&samsung3g_account_index);
+                       }while( samsung3g_account_index > 10 || samsung3g_account_index < 1);
+                       sprintf(id_string, "test%02d", samsung3g_account_index);
+                       sprintf(address_string, "<test%02d@streaming.s3glab.net>", samsung3g_account_index);
+                       strcpy(password_string, id_string);
+                       break;
+               default:
+                       testapp_print("Enter email address : ");
+                       result_from_scanf = scanf("%s", address_string);
+
+                       testapp_print("Enter id : ");
+                       result_from_scanf = scanf("%s", id_string);
+
+                       testapp_print("Enter password_string : ");
+                       result_from_scanf = scanf("%s", password_string);
+                       break;
+       }
+
+       account = malloc(sizeof(email_account_t));
+       memset(account, 0x00, sizeof(email_account_t));
+
+       typedef struct {
+               int is_preset_account;
+               int index_color;
+       } user_data_t;
+       user_data_t data = (user_data_t) {1, 0};
+       /* if user_data_t has any pointer member, please don't use sizeof(). */
+       /* You need to serialize user_data to buffer and then take its length */
+       int data_length = sizeof(data);
+
+       /* Common Options */
+       account->retrieval_mode                = EMAIL_IMAP4_RETRIEVAL_MODE_ALL;
+       account->incoming_server_secure_connection      = 1;
+       account->outgoing_server_type          = EMAIL_SERVER_TYPE_SMTP;
+       account->auto_download_size                        = 2;
+       account->outgoing_server_use_same_authenticator = 1;
+       account->pop_before_smtp               = 0;
+       account->incoming_server_requires_apop = 0;
+       account->logo_icon_path                = NULL;
+       account->user_data                     = malloc (data_length);
+       memcpy( account->user_data, (void*) &data, data_length );
+       account->user_data_length              = data_length;
+       account->options.priority              = 3;
+       account->options.keep_local_copy       = 1;
+       account->options.req_delivery_receipt  = 0;
+       account->options.req_read_receipt      = 0;
+       account->options.download_limit        = 0;
+       account->options.block_address         = 0;
+       account->options.block_subject         = 0;
+       account->options.display_name_from     = NULL;
+       account->options.reply_with_body       = 0;
+       account->options.forward_with_files    = 0;
+       account->options.add_myname_card       = 0;
+       account->options.add_signature         = 0;
+       account->options.signature             = NULL;
+       account->options.add_my_address_to_bcc = 0;
+       account->check_interval                = 0;
+       account->keep_mails_on_pop_server_after_download        = 1;
+       account->default_mail_slot_size        = 200;
+
+       account->account_name                  = strdup(address_string);
+       account->user_display_name             = strdup(id_string);
+       account->user_email_address            = strdup(address_string);
+       account->reply_to_address              = strdup(address_string);
+       account->return_address                = strdup(address_string);
+
+       account->incoming_server_user_name     = strdup(id_string);
+       account->incoming_server_password      = strdup(password_string);
+       account->outgoing_server_user_name     = strdup(id_string);
+       account->outgoing_server_password          = strdup(password_string);
+
+       switch (account_type) {
+               case 1:/*  gawab */
+                       account->incoming_server_type            = EMAIL_SERVER_TYPE_POP3 ;
+                       account->incoming_server_address         = strdup(GWB_RECV_SERVER_ADDR);
+                       account->incoming_server_port_number = EMAIL_POP3S_PORT;
+                       account->outgoing_server_address     = strdup(GWB_SMTP_SERVER_ADDR);
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_need_authentication = 1;
+                       account->outgoing_server_port_number = EMAIL_SMTPS_PORT;
+                       account->outgoing_server_secure_connection       = 1;
+
+                       break;
+
+               case 2:/*  vadofone */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
+                       account->incoming_server_address= strdup(VDF_RECV_SERVER_ADDR);
+                       account->incoming_server_port_number = EMAIL_IMAP_PORT;
+                       account->outgoing_server_address     = strdup(VDF_SMTP_SERVER_ADDR);
+                       account->incoming_server_secure_connection      = 0;
+                       account->outgoing_server_need_authentication = 0;
+                       break;
+
+               case 4:/*  SAMSUNG 3G TEST */
+                       account->incoming_server_type            = EMAIL_SERVER_TYPE_POP3;
+                       account->incoming_server_address         = strdup(S3G_RECV_SERVER_ADDR);
+                       account->incoming_server_port_number = S3G_RECV_SERVER_PORT;
+                       account->outgoing_server_address     = strdup(S3G_SMTP_SERVER_ADDR);
+                       account->outgoing_server_port_number = S3G_SMTP_SERVER_PORT;
+                       account->incoming_server_secure_connection      = S3G_RECV_USE_SECURITY;
+                       account->outgoing_server_secure_connection  = S3G_SMTP_USE_SECURITY;
+                       account->outgoing_server_need_authentication = S3G_SMTP_AUTH;
+                       break;
+
+               case 5:/*  SAMSUNG 3G TEST */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
+                       account->incoming_server_address= strdup(S3G_RECV_SERVER_ADDR);
+                       account->incoming_server_port_number = EMAIL_IMAPS_PORT;
+                       account->outgoing_server_address     = strdup(S3G_SMTP_SERVER_ADDR);
+                       account->outgoing_server_port_number = S3G_SMTP_SERVER_PORT;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_secure_connection  = S3G_SMTP_USE_SECURITY;
+                       account->outgoing_server_need_authentication = S3G_SMTP_AUTH;
+                       break;
+
+               case 6:/*  Gmail POP3 */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_POP3;
+                       account->incoming_server_address= strdup("pop.gmail.com");
+                       account->incoming_server_port_number = 995;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address    = strdup("smtp.gmail.com");
+                       account->outgoing_server_port_number = 465;
+                       account->outgoing_server_secure_connection = 1;
+                       account->outgoing_server_need_authentication = 1;
+                       break;
+
+               case 7 : /*  Gmail IMAP4 */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
+                       account->incoming_server_address= strdup("imap.gmail.com");
+                       account->incoming_server_port_number = 993;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address    = strdup("smtp.gmail.com");
+                       account->outgoing_server_port_number = 465;
+                       account->outgoing_server_secure_connection = 1;
+                       account->outgoing_server_need_authentication = 1;
+                       break;
+
+               case 8: /*  Active Sync */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_ACTIVE_SYNC;
+                       account->incoming_server_address= strdup("");
+                       account->incoming_server_port_number = 0;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address    = strdup("");
+                       account->outgoing_server_port_number = 0;
+                       account->outgoing_server_secure_connection = 1;
+                       account->outgoing_server_need_authentication = 1;
+                       break;
+
+               case 9: /*  AOL */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
+                       account->incoming_server_address= strdup("imap.aol.com");
+                       account->incoming_server_port_number = 143;
+                       account->incoming_server_secure_connection      = 0;
+                       account->outgoing_server_address    = strdup("smtp.aol.com");
+                       account->outgoing_server_port_number = 587;
+                       account->outgoing_server_secure_connection = 0;
+                       account->outgoing_server_need_authentication = 1;
+                       break;
+
+               case 10: /*  Hotmail */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_POP3;
+                       account->incoming_server_address= strdup("pop3.live.com");
+                       account->incoming_server_port_number = 995;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address    = strdup("smtp.live.com");
+                       account->outgoing_server_port_number = 587;
+                       account->outgoing_server_secure_connection  = 0x02;
+                       account->outgoing_server_need_authentication = 1;
+                       break;
+
+               case 11:/*  Daum IMAP4*/
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
+                       account->incoming_server_address= strdup("imap.daum.net");
+                       account->incoming_server_port_number = 993;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address    = strdup("smtp.daum.net");
+                       account->outgoing_server_port_number = 465;
+            account->outgoing_server_secure_connection = 1;
+                       account->outgoing_server_need_authentication = 1;
+                       break;
+
+               case 12:/*  Daum POP3*/
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_POP3;
+                       account->incoming_server_address= strdup("pop.daum.net");
+                       account->incoming_server_port_number = 995;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address    = strdup("smtp.daum.net");
+                       account->outgoing_server_port_number = 465;
+            account->outgoing_server_secure_connection = 1;
+                       account->outgoing_server_need_authentication = 1;
+                       break;
+
+               case 13: /* Yahoo IMAP ID */
+                       account->incoming_server_type  = EMAIL_SERVER_TYPE_IMAP4;
+                       account->incoming_server_address= strdup("samsung.imap.mail.yahoo.com");
+                       account->incoming_server_port_number = 993;
+                       account->incoming_server_secure_connection      = 1;
+                       account->outgoing_server_address    = strdup("samsung.smtp.mail.yahoo.com");
+                       account->outgoing_server_port_number = 465;
+                       account->outgoing_server_secure_connection = 1;
+                       account->outgoing_server_need_authentication = 1;
+                       break;
+
+               default:
+                       testapp_print("Invalid Account Number\n");
+                       return FALSE;
+                       break;
+       }
+       account->account_svc_id = 77;
+       err_code = email_add_account_with_validation(account, &handle);
+       if( err_code < 0) {
+               testapp_print ("   email_add_account_with_validation error : %d\n",err_code);
+               err_code = email_free_account(&account, 1);
+               return FALSE;
+       }
+
+       testapp_print ("   email_add_account succeed\n");
+
+       if(account_id)
+               *account_id = account->account_id;
+
+       err_code = email_free_account(&account, 1);
+       return TRUE;
+
+}
+
+static gboolean testapp_test_create_account() 
+{
+       int account_type = 0 ;
+       int err = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+       
+       testapp_print("1. Gawab\n");
+       testapp_print("2. Vodafone\n");
+       testapp_print("4. SAMSUNG 3G TEST (POP)\n");
+       testapp_print("5. SAMSUNG 3G TEST (IMAP)\n");
+       testapp_print("6. Gmail (POP3)\n");
+       testapp_print("7. Gmail (IMAP4)\n");
+       testapp_print("8. Active Sync (dummy)\n");
+       testapp_print("9. AOL\n");
+       testapp_print("10. Hotmail\n");
+       testapp_print("11. Daum (IMAP4)\n");
+       testapp_print("12. Daum (POP3)\n");
+       testapp_print("13. Yahoo (IMAP ID)\n");
+       testapp_print("Choose server type: ");
+       
+       result_from_scanf = scanf("%d",&account_type);
+
+       if(!testapp_test_create_account_by_account_type(account_type,&err)) {
+               testapp_print ("   testapp_test_create_account_by_account_type error\n");
+               return FALSE;
+       }
+       return FALSE;
+}
+
+static gboolean testapp_test_update_account()
+{
+       int result_from_scanf = 0;
+       int account_id;
+       email_account_t *account = NULL;
+       char account_name[256];
+       int err = EMAIL_ERROR_NONE;
+       char signature[100] = {0};
+       char user_email_address[256] = {0,};
+       int add_my_address_to_bcc = 0;
+       int account_svc_id = 0, with_validation = 0;
+
+       
+       testapp_print("\n>> Enter Account No: ");
+       result_from_scanf = scanf("%d",&account_id);
+
+/* sowmya.kr, 281209 Adding signature to options in email_account_t changes */
+       if( (err = email_get_account(account_id, GET_FULL_DATA,&account)) != EMAIL_ERROR_NONE) {
+               testapp_print ("email_get_account failed - %d\n", err);
+               return false;
+       }
+
+       testapp_print ("email_get_account result account_name - %s \n", account->account_name);
+
+       testapp_print ("email_get_account result signature - %s \n", account->options.signature);
+
+#ifdef __FEATURE_AUTO_POLLING__
+       testapp_print ("email_get_account result check_interval - %d \n", account->check_interval);
+#endif
+
+       testapp_print("\n Enter new Account name:");
+       result_from_scanf = scanf("%s",account_name);
+
+       
+       testapp_print("\n Enter new email addr:");
+       result_from_scanf = scanf("%s",user_email_address);
+#ifdef __FEATURE_AUTO_POLLING__
+       testapp_print("\n Enter new check interval (in mins):");
+       result_from_scanf = scanf("%d",&(account->check_interval));
+#endif
+       testapp_print("\n Enter new signature:");
+       result_from_scanf = scanf("%s",signature);
+
+       testapp_print("\n>> Enter add_my_address_to_bcc:(0:off, 1:on) ");
+       result_from_scanf = scanf("%d",&add_my_address_to_bcc);
+
+       testapp_print("\n>> Enter account_svc_id: ");
+       result_from_scanf = scanf("%d",&account_svc_id);
+
+       testapp_print("\n>> With validation ? (0: No, 1:Yes) ");
+       result_from_scanf = scanf("%d",&with_validation);
+
+    if( account )  {
+               account->account_name = strdup(account_name);
+               testapp_print("\n Assigning New Account name: (%s)", account->account_name);
+               account->user_email_address = strdup(user_email_address);
+               account->options.signature = strdup(signature);
+               testapp_print("\n Assigning New Signature: (%s)\n", account->options.signature);
+               account->options.add_my_address_to_bcc = add_my_address_to_bcc;
+               account->account_svc_id = account_svc_id;
+
+               if(with_validation) {
+                       if((err = email_update_account_with_validation(account_id, account)) != EMAIL_ERROR_NONE){
+                               testapp_print ("email_update_account_with_validation failed - %d\n", err);
+                               return false;
+                       }
+                               testapp_print ("email_update_account_with_validation successful \n");
+               }
+               else {
+                       if((err = email_update_account(account_id, account)) != EMAIL_ERROR_NONE) {
+                               testapp_print ("email_update_account failed - %d\n", err);
+                               return false;
+                       }
+                       testapp_print ("email_update_account successful \n");
+               }
+    }
+       return true;
+}
+
+static gboolean testapp_test_delete_account ()
+{
+       int account_id;
+       email_account_t *account=NULL;
+       int err = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+
+       testapp_print("\n>> Enter Account No: ");
+       result_from_scanf = scanf("%d",&account_id);
+
+/* sowmya.kr, 281209 Adding signature to options in email_account_t changes */
+       if( (err = email_get_account(account_id, WITHOUT_OPTION,&account)) < 0) {
+               testapp_print ("email_get_account failed \n");
+               testapp_print("testapp_test_delete_account failed\n");
+       }
+       else {
+               testapp_print ("email_get_account result account_name - %s \n", account->account_name);
+
+               if((err = email_delete_account(account_id)) < 0) 
+                       testapp_print ("email_delete_account failed[%d]\n", err);
+               else
+                       testapp_print ("email_delete_account successful \n");
+       }
+       return FALSE;
+
+}
+
+
+static gboolean testapp_test_validate_account ()
+{
+       int result_from_scanf = 0;
+       int account_id;
+       email_account_t *account=NULL;
+       int err_code = EMAIL_ERROR_NONE;
+       int handle = 0;
+       
+       testapp_print("\n>> Enter Account No: ");
+       result_from_scanf = scanf("%d",&account_id);
+
+/* sowmya.kr, 281209 Adding signature to options in email_account_t changes */
+       if( (err_code = email_get_account(account_id, WITHOUT_OPTION,&account)) < 0 ) {
+               testapp_print ("email_get_account failed \n");
+               return FALSE;
+       }
+       else
+               testapp_print ("email_get_account result account_name - %s \n", account->account_name);
+
+       if((err_code = email_validate_account(account_id, &handle)) == EMAIL_ERROR_NONE )
+               testapp_print ("email_validate_account successful  handle : %u\n",handle);
+       else
+               testapp_print ("email_validate_account failed err_code: %d \n",err_code);
+               
+       return FALSE;
+
+}
+
+
+static gboolean testapp_test_cancel_validate_account ()
+{
+       int result_from_scanf = 0;
+       int account_id = 0;
+       int err_code = EMAIL_ERROR_NONE;
+       unsigned account_handle = 0;
+
+       testapp_print("\n > Enter account_id: ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n > Enter handle: ");
+       result_from_scanf = scanf("%d", &account_handle);
+
+       err_code = email_cancel_job(account_id, account_handle, EMAIL_CANCELED_BY_USER);
+       if(err_code == 0)
+               testapp_print("email_cancel_job Success..!handle:[%d]", account_handle);
+       else
+               testapp_print ("email_cancel_job failed err_code: %d \n",err_code);
+       
+       return FALSE;
+}
+
+static gboolean testapp_test_get_account()
+{
+       int result_from_scanf = 0;
+       int account_id;
+       email_account_t *account=NULL;
+       int err_code = EMAIL_ERROR_NONE;
+       testapp_print("\n>> Enter Account No: ");
+       result_from_scanf = scanf("%d",&account_id);
+
+       typedef struct {
+               int is_preset_account;
+               int index_color;
+       } user_data_t;
+
+       testapp_print ("\n----------------------------------------------------------\n");
+       testapp_print ("email_get_account GET_FULL_DATA \n");
+       if( (err_code = email_get_account(account_id,GET_FULL_DATA,&account)) < 0) {
+               testapp_print ("email_get_account failed - %d\n", err_code);
+               return FALSE;
+       }
+
+       user_data_t* val = (user_data_t*) account->user_data;
+       int is_preset_account =  val? val->is_preset_account : 0;
+       int index_color = val? val->index_color : 0;
+
+       testapp_print ("email_get_account result\n"
+                       "account_name - %s \n"
+                       "user_email_address - %s \n"
+                       "incoming_server_secure_connection %d \n"
+                       "add_sig : %d \n"
+                       "signature %s \n"
+                       "add_my_address_to_bcc %d \n"
+                       "account_svc_id %d\n"
+                       "incoming_server_address %s\n"
+                       "outgoing_server_address %s\n"
+                       "default_mail_slot_size %d\n"
+                       "sync_status %d\n"
+                       "sync_disabled %d\n"
+                       "is_preset %d\n"
+                       "index_color %d\n"
+                       "certificate_path %s\n"
+                       "digest_type %d\n"
+               ,
+               account->account_name,
+               account->user_email_address,
+               account->incoming_server_secure_connection,
+               account->options.add_signature,
+               account->options.signature,
+               account->options.add_my_address_to_bcc,
+               account->account_svc_id,
+               account->incoming_server_address,
+               account->outgoing_server_address,
+               account->default_mail_slot_size,
+               account->sync_status,
+               account->sync_disabled,
+               is_preset_account,
+               index_color,
+               account->certificate_path,
+               account->digest_type
+               );
+
+       err_code = email_free_account(&account, 1);
+
+       testapp_print ("\n----------------------------------------------------------\n");
+       testapp_print ("email_get_account WITHOUT_OPTION \n");
+
+       if( (err_code = email_get_account(account_id, WITHOUT_OPTION, &account)) < 0) {
+               testapp_print ("email_get_account failed \n");
+               return FALSE;
+       }
+
+       testapp_print ("email_get_account result\n"
+                       "account_name - %s \n"
+                       "user_email_address - %s \n"
+                       "incoming_server_secure_connection %d \n"
+                       "add_signature : %d \n",
+               account->account_name,
+               account->user_email_address,
+               account->incoming_server_secure_connection,
+               account->options.add_signature
+       );
+
+       if(account->options.signature)
+               testapp_print ("signature : %s\n", account->options.signature);
+       else
+               testapp_print ("signature not retrieved \n");
+
+       err_code = email_free_account(&account, 1);
+
+       testapp_print ("\n----------------------------------------------------------\n");
+       testapp_print ("email_get_account ONLY_OPTION \n");
+
+       if( (err_code = email_get_account(account_id, ONLY_OPTION, &account)) < 0) {
+               testapp_print ("email_get_account failed \n");
+               return FALSE;
+       }
+
+       testapp_print ("email_get_account result\n"
+                       "add_sig : %d \n"
+                       "signature %s \n"
+                       "add_my_address_to_bcc %d\n"
+                       "account_svc_id %d\n",
+               account->options.add_signature,
+               account->options.signature,
+               account->options.add_my_address_to_bcc,
+               account->account_svc_id
+               );
+
+       if(account->account_name)
+               testapp_print ("account_name : %s \n", account->account_name);
+       else
+               testapp_print ("account_name not retrieved \n");        
+
+       if(account->user_email_address)
+               testapp_print ("user_email_address : %s \n", account->user_email_address);
+       else
+               testapp_print ("user_email_address not retrieved \n");  
+       err_code = email_free_account(&account, 1);
+               
+       return FALSE;
+}
+
+static gboolean testapp_test_get_account_list ()
+{
+
+       int count, i;
+       email_account_t *account_list=NULL;
+       struct timeval tv_1, tv_2;
+       int interval;
+       int err_code = EMAIL_ERROR_NONE;
+
+       gettimeofday(&tv_1, NULL);
+
+       if((err_code = email_get_account_list(&account_list, &count)) < 0 ) {
+               testapp_print("   email_get_account_list error\n");
+               return false ;
+       }
+
+       gettimeofday(&tv_2, NULL);
+       interval = tv_2.tv_usec - tv_1.tv_usec;
+       testapp_print("\t testapp_test_get_account_list Proceed time %d us\n",interval);
+       
+       for(i=0;i<count;i++){
+               testapp_print("   %2d) %-15s %-30s\n",account_list[i].account_id, 
+                       account_list[i].account_name, 
+                       account_list[i].user_email_address);
+       }
+
+       err_code = email_free_account(&account_list, count);
+       return FALSE;
+}
+
+static gboolean testapp_test_backup_account()
+{
+       char *file_name = "accounts_file";
+       int error_code;
+       error_code = email_backup_accounts_into_secure_storage(file_name);
+       testapp_print("\n email_backup_accounts_into_secure_storage returned [%d]\n",error_code);
+       return FALSE;
+}
+static gboolean testapp_test_restore_account()
+{
+       char *file_name = "accounts_file";
+       int error_code;
+       error_code = email_restore_accounts_from_secure_storage(file_name);
+       testapp_print("\n email_restore_accounts_from_secure_storage returned [%d]\n",error_code);
+       return FALSE;
+}
+
+static gboolean testapp_test_get_password_length_of_account()
+{
+       int result_from_scanf = 0;
+       int error_code, password_length, account_id;
+
+       testapp_print("\n input account id\n");
+       result_from_scanf = scanf("%d", &account_id);
+       error_code = email_get_password_length_of_account(account_id, &password_length);
+       testapp_print("testapp_test_get_password_length_of_account returned [%d]\n",password_length);
+       return FALSE;
+}
+
+static gboolean testapp_test_query_server_info()
+{
+       int result_from_scanf = 0;
+       int error_code;
+       char domain_name[255];
+       email_server_info_t *result_server_info;
+
+       testapp_print("\n input domain name\n");
+       result_from_scanf = scanf("%s", domain_name);
+
+       error_code = email_query_server_info(domain_name, &result_server_info);
+       testapp_print("email_query_server_info returned [%d]\n",error_code);
+       if(error_code == EMAIL_ERROR_NONE)
+               testapp_print("service_name [%s]\n", result_server_info->service_name);
+       return FALSE;
+}
+
+static gboolean testapp_test_clear_all_notification()
+{
+       int error_code;
+
+       error_code = email_clear_all_notification_bar();
+       testapp_print("email_clear_all_notification_bar returned [%d]\n",error_code);
+       return FALSE;
+}
+
+static gboolean testapp_test_save_default_account_id()
+{
+       int result_from_scanf = 0;
+       int error_code;
+       int account_id = 0;
+
+       testapp_print ("\nInput default account id : ");
+
+       result_from_scanf = scanf("%d", &account_id);
+
+       error_code = email_save_default_account_id(account_id);
+
+       testapp_print("email_save_default_account_id returned [%d]\n",error_code);
+       return FALSE;
+}
+
+static gboolean testapp_test_load_default_account_id()
+{
+       int error_code;
+       int account_id = 0;
+
+       error_code = email_load_default_account_id(&account_id);
+
+       testapp_print ("\ndefault account id : %d\n", account_id);
+       testapp_print("email_load_default_account_id returned [%d]\n",error_code);
+       return FALSE;
+}
+
+static gboolean testapp_test_add_certificate()
+{
+       int result_from_scanf = 0;
+       int ret = 0;
+       char save_name[50] = {0, };
+       char certificate_path[255] = {0, };
+
+       testapp_print("Input cert path : ");
+       result_from_scanf = scanf("%s", certificate_path);      
+
+       testapp_print("Input cert email-address : ");
+       result_from_scanf = scanf("%s", save_name);
+
+       testapp_print("cert path : [%s]", certificate_path);
+       testapp_print("email-address : [%s]", save_name);
+
+       ret = email_add_certificate(certificate_path, save_name);
+       if (ret != EMAIL_ERROR_NONE) {
+               testapp_print("Add certificate failed\n");
+               return false;
+       }
+
+       testapp_print("Add certificate success\n");
+       return true;
+}
+
+static gboolean testapp_test_get_certificate()
+{
+       int result_from_scanf = 0;
+       int ret = 0;
+       char save_name[20] = {0, };
+       email_certificate_t *certificate = NULL;
+
+       testapp_print("Input cert email-address : ");
+       result_from_scanf = scanf("%s", save_name);
+
+       ret = email_get_certificate(save_name, &certificate);
+       if (ret != EMAIL_ERROR_NONE) {
+               testapp_print("Get certificate failed\n");
+               return false;
+       }
+
+       testapp_print("certificate_id : %d\n", certificate->certificate_id);
+       testapp_print("issue_year : %d\n", certificate->issue_year);
+       testapp_print("issue_month : %d\n", certificate->issue_month);
+       testapp_print("issue_day : %d\n", certificate->issue_day);
+       testapp_print("expiration_year : %d\n", certificate->expiration_year);
+       testapp_print("expiration_month : %d\n", certificate->expiration_month);
+       testapp_print("expiration_day : %d\n", certificate->expiration_day);
+       testapp_print("issue_organization_name : %s\n", certificate->issue_organization_name);
+       testapp_print("subject_string : %s\n", certificate->subject_str);
+       testapp_print("file path : %s\n", certificate->filepath);
+
+       if (certificate)
+               email_free_certificate(&certificate, 1);
+
+       testapp_print("Get certificate success\n");
+       return true;
+}
+
+static gboolean testapp_test_delete_certificate()
+{
+       int result_from_scanf = 0;
+       int ret = 0;
+       char save_name[20] = {0, };
+
+       testapp_print("Input cert email-address : ");
+       result_from_scanf = scanf("%s", save_name);
+
+       ret = email_delete_certificate(save_name);
+       if (ret != EMAIL_ERROR_NONE) {
+               testapp_print("Delete certificate failed\n");
+               return false;
+       }
+
+       testapp_print("Delete certificate success\n");
+       return true;
+}
+static gboolean testapp_test_interpret_command (int selected_number)
+{
+       gboolean go_to_loop = TRUE;
+       
+       switch (selected_number) {
+               case 1:
+                       testapp_test_create_account();
+                       break;
+
+               case 2:
+                       testapp_test_update_account();
+                       break;
+
+               case 3:
+                       testapp_test_delete_account();
+                       break;
+
+               case 4:
+                       testapp_test_get_account();
+                       break;
+               
+               case 5:
+                       testapp_test_get_account_list();
+                       break;
+
+               case 7:
+                       testapp_test_validate_account();
+                       break;          
+
+               case 8:
+                       testapp_test_cancel_validate_account();
+                       break;  
+
+               case 9:
+                       testapp_test_backup_account();
+                       break;  
+
+               case 10:
+                       testapp_test_restore_account();
+                       break;  
+
+               case 11:
+                       testapp_test_get_password_length_of_account();
+                       break;
+
+               case 12:
+                       testapp_test_query_server_info();
+                       break;
+
+               case 13:
+                       testapp_test_clear_all_notification();
+                       break;
+
+               case 14:
+                       testapp_test_save_default_account_id();
+                       break;
+
+               case 15:
+                       testapp_test_load_default_account_id();
+                       break;
+
+               case 16:
+                       testapp_test_add_certificate();
+                       break;
+
+               case 17:
+                       testapp_test_get_certificate();
+                       break;
+
+               case 18:
+                       testapp_test_delete_certificate();
+                       break;
+
+               case 0:
+                       go_to_loop = FALSE;
+                       break;
+
+               default:
+                       break;
+       }
+
+       return go_to_loop;
+}
+
+void testapp_account_main ()
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+       int result_from_scanf = 0;
+       
+       while (go_to_loop) {
+               testapp_show_menu (EMAIL_ACCOUNT_MENU);
+               testapp_show_prompt (EMAIL_ACCOUNT_MENU);
+                       
+               result_from_scanf = scanf ("%d", &menu_number);
+
+               go_to_loop = testapp_test_interpret_command (menu_number);
+       }       
+}
+
diff --git a/utilities/test-application/testapp-mail.c b/utilities/test-application/testapp-mail.c
new file mode 100755 (executable)
index 0000000..1ee47ac
--- /dev/null
@@ -0,0 +1,2156 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/* common header */
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <wait.h>
+
+/* open header */
+#include <glib.h>
+#include <time.h>
+
+#include "email-api-account.h"
+#include "email-api-network.h"
+#include "email-api-mail.h"
+#include "email-api-mailbox.h"
+#include "email-api-etc.h"
+#include "email-api-smime.h"
+
+/* internal header */
+#include "testapp-utility.h"
+#include "testapp-mail.h"
+#include "email-core-utils.h"
+#include "email-core-mime.h"
+
+#define MAIL_TEMP_BODY "/tmp/utf8"
+#define HTML_TEMP_BODY "/tmp/utf8.htm"
+
+/*
+static void testapp_test_print_sorting_menu()
+{
+       testapp_print("   EMAIL_SORT_DATETIME_HIGH = 0\n");
+       testapp_print("   EMAIL_SORT_DATETIME_LOW = 1\n");      
+       testapp_print("   EMAIL_SORT_SENDER_HIGH = 2\n");
+       testapp_print("   EMAIL_SORT_SENDER_LOW = 3\n");   
+       testapp_print("   EMAIL_SORT_RCPT_HIGH = 4\n");
+       testapp_print("   EMAIL_SORT_RCPT_LOW = 5\n");    
+       testapp_print("   EMAIL_SORT_SUBJECT_HIGH = 6\n");
+       testapp_print("   EMAIL_SORT_SUBJECT_LOW = 7\n");   
+       testapp_print("   EMAIL_SORT_PRIORITY_HIGH = 8\n");
+       testapp_print("   EMAIL_SORT_PRIORITY_LOW = 9\n");   
+       testapp_print("   EMAIL_SORT_ATTACHMENT_HIGH = 10\n");
+       testapp_print("   EMAIL_SORT_ATTACHMENT_LOW = 11\n");   
+       testapp_print("   EMAIL_SORT_FAVORITE_HIGH = 12\n");
+       testapp_print("   EMAIL_SORT_FAVORITE_LOW = 13\n");   
+}
+
+static void testapp_test_print_mail_list_item(email_mail_list_item_t *mail_list_item, int count)
+{
+       int i;
+       
+       testapp_print("\n>>>>> Print mail list items: count[%d]\n", count);
+       for (i=0; i< count; i++) {
+               testapp_print("\n[%d]\n", i);
+               testapp_print(" >>> Mailbox Name [ %s ] \n", mail_list_item[i].mailbox_name);
+               testapp_print(" >>> Mail ID [ %d ] \n", mail_list_item[i].mail_id);
+               testapp_print(" >>> Account ID [ %d ] \n", mail_list_item[i].account_id);
+               if (  mail_list_item[i].from!= NULL ) {
+                       testapp_print(" >>> From [ %s ] \n", mail_list_item[i].from);
+               }
+               if (  mail_list_item[i].from_email_address != NULL ) {
+                       testapp_print(" >>> from_email_address [ %s ] \n", mail_list_item[i].from_email_address);
+               }
+               if (  mail_list_item[i].recipients!= NULL ) {
+                       testapp_print(" >>> recipients [ %s ] \n", mail_list_item[i].recipients);
+               }
+               if (  mail_list_item[i].subject != NULL ) {
+                       testapp_print(" >>> subject [ %s ] \n", mail_list_item[i].subject);
+               }
+               testapp_print(" >>> text_download_yn [ %d ] \n", mail_list_item[i].body_download_status);
+               testapp_print(" >>> date_time [ %d ] \n", mail_list_item[i].date_time);
+               testapp_print(" >>> flags_seen_field [ %d ] \n", mail_list_item[i].flags_seen_field);
+               testapp_print(" >>> priority [ %d ] \n", mail_list_item[i].priority);
+               testapp_print(" >>> save_status [ %d ] \n", mail_list_item[i].save_status);
+               testapp_print(" >>> lock [ %d ] \n", mail_list_item[i].lock_status);
+               testapp_print(" >>> report_status [ %d ] \n", mail_list_item[i].report_status);
+               testapp_print(" >>> recipients_count [ %d ] \n", mail_list_item[i].recipients_count);
+               testapp_print(" >>> attachment_count [ %d ] \n", mail_list_item[i].attachment_count);
+               testapp_print(" >>> DRM_status [ %d ] \n", mail_list_item[i].DRM_status);
+
+               if (  mail_list_item[i].preview_text != NULL ) {
+                       testapp_print(" >>> preview_text [ %s ] \n", mail_list_item[i].preview_text);
+               }
+
+               testapp_print(" >>> thread_id [ %d ] \n", mail_list_item[i].thread_id);
+               testapp_print(" >>> thread_item_count [ %d ] \n", mail_list_item[i].thread_item_count);
+       }
+}
+*/
+
+static gboolean testapp_add_mail_for_sending (int *result_mail_id)
+{
+       int                    result_from_scanf = 0;
+       int                    i = 0;
+       int                    account_id = 0;
+       int                    err = EMAIL_ERROR_NONE;
+       int                    smime_type = 0;
+       char                   receipient_address[300] = { 0 , };
+       char                   from_address[300] = { 0 , };
+       const char            *body_file_path = MAIL_TEMP_BODY;
+       email_account_t       *account_data = NULL;
+       email_mailbox_t       *mailbox_data = NULL;
+       email_mail_data_t     *test_mail_data = NULL;
+       FILE                  *body_file;
+
+       testapp_print("\n > Enter account id : ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n > Enter receipient address : ");
+       result_from_scanf = scanf("%s", receipient_address);
+
+       email_get_account(account_id, GET_FULL_DATA_WITHOUT_PASSWORD, &account_data);
+
+       email_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &mailbox_data);
+
+       test_mail_data = malloc(sizeof(email_mail_data_t));
+       memset(test_mail_data, 0x00, sizeof(email_mail_data_t));
+
+       SNPRINTF(from_address, 300, "<%s>", account_data->user_email_address);
+
+       test_mail_data->account_id           = account_id;
+       test_mail_data->save_status          = 1;
+       test_mail_data->body_download_status = 1;
+       test_mail_data->flags_seen_field     = 1;
+       test_mail_data->file_path_plain      = strdup(body_file_path);
+       test_mail_data->mailbox_id           = mailbox_data->mailbox_id;
+       test_mail_data->mailbox_type         = mailbox_data->mailbox_type;
+       test_mail_data->full_address_from    = strdup(from_address);
+       test_mail_data->full_address_to      = strdup(receipient_address);
+       test_mail_data->subject              = strdup("Read receipt request from TIZEN");
+       test_mail_data->report_status        = EMAIL_MAIL_REQUEST_DSN | EMAIL_MAIL_REQUEST_MDN;
+
+       body_file = fopen(body_file_path, "w");
+
+       testapp_print("\n body_file [%p]\n", body_file);
+
+       if(body_file == NULL) {
+               testapp_print("\n fopen [%s]failed\n", body_file_path);
+               return FALSE;
+       }
+
+       for(i = 0; i < 100; i++)
+               fprintf(body_file, "Mail sending Test. [%d]\n", i);
+
+       fflush(body_file);
+       fclose(body_file);
+
+       testapp_print(" > Select smime? [0: Normal, 1: sign, 2: Encrpyt, 3: sing + encrypt] : ");
+       result_from_scanf = scanf("%d", &smime_type);
+       test_mail_data->smime_type = smime_type;
+
+       if((err = email_add_mail(test_mail_data, NULL, 0, NULL, 0)) != EMAIL_ERROR_NONE)
+               testapp_print("email_add_mail failed. [%d]\n", err);
+       else
+               testapp_print("email_add_mail success.\n");
+
+       testapp_print("saved mail id = [%d]\n", test_mail_data->mail_id);
+
+       if(result_mail_id)
+               *result_mail_id = test_mail_data->mail_id;
+
+       email_free_mail_data(&test_mail_data, 1);
+       email_free_mailbox(&mailbox_data, 1);
+       email_free_account(&account_data, 1);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_add_mail (int *result_mail_id)
+{
+       int                    result_from_scanf = 0;
+       int                    i = 0;
+       int                    account_id = 0;
+       int                    mailbox_id = 0;
+       int                    from_eas = 0;
+       int                    attachment_count = 0;
+       int                    err = EMAIL_ERROR_NONE;
+       int                    smime_type = 0;
+       char                   arg[50] = { 0 , };
+       const char            *body_file_path = MAIL_TEMP_BODY;
+       email_mailbox_t         *mailbox_data = NULL;
+       email_mail_data_t       *test_mail_data = NULL;
+       email_attachment_data_t *attachment_data = NULL;
+       email_meeting_request_t *meeting_req = NULL;
+       FILE                  *body_file;
+       testapp_print("\n > Enter account id : ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       
+       memset(arg, 0x00, 50);
+       testapp_print("\n > Enter mailbox id : ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       email_get_mailbox_by_mailbox_id(mailbox_id, &mailbox_data);
+
+       test_mail_data = malloc(sizeof(email_mail_data_t));
+       memset(test_mail_data, 0x00, sizeof(email_mail_data_t));
+       
+       testapp_print("\n Sync server? [0/1]> ");
+       result_from_scanf = scanf("%d", &from_eas);
+
+       test_mail_data->account_id           = account_id;
+       test_mail_data->save_status          = 1;
+       test_mail_data->body_download_status = 1;
+       test_mail_data->flags_seen_field     = 1;
+       test_mail_data->file_path_plain      = strdup(body_file_path);
+       test_mail_data->mailbox_id           = mailbox_id;
+       test_mail_data->mailbox_type         = mailbox_data->mailbox_type;
+       test_mail_data->full_address_from    = strdup("<test1@test.com>");
+       test_mail_data->full_address_to      = strdup("<test2@test.com>");
+       test_mail_data->full_address_cc      = strdup("<test3@test.com>");
+       test_mail_data->full_address_bcc     = strdup("<test4@test.com>");
+       test_mail_data->subject              = strdup("Meeting request mail");
+
+       body_file = fopen(body_file_path, "w");
+
+       testapp_print("\n body_file [%p]\n", body_file);
+
+       if(body_file == NULL) {
+               testapp_print("\n fopen [%s]failed\n", body_file_path);
+               return FALSE;
+       }
+/*     
+       for(i = 0; i < 500; i++)
+               fprintf(body_file, "X2 X2 X2 X2 X2 X2 X2");
+*/
+       fprintf(body_file, "Hello world");
+       fflush(body_file);
+       fclose(body_file);
+
+       testapp_print(" > Select smime? [0: Normal, 1: sign, 2: Encrypt, 3: sing + encrypt] : ");
+       result_from_scanf = scanf("%d", &smime_type);
+       test_mail_data->smime_type = smime_type;
+       
+       testapp_print(" > How many file attachment? [>=0] : ");
+       result_from_scanf = scanf("%d",&attachment_count);
+       
+       test_mail_data->attachment_count  = attachment_count;
+       if ( attachment_count > 0 )
+               attachment_data = calloc(attachment_count, sizeof(email_attachment_data_t));
+
+
+       for ( i = 0; i < attachment_count ; i++ ) {
+               memset(arg, 0x00, 50);
+               testapp_print("\n > Enter attachment name : ");
+               result_from_scanf = scanf("%s", arg);
+
+               attachment_data[i].attachment_name  = strdup(arg);
+               
+               memset(arg, 0x00, 50);
+               testapp_print("\n > Enter attachment absolute path : ");
+               result_from_scanf = scanf("%s",arg);
+               
+               attachment_data[i].attachment_path  = strdup(arg);
+               attachment_data[i].save_status      = 1;
+               attachment_data[i].mailbox_id       = test_mail_data->mailbox_id;
+       }
+       
+       testapp_print("\n > Meeting Request? [0: no, 1: yes (request from server), 2: yes (response from local)]");
+       result_from_scanf = scanf("%d", (int*)&(test_mail_data->meeting_request_status));
+       
+       if ( test_mail_data->meeting_request_status == 1 
+               || test_mail_data->meeting_request_status == 2 ) {
+               time_t current_time;
+               /*  dummy data for meeting request */
+               meeting_req = malloc(sizeof(email_meeting_request_t));
+               memset(meeting_req, 0x00, sizeof(email_meeting_request_t));
+               
+               meeting_req->meeting_response     = 1;
+               current_time = time(NULL);
+               gmtime_r(&current_time, &(meeting_req->start_time));
+               gmtime_r(&current_time, &(meeting_req->end_time));
+               meeting_req->location = strdup("Seoul");
+               meeting_req->global_object_id = strdup("abcdef12345");
+
+               meeting_req->time_zone.offset_from_GMT = 9;
+               strcpy(meeting_req->time_zone.standard_name, "STANDARD_NAME");
+               gmtime_r(&current_time, &(meeting_req->time_zone.standard_time_start_date));
+               meeting_req->time_zone.standard_bias = 3;
+               
+               strcpy(meeting_req->time_zone.daylight_name, "DAYLIGHT_NAME");
+               gmtime_r(&current_time, &(meeting_req->time_zone.daylight_time_start_date));
+               meeting_req->time_zone.daylight_bias = 7;
+
+       }
+       
+       if((err = email_add_mail(test_mail_data, attachment_data, attachment_count, meeting_req, from_eas)) != EMAIL_ERROR_NONE)
+               testapp_print("email_add_mail failed. [%d]\n", err);
+       else
+               testapp_print("email_add_mail success.\n");
+
+       testapp_print("saved mail id = [%d]\n", test_mail_data->mail_id);
+
+       if(result_mail_id)
+               *result_mail_id = test_mail_data->mail_id;
+
+       if(attachment_data)
+               email_free_attachment_data(&attachment_data, attachment_count);
+               
+       if(meeting_req)
+               email_free_meeting_request(&meeting_req, 1);
+               
+       email_free_mail_data(&test_mail_data, 1);
+       email_free_mailbox(&mailbox_data, 1);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_update_mail()
+{
+       int                    result_from_scanf = 0;
+       int                    mail_id = 0;
+       int                    err = EMAIL_ERROR_NONE;
+       int                    test_attachment_data_count = 0;
+       int                    ret = 0;
+       char                   arg[50];
+       email_mail_data_t       *test_mail_data = NULL;
+       email_attachment_data_t *test_attachment_data_list = NULL;
+       email_meeting_request_t *meeting_req = NULL;
+       
+       testapp_print("\n > Enter mail id : ");
+       result_from_scanf = scanf("%d", &mail_id);
+
+       email_get_mail_data(mail_id, &test_mail_data);
+
+       if (!test_mail_data) {
+               testapp_print("email_get_mail_data() failed\n");
+               return FALSE;
+       }
+
+       testapp_print("\n > Enter Subject: ");
+       result_from_scanf = scanf("%s", arg);
+
+       test_mail_data->subject= strdup(arg);
+
+       if (test_mail_data->attachment_count > 0) {
+               if ( (err = email_get_attachment_data_list(mail_id, &test_attachment_data_list, &test_attachment_data_count)) != EMAIL_ERROR_NONE ) {
+                       testapp_print("email_get_meeting_request() failed [%d]\n", err);
+                       goto FINISH_OFF;
+               }
+       }       
+
+       if ( test_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_REQUEST 
+               || test_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_RESPONSE 
+               || test_mail_data->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST) {
+               
+               if ( (err = email_get_meeting_request(mail_id, &meeting_req)) != EMAIL_ERROR_NONE ) {
+                       testapp_print("email_get_meeting_request() failed [%d]\n", err);
+                       goto FINISH_OFF;
+               }
+       
+               testapp_print("\n > Enter meeting response: ");
+               result_from_scanf = scanf("%d", (int*)&(meeting_req->meeting_response));
+       }
+       
+       if ( (err = email_update_mail(test_mail_data, test_attachment_data_list, test_attachment_data_count, meeting_req, 0)) != EMAIL_ERROR_NONE) 
+                       testapp_print("email_update_mail failed.[%d]\n", err);
+               else
+                       testapp_print("email_update_mail success\n");
+
+       ret = 1;
+
+FINISH_OFF:
+
+       if(test_mail_data)
+               email_free_mail_data(&test_mail_data, 1);
+               
+       if(test_attachment_data_list) 
+               email_free_attachment_data(&test_attachment_data_list, test_attachment_data_count);
+               
+       if(meeting_req)
+               email_free_meeting_request(&meeting_req, 1);
+
+       if (!ret)
+               return FALSE;
+
+       return TRUE;
+}
+
+static gboolean testapp_test_get_mails()
+{
+       testapp_print("\n >>> testapp_test_get_mails : Entered \n");
+       email_mail_data_t *mails = NULL, **mails_pointer = NULL;
+       int mailbox_id = 0;
+       int count = 0, i = 0;
+       int account_id = 0;
+       int start_index =0;
+       int limit_count = 0;
+       int sorting = 0;
+       int err_code = EMAIL_ERROR_NONE;
+       int to_get_count = 0;
+       int is_for_thread_view = 0;
+       int list_type;
+       int result_from_scanf = 0;
+       struct tm *temp_time_info;
+
+       testapp_print("\n > Enter Account_id (0 = all accounts) : ");
+       result_from_scanf = scanf("%d",&account_id);
+
+       testapp_print("\n > Enter Mailbox id (0 = all mailboxes) :");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print("\n > Enter Sorting : ");
+       result_from_scanf = scanf("%d",&sorting);
+
+       testapp_print("\n > Enter Start index (starting at 0): ");
+       result_from_scanf = scanf("%d",&start_index);
+
+       testapp_print("\n > Enter max_count : ");
+       result_from_scanf = scanf("%d",&limit_count);
+
+       testapp_print("\n > For thread view : ");
+       result_from_scanf = scanf("%d",&is_for_thread_view);
+
+       testapp_print("\n > Mail count only (0:list 1:count): ");
+       result_from_scanf = scanf("%d",&to_get_count);
+
+       if(to_get_count)
+               mails_pointer = NULL;
+       else
+               mails_pointer = &mails;
+
+       if(is_for_thread_view == -2) {
+               list_type = EMAIL_LIST_TYPE_LOCAL;
+       }
+       else if(is_for_thread_view == -1)
+               list_type = EMAIL_LIST_TYPE_THREAD;
+       else
+               list_type = EMAIL_LIST_TYPE_NORMAL;
+
+       /* Get mail list */
+       if(mailbox_id == 0) {
+               testapp_print("Calling email_get_mail_list for all mailbox.\n");
+               err_code = email_get_mails(account_id, 0, list_type, start_index, limit_count, sorting, mails_pointer, &count);
+               if ( err_code < 0)
+                       testapp_print("email_get_mails failed - err[%d]\n", err_code);
+       }
+       else {
+               testapp_print("Calling email_get_mail_list for %d mailbox_id.\n", mailbox_id);
+               err_code = email_get_mails(account_id, mailbox_id, list_type, start_index, limit_count, sorting,  mails_pointer, &count);
+               if ( err_code < 0)
+                       testapp_print("email_get_mails failed - err[%d]\n", err_code);
+       }
+       testapp_print("email_get_mails >>>>>>count - %d\n",count);
+
+       if (mails) {
+               for (i=0; i< count; i++) {
+                       testapp_print("\n[%d]\n", i);
+                       testapp_print(" >>> mailbox_id [ %d ] \n", mails[i].mailbox_id);
+                       testapp_print(" >>> mail_id [ %d ] \n", mails[i].mail_id);
+                       testapp_print(" >>> account_id [ %d ] \n", mails[i].account_id);
+                       if (  mails[i].full_address_from != NULL )
+                               testapp_print(" >>> full_address_from [ %s ] \n", mails[i].full_address_from);
+                       if (  mails[i].full_address_to != NULL )
+                               testapp_print(" >>> recipients [ %s ] \n", mails[i].full_address_to);
+                       if (  mails[i].subject != NULL )
+                               testapp_print(" >>> subject [ %s ] \n", mails[i].subject);
+                       testapp_print(" >>> body_download_status [ %d ] \n", mails[i].body_download_status);
+                       temp_time_info = localtime(&mails[i].date_time);
+                       testapp_print(" >>> date_time [ %d/%d/%d %d:%d:%d] \n",
+                                                                       temp_time_info->tm_year + 1900,
+                                                                       temp_time_info->tm_mon+1,
+                                                                       temp_time_info->tm_mday,
+                                                                       temp_time_info->tm_hour,
+                                                                       temp_time_info->tm_min,
+                                                                       temp_time_info->tm_sec);
+                       testapp_print(" >>> flags_seen_field [ %d ] \n", mails[i].flags_seen_field);
+                       testapp_print(" >>> priority [ %d ] \n", mails[i].priority);
+                       testapp_print(" >>> save_status [ %d ] \n", mails[i].save_status);
+                       testapp_print(" >>> lock_status [ %d ] \n", mails[i].lock_status);
+                       testapp_print(" >>> attachment_count [ %d ] \n", mails[i].attachment_count);
+                       if (  mails[i].preview_text != NULL )
+                               testapp_print(" >>> preview_text [ %s ] \n", mails[i].preview_text);
+               }
+               free(mails);
+       }
+
+       testapp_print(" >>> testapp_test_get_mails : End \n");
+       return 0;
+}
+
+#define TEMP_ARGUMENT_SIZE 4096
+
+static gboolean testapp_test_mail_send (int *result_mail_id)
+{
+       int                    added_mail_id = 0;
+       int                    err = EMAIL_ERROR_NONE;
+       int                    handle = 0;
+       email_mail_data_t     *result_mail_data = NULL;
+
+       testapp_add_mail_for_sending(&added_mail_id);
+       
+       if(added_mail_id) {
+               email_get_mail_data(added_mail_id, &result_mail_data);
+
+               testapp_print("Calling email_send_mail...\n");
+
+               if( email_send_mail(added_mail_id, &handle) < 0) {
+                       testapp_print("Sending failed[%d]\n", err);
+               }
+               else  {
+                       testapp_print("Start sending. handle[%d]\n", handle);
+               }
+
+               email_free_mail_data(&result_mail_data, 1);
+       }
+
+       if(result_mail_id)
+               *result_mail_id = added_mail_id;
+
+       return FALSE;
+}
+
+static gboolean testapp_test_get_mail_list_ex()
+{
+       email_list_filter_t *filter_list = NULL;
+       email_list_sorting_rule_t *sorting_rule_list = NULL;
+       email_mail_list_item_t *result_mail_list = NULL;
+       int filter_rule_count = 0;
+       int sorting_rule_count = 0;
+       int result_mail_count = 0;
+       int err = EMAIL_ERROR_NONE;
+       int i = 0;
+
+       filter_rule_count = 1;
+
+       filter_list = malloc(sizeof(email_list_filter_t) * filter_rule_count);
+       memset(filter_list, 0 , sizeof(email_list_filter_t) * filter_rule_count);
+
+       filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_MAILBOX_TYPE;
+       filter_list[0].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[0].list_filter_item.rule.key_value.integer_type_value  = EMAIL_MAILBOX_TYPE_INBOX;
+
+       /*
+       filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+
+       filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_TO;
+       filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+       filter_list[2].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+       filter_list[2].list_filter_item.rule.case_sensitivity              = false;
+
+       filter_list[3].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[3].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+
+       filter_list[4].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[4].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_CC;
+       filter_list[4].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+       filter_list[4].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+       filter_list[4].list_filter_item.rule.case_sensitivity              = false;
+
+       filter_list[5].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[5].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+
+       filter_list[6].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[6].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_BCC;
+       filter_list[6].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+       filter_list[6].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+       filter_list[6].list_filter_item.rule.case_sensitivity              = false;
+
+       filter_list[7].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[7].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+
+       filter_list[8].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[8].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_FROM;
+       filter_list[8].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+       filter_list[8].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+       filter_list[8].list_filter_item.rule.case_sensitivity              = false;
+       */
+
+       /*
+       filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_ACCOUNT_ID;
+       filter_list[0].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[0].list_filter_item.rule.key_value.integer_type_value  = 1;
+
+       filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_AND;
+
+       filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_MAILBOX_NAME;
+       filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_EQUAL;
+       filter_list[2].list_filter_item.rule.key_value.string_type_value   = strdup("INBOX");
+       filter_list[2].list_filter_item.rule.case_sensitivity              = true;
+       */
+       sorting_rule_count = 1;
+
+       sorting_rule_list = malloc(sizeof(email_list_sorting_rule_t) * sorting_rule_count);
+       memset(sorting_rule_list, 0 , sizeof(email_list_sorting_rule_t) * sorting_rule_count);
+
+       sorting_rule_list[0].target_attribute                              = EMAIL_MAIL_ATTRIBUTE_DATE_TIME;
+       sorting_rule_list[0].sort_order                                    = EMAIL_SORT_ORDER_DESCEND;
+
+       err = email_get_mail_list_ex(filter_list, filter_rule_count, sorting_rule_list, sorting_rule_count, 0, 10, &result_mail_list, &result_mail_count);
+
+       if(err == EMAIL_ERROR_NONE) {
+               testapp_print("email_get_mail_list_ex succeed.\n");
+
+               for(i = 0; i < result_mail_count; i++) {
+                       testapp_print("mail_id [%d], subject [%s], full_address_from [%s]\n", result_mail_list[i].mail_id, result_mail_list[i].subject, result_mail_list[i].full_address_from);
+               }
+       }
+       else {
+               testapp_print("email_get_mail_list_ex failed.\n");
+       }
+
+       email_free_list_filter(&filter_list, 9);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_send_cancel ()
+{
+       int num = 0;
+       int Y = 0;
+       int i = 0;
+       int j = 0;
+       int *mailIdList = NULL;
+       int mail_id = 0;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter total Number of mail  want to send: ");
+       result_from_scanf = scanf("%d", &num);
+       mailIdList = (int *)malloc(sizeof(int)*num);
+       if(!mailIdList)
+               return false ;
+       
+       for(i = 1;i <=num ; i++) {
+               testapp_test_mail_send(&mail_id);
+               
+               testapp_print("mail_id[%d]",mail_id);
+
+               mailIdList[i] = mail_id;
+               testapp_print("mailIdList[%d][%d]",i,mailIdList[i]);
+
+               mail_id = 0;
+               testapp_print("\n > Do you want to cancel the send mail job '1' or '0': ");
+               result_from_scanf = scanf("%d", &Y);
+               if(Y == 1) {
+                       testapp_print("\n >Enter mail-id[1-%d] ",i);
+                               result_from_scanf = scanf("%d", &j);
+                       testapp_print("\n mailIdList[%d] ",mailIdList[j]);      
+                       if(email_cancel_sending_mail( mailIdList[j]) < 0)
+                               testapp_print("email_cancel_sending_mail failed..!");
+                       else
+                               testapp_print("email_cancel_sending_mail success..!");
+               }
+       }
+       return FALSE;
+}
+
+static gboolean testapp_test_delete()
+{
+       int mail_id=0, account_id =0;
+       int mailbox_id = 0;
+       int err = EMAIL_ERROR_NONE;
+       int from_server = 0;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter Account_id: ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n > Enter Mail_id: ");
+       result_from_scanf = scanf("%d", &mail_id);
+       
+       testapp_print("\n > Enter Mailbox id: ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+       
+       testapp_print("\n > Enter from_server: ");
+       result_from_scanf = scanf("%d", &from_server);
+
+       /* delete message */
+       if( (err = email_delete_mail(mailbox_id, &mail_id, 1, from_server)) < 0)
+               testapp_print("\n email_delete_mail failed[%d]\n", err);
+       else
+               testapp_print("\n email_delete_mail success\n");
+
+       return FALSE;
+}
+
+
+
+static gboolean testapp_test_move()
+{
+       int mail_id[3];
+       int i = 0;
+       int mailbox_id = 0;
+       int result_from_scanf = 0;
+       
+       for(i = 0; i< 3; i++) {
+               testapp_print("\n > Enter mail_id: ");
+               result_from_scanf = scanf("%d",&mail_id[i]);
+       }
+       
+       testapp_print("\n > Enter mailbox_id: ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       /* move mail */
+       email_move_mail_to_mailbox(mail_id, 3, mailbox_id);
+       return FALSE;
+}
+
+static gboolean testapp_test_delete_all()
+{
+       int mailbox_id =0;
+       int err = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter mailbox_id: ");
+       result_from_scanf = scanf("%d",&mailbox_id);
+                                               
+       /* delete all message */
+       if ( (err = email_delete_all_mails_in_mailbox(mailbox_id, 0)) < 0)
+               testapp_print("email_delete_all_mails_in_mailbox failed [%d]\n", err);
+       else
+               testapp_print("email_delete_all_mails_in_mailbox Success\n");   
+                                                                                                                       
+       return FALSE;
+}
+
+
+static gboolean testapp_test_add_attachment()
+{      
+       int mail_id = 0;
+       int result_from_scanf = 0;
+       char arg[100];
+       email_attachment_data_t attachment;
+       
+       testapp_print("\n > Enter Mail Id: ");
+       result_from_scanf = scanf("%d", &mail_id);
+
+       memset(&attachment, 0x00, sizeof(email_attachment_data_t));
+       memset(arg, 0x00, 100);
+       testapp_print("\n > Enter attachment name: ");
+       result_from_scanf = scanf("%s",arg);
+       
+       attachment.attachment_name = strdup(arg);
+       
+       memset(arg, 0x00, 100);
+       testapp_print("\n > Enter attachment absolute path: ");
+       result_from_scanf = scanf("%s",arg);
+
+       attachment.save_status = true;
+       attachment.attachment_path = strdup(arg);
+       if(email_add_attachment(mail_id, &attachment) < 0)
+               testapp_print("email_add_attachment failed\n"); 
+       else
+               testapp_print("email_add_attachment success\n");
+
+
+       return FALSE;
+
+}
+
+static gboolean testapp_test_set_deleted_flag()
+{
+       int index = 0;
+       int account_id = 0;
+       int mail_ids[100] = { 0, };
+       int temp_mail_id = 0;
+       int err_code = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+
+       testapp_print("\n >>> Input target account id: ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       do {
+               testapp_print("\n >>> Input target mail id ( Input 0 to terminate ) [MAX = 100]: ");
+               result_from_scanf = scanf("%d", &temp_mail_id);
+               mail_ids[index++] = temp_mail_id;
+       } while (temp_mail_id != 0);
+
+       err_code = email_set_flags_field(account_id, mail_ids, index, EMAIL_FLAGS_DELETED_FIELD, 1, true);
+       testapp_print("email_set_flags_field returns - err[%d]\n", err_code);
+
+       return 0;
+}
+
+static gboolean testapp_test_expunge_mails_deleted_flagged()
+{
+       int mailbox_id = 0;
+       int on_server = 0;
+       int err_code = EMAIL_ERROR_NONE;
+       int handle = 0;
+       int result_from_scanf = 0;
+
+       testapp_print("\n >>> Input target mailbox id: ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print("\n >>> Expunge on server?: ");
+       result_from_scanf = scanf("%d", &on_server);
+
+       err_code = email_expunge_mails_deleted_flagged(mailbox_id, on_server, &handle);
+
+       testapp_print("email_expunge_mails_deleted_flagged returns - err[%d]\n", err_code);
+
+       return 0;
+}
+
+static gboolean testapp_test_send_read_receipt()
+{
+       int read_mail_id = 0;
+       int receipt_mail_id = 0;
+       int err_code = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+       int handle = 0;
+
+       testapp_print("\n >>> Input read mail id: ");
+       result_from_scanf = scanf("%d", &read_mail_id);
+
+       err_code = email_add_read_receipt(read_mail_id, &receipt_mail_id);
+
+       testapp_print("eamil_add_read_receipt returns receipt_mail_id [%d] - err[%d]\n", receipt_mail_id, err_code);
+       testapp_print("Calling email_send_mail...\n");
+
+       if( (err_code = email_send_mail(receipt_mail_id, &handle)) != EMAIL_ERROR_NONE) {
+               testapp_print("Sending failed[%d]\n", err_code);
+       }
+       else  {
+               testapp_print("Start sending. handle[%d]\n", handle);
+       }
+
+       return 0;
+}
+
+static gboolean testapp_test_delete_attachment()
+{
+       int attachment_id = 0;
+       int err_code = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+
+       testapp_print("\n >>> Input attachment id: ");
+       result_from_scanf = scanf("%d", &attachment_id);
+
+       if( (err_code = email_delete_attachment(attachment_id)) != EMAIL_ERROR_NONE) {
+               testapp_print("email_delete_attachment failed[%d]\n", err_code);
+       }
+
+       return 0;
+}
+
+static gboolean testapp_test_get_mail_list()
+{
+       testapp_print("\n >>> testapp_test_get_mail_list : Entered \n");
+       email_mail_list_item_t *mail_list = NULL, **mail_list_pointer = NULL;
+       int mailbox_id = 0;
+       int count = 0, i = 0;
+       int account_id = 0;
+       int start_index =0;
+       int limit_count = 0;
+       int sorting = 0;
+       int err_code = EMAIL_ERROR_NONE;
+       int to_get_count = 0;
+       int is_for_thread_view = 0;
+       int list_type;
+       struct tm *temp_time_info;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter Account_id (0 = all accounts) : ");
+       result_from_scanf = scanf("%d",&account_id);
+
+       testapp_print("\n > Enter Mailbox id (0 = all mailboxes) :");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print("\n > Enter Sorting : ");
+       result_from_scanf = scanf("%d",&sorting);
+       
+       testapp_print("\n > Enter Start index (starting at 0): ");
+       result_from_scanf = scanf("%d",&start_index);
+
+       testapp_print("\n > Enter max_count : ");
+       result_from_scanf = scanf("%d",&limit_count);
+
+       testapp_print("\n > For thread view : ");
+       result_from_scanf = scanf("%d",&is_for_thread_view);
+
+       testapp_print("\n > Count mails?(1: YES):");
+       result_from_scanf = scanf("%d",&to_get_count);
+
+       if(to_get_count)
+               mail_list_pointer = NULL;
+       else
+               mail_list_pointer = &mail_list;
+       
+       if(is_for_thread_view == -2) {
+               list_type = EMAIL_LIST_TYPE_LOCAL;
+       }
+       else if(is_for_thread_view == -1)
+               list_type = EMAIL_LIST_TYPE_THREAD;
+       else
+               list_type = EMAIL_LIST_TYPE_NORMAL;
+       
+       /* Get mail list */
+       if( mailbox_id == 0) {
+               testapp_print("Calling email_get_mail_list for all mailbox.\n");
+               err_code = email_get_mail_list(account_id, 0, list_type, start_index, limit_count, sorting,  mail_list_pointer, &count);
+               if ( err_code < 0) 
+                       testapp_print("email_get_mail_list failed - err[%d]\n", err_code);
+       }
+       else {
+               testapp_print("Calling email_get_mail_list for %d mailbox_id.\n", mailbox_id);
+               err_code = email_get_mail_list(account_id, mailbox_id, list_type, start_index, limit_count, sorting,  mail_list_pointer, &count);
+               if ( err_code < 0) 
+                       testapp_print("email_get_mail_list failed - err[%d]\n", err_code);
+       }
+       testapp_print("email_get_mail_list >>>>>>count - %d\n",count);
+
+       if (mail_list) {
+               for (i=0; i< count; i++) {
+                       testapp_print("\n[%d]\n", i);
+                       testapp_print(" >>> mailbox_id [ %d ] \n", mail_list[i].mailbox_id);
+                       testapp_print(" >>> mail_id [ %d ] \n", mail_list[i].mail_id);
+                       testapp_print(" >>> account_id [ %d ] \n", mail_list[i].account_id);
+                       if (  mail_list[i].full_address_from != NULL )
+                               testapp_print(" >>> full_address_from [ %s ] \n", mail_list[i].full_address_from);
+                       if (  mail_list[i].email_address_recipient != NULL )
+                               testapp_print(" >>> email_address_recipient [ %s ] \n", mail_list[i].email_address_recipient);
+                       if (  mail_list[i].subject != NULL )
+                               testapp_print(" >>> subject [ %s ] \n", mail_list[i].subject);
+                       testapp_print(" >>> body_download_status [ %d ] \n", mail_list[i].body_download_status);
+                       temp_time_info = localtime(&mail_list[i].date_time);
+                       testapp_print(" >>> date_time [ %d/%d/%d %d:%d:%d] \n",
+                                                               temp_time_info->tm_year + 1900,
+                                                               temp_time_info->tm_mon+1,
+                                                               temp_time_info->tm_mday,
+                                                               temp_time_info->tm_hour,
+                                                               temp_time_info->tm_min,
+                                                               temp_time_info->tm_sec);
+                       testapp_print(" >>> flags_seen_field [ %d ] \n", mail_list[i].flags_seen_field);
+                       testapp_print(" >>> priority [ %d ] \n", mail_list[i].priority);
+                       testapp_print(" >>> save_status [ %d ] \n", mail_list[i].save_status);
+                       testapp_print(" >>> lock_status [ %d ] \n", mail_list[i].lock_status);
+                       testapp_print(" >>> attachment_count [ %d ] \n", mail_list[i].attachment_count);
+                       if (  mail_list[i].preview_text != NULL )
+                               testapp_print(" >>> preview_text [ %s ] \n", mail_list[i].preview_text);
+               }
+               free(mail_list);
+       }
+       
+       testapp_print("\n >>> email_get_mail_list : End \n");
+       return 0;
+}
+
+
+static gboolean testapp_test_get_mail_list_for_thread_view()
+{
+       testapp_print(" >>> testapp_test_get_mail_list_for_thread_view : Entered \n");
+       email_mail_list_item_t *mail_list = NULL;
+       int count = 0, i = 0;
+       int account_id = 0;
+       int mailbox_id = 0;
+       int result_from_scanf;
+       int err_code = EMAIL_ERROR_NONE;
+       struct tm *time_info;
+
+       testapp_print("\nEnter account id\n");
+       result_from_scanf = scanf("%d",&account_id);
+
+       testapp_print("\nEnter mailbox id\n");
+       result_from_scanf = scanf("%d",&mailbox_id);
+
+
+       /* Get mail list */
+       if ( email_get_mail_list(account_id, mailbox_id , EMAIL_LIST_TYPE_THREAD, 0, 500, EMAIL_SORT_DATETIME_HIGH, &mail_list, &count) < 0)  {
+               testapp_print("email_get_mail_list failed : %d\n",err_code);
+               return FALSE;
+       }
+       testapp_print("email_get_mail_list >>>>>>count - %d\n",count);
+       if (mail_list) {
+               for (i=0; i< count; i++) {
+                       testapp_print(" i [%d]\n", i);
+                       testapp_print(" >>> mail_id [ %d ] \n", mail_list[i].mail_id);
+                       testapp_print(" >>> account_id [ %d ] \n", mail_list[i].account_id);
+                       testapp_print(" >>> mailbox_id [ %d ] \n", mail_list[i].mailbox_id);
+                       testapp_print(" >>> full_address_from [ %s ] \n", mail_list[i].full_address_from);
+                       testapp_print(" >>> email_address_recipient [ %s ] \n", mail_list[i].email_address_recipient);
+                       testapp_print(" >>> subject [ %s ] \n", mail_list[i].subject);
+                       testapp_print(" >>> body_download_status [ %d ] \n", mail_list[i].body_download_status);
+                       time_info = localtime(&mail_list[i].date_time);
+                       testapp_print(" >>> date_time [ %s ] \n", asctime(time_info));
+                       testapp_print(" >>> flags_seen_field [ %d ] \n", mail_list[i].flags_seen_field);
+                       testapp_print(" >>> priority [ %d ] \n", mail_list[i].priority);
+                       testapp_print(" >>> save_status [ %d ] \n", mail_list[i].save_status);
+                       testapp_print(" >>> lock [ %d ] \n", mail_list[i].lock_status);
+                       testapp_print(" >>> attachment_count [ %d ] \n", mail_list[i].attachment_count);
+                       testapp_print(" >>> preview_text [ %s ] \n", mail_list[i].preview_text);
+                       testapp_print(" >>> thread_id [ %d ] \n", mail_list[i].thread_id);
+                       testapp_print(" >>> thread__item_count [ %d ] \n", mail_list[i].thread_item_count);
+               }
+               free(mail_list);
+       }       
+       testapp_print(" >>> testapp_test_get_mail_list_for_thread_view : End \n");
+       return 0;
+}
+
+static gboolean testapp_test_count ()
+{
+       int total = 0;
+       int unseen = 0;
+       email_list_filter_t *filter_list = NULL;
+
+       filter_list = malloc(sizeof(email_list_filter_t) * 3);
+       memset(filter_list, 0 , sizeof(email_list_filter_t) * 3);
+
+       filter_list[0].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[0].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_SUBJECT;
+       filter_list[0].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+       filter_list[0].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+       filter_list[0].list_filter_item.rule.case_sensitivity              = false;
+
+       filter_list[1].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_OPERATOR;
+       filter_list[1].list_filter_item.operator_type                      = EMAIL_LIST_FILTER_OPERATOR_OR;
+
+       filter_list[2].list_filter_item_type                               = EMAIL_LIST_FILTER_ITEM_RULE;
+       filter_list[2].list_filter_item.rule.target_attribute              = EMAIL_MAIL_ATTRIBUTE_TO;
+       filter_list[2].list_filter_item.rule.rule_type                     = EMAIL_LIST_FILTER_RULE_INCLUDE;
+       filter_list[2].list_filter_item.rule.key_value.string_type_value   = strdup("RE");
+       filter_list[2].list_filter_item.rule.case_sensitivity              = false;
+
+       if(EMAIL_ERROR_NONE == email_count_mail(filter_list, 3, &total, &unseen))
+               printf("\n Total: %d, Unseen: %d \n", total, unseen);
+       return 0;
+}
+
+static gboolean testapp_test_move_mails_to_mailbox_of_another_account()
+{
+       int  err = EMAIL_ERROR_NONE;
+       int  mail_id_count = 0 ;
+       int *mail_id_array = NULL;
+       int  source_mailbox_id = 0;
+       int  target_mailbox_id = 0;
+       int  task_id = 0;
+       int  i = 0;
+       int  result_from_scanf = 0;
+
+       testapp_print("\n > Enter source mailbox id: ");
+       result_from_scanf = scanf("%d", &source_mailbox_id);
+
+       testapp_print("\n > Enter target mailbox id: ");
+       result_from_scanf = scanf("%d", &target_mailbox_id);
+
+       testapp_print("\n > Enter mail count: ");
+       result_from_scanf = scanf("%d", &mail_id_count);
+
+       mail_id_count = (mail_id_count < 5000)?mail_id_count:5000;
+
+       if(mail_id_count > 0) {
+               mail_id_array = malloc(sizeof(int) * mail_id_count);
+       }
+
+       for(i = 0; i < mail_id_count; i++) {
+               testapp_print("\n > Enter mail id: ");
+               result_from_scanf = scanf("%d", (mail_id_array + i));
+       }
+
+       err = email_move_mails_to_mailbox_of_another_account(source_mailbox_id, mail_id_array, mail_id_count, target_mailbox_id, &task_id);
+
+       testapp_print("\nemail_move_mails_to_mailbox_of_another_account returns [%d], tast_id [%d] \n", err, task_id);
+       return 0;
+}
+
+static gboolean        copy_file(char *input_source_path, char *input_dest_path)
+{
+    int childExitStatus;
+    pid_t pid;
+    int status;
+    if (!input_source_path || !input_dest_path) {
+        return FALSE;
+    }
+    testapp_print("copy_file started\n");
+
+    pid = fork();
+
+    if (pid == 0) {
+       testapp_print("Copying file [%s] [%s]\n", input_source_path, input_dest_path);
+        execl("/bin/cp", "/bin/cp", input_source_path, input_dest_path, (char *)0);
+    }
+    else {
+       testapp_print("Wating child process\n");
+        pid_t ws = waitpid( pid, &childExitStatus, WNOHANG);
+        if (ws == -1)
+        { /* error - handle as you wish */
+               testapp_print("waitpid returns error\n");
+        }
+
+        if( WIFEXITED(childExitStatus)) /* exit code in childExitStatus */
+        {
+            status = WEXITSTATUS(childExitStatus); /* zero is normal exit */
+            testapp_print("WEXITSTATUS\n");
+            /* handle non-zero as you wish */
+        }
+        else if (WIFSIGNALED(childExitStatus)) /* killed */
+        {
+               testapp_print("WIFSIGNALED\n");
+        }
+        else if (WIFSTOPPED(childExitStatus)) /* stopped */
+        {
+               testapp_print("WIFSTOPPED\n");
+        }
+    }
+    testapp_print("copy_file finished\n");
+    return TRUE;
+}
+
+
+static gboolean        testapp_test_send_mail_with_downloading_attachment_of_original_mail()
+{
+       int err = EMAIL_ERROR_NONE;
+       int original_mail_id = 0;
+       int result_from_scanf = 0;
+       int original_attachment_count = 0;
+       int i = 0;
+       int handle = 0;
+       char *plain_text_path = MAIL_TEMP_BODY;
+       char *html_file_path = HTML_TEMP_BODY;
+       char new_subject[4086] = { 0, };
+/*     FILE *body_file; */
+       email_mail_data_t *original_mail_data = NULL;
+       email_mailbox_t *outbox = NULL;
+       email_attachment_data_t *original_attachment_array = NULL;
+
+       testapp_print("\n > Enter original mail id: ");
+       result_from_scanf = scanf("%d", &original_mail_id);
+
+       /* Get original mail */
+       if((err = email_get_mail_data(original_mail_id, &original_mail_data)) != EMAIL_ERROR_NONE || !original_mail_data) {
+               testapp_print("email_get_mail_data failed [%d]\n", err);
+               return FALSE;
+       }
+
+       /* Get attachment of original mail */
+       if((err = email_get_attachment_data_list(original_mail_id, &original_attachment_array, &original_attachment_count)) != EMAIL_ERROR_NONE || !original_attachment_array) {
+               testapp_print("email_get_attachment_data_list failed [%d]\n", err);
+               return FALSE;
+       }
+
+       /* Remove attachment file path */
+       for(i = 0; i < original_attachment_count; i++) {
+               original_attachment_array[i].save_status = 0;
+               if(original_attachment_array[i].attachment_path)
+                       free(original_attachment_array[i].attachment_path);
+               original_attachment_array[i].attachment_path = NULL;
+       }
+
+       /* Set reference mail id */
+       original_mail_data->reference_mail_id = original_mail_data->mail_id;
+       original_mail_data->body_download_status = 1;
+
+       /* Set from address */
+       if(!original_mail_data->full_address_from) {
+               original_mail_data->full_address_from = strdup("<abc@abc.com>");
+       }
+
+       /* Rewrite subject */
+       if(original_mail_data->subject) {
+               snprintf(new_subject, 4086, "Fw:%s", original_mail_data->subject);
+               free(original_mail_data->subject);
+               original_mail_data->subject = NULL;
+       }
+       else {
+               snprintf(new_subject, 4086, "Forward test");
+       }
+
+       original_mail_data->subject = strdup(new_subject);
+
+       /* Set mailbox information */
+       if((err = email_get_mailbox_by_mailbox_type(original_mail_data->account_id, EMAIL_MAILBOX_TYPE_OUTBOX, &outbox)) != EMAIL_ERROR_NONE || !outbox) {
+               testapp_print("email_get_mailbox_by_mailbox_type failed [%d]\n", err);
+               return FALSE;
+       }
+       original_mail_data->mailbox_id = outbox->mailbox_id;
+       original_mail_data->mailbox_type = outbox->mailbox_type;
+
+       /* Copy body text */
+       if(original_mail_data->file_path_html) {
+               copy_file(original_mail_data->file_path_html, html_file_path);
+               /*execl("/bin/cp", "/bin/cp", original_mail_data->file_path_html, html_file_path, (char *)0); */
+               free(original_mail_data->file_path_html);
+               original_mail_data->file_path_html = strdup(html_file_path);
+       }
+
+       if(original_mail_data->file_path_plain) {
+               copy_file(original_mail_data->file_path_plain, plain_text_path);
+               /*execl("/bin/cp", "/bin/cp", original_mail_data->file_path_plain, plain_text_path, (char *)0);*/
+               free(original_mail_data->file_path_plain);
+               original_mail_data->file_path_plain = strdup(plain_text_path);
+       }
+
+
+       /*
+       body_file = fopen(body_file_path, "w");
+
+       testapp_print("\n body_file [%p]\n", body_file);
+
+       if(body_file == NULL) {
+               testapp_print("\n fopen [%s]failed\n", body_file_path);
+               return FALSE;
+       }
+
+       for(i = 0; i < 100; i++)
+               fprintf(body_file, "Mail sending Test. [%d]\n", i);
+
+       fflush(body_file);
+       fclose(body_file);
+       */
+
+       /* Add mail */
+       if((err = email_add_mail(original_mail_data, original_attachment_array, original_attachment_count, NULL, false)) != EMAIL_ERROR_NONE) {
+               testapp_print("email_get_attachment_data_list failed [%d]\n", err);
+               return FALSE;
+       }
+
+       /* Send mail */
+       if((err = email_send_mail_with_downloading_attachment_of_original_mail(original_mail_data->mail_id, &handle)) != EMAIL_ERROR_NONE) {
+               testapp_print("email_send_mail_with_downloading_attachment_of_original_mail failed [%d]\n", err);
+               return FALSE;
+       }
+
+       if(original_mail_data)
+               email_free_mail_data(&original_mail_data, 1);
+
+       if(outbox)
+               email_free_mailbox(&outbox, 1);
+
+       if(original_attachment_array)
+               email_free_attachment_data(&original_attachment_array, original_attachment_count);
+
+       return TRUE;
+}
+
+
+
+static gboolean        testapp_test_set_flags_field ()
+{
+       int account_id = 0;
+       int mail_id = 0;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter Account ID: ");
+       result_from_scanf = scanf("%d", &account_id);
+       
+       testapp_print("\n > Enter Mail ID: ");
+       result_from_scanf = scanf("%d", &mail_id);
+
+       if(email_set_flags_field(account_id, &mail_id, 1, EMAIL_FLAGS_FLAGGED_FIELD, 1, 1) < 0)
+               testapp_print("email_set_flags_field failed");
+       else
+               testapp_print("email_set_flags_field success");
+               
+       return TRUE;
+}
+
+static gboolean testapp_test_download_body ()
+{
+       int mail_id = 0;
+       int handle = 0, err;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter Mail Id: ");
+       result_from_scanf = scanf("%d", &mail_id);
+       err = email_download_body(mail_id, 0, &handle);
+       if(err  < 0)
+               testapp_print("email_download_body failed");
+       else {
+               testapp_print("email_download_body success");
+               testapp_print("handle[%d]\n", handle);
+       }
+       return TRUE;
+}
+
+
+static gboolean testapp_test_cancel_download_body ()
+{
+       int mail_id = 0;
+       int account_id = 0;
+       int yes = 0;
+       int handle = 0;
+       int result_from_scanf = 0;
+       
+       email_mailbox_t mailbox;
+       memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+
+       testapp_print("\n > Enter account_id: ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n > Enter mail id: ");
+       result_from_scanf = scanf("%d", &mail_id);
+       
+       if( email_download_body(mail_id, 0, &handle) < 0)
+               testapp_print("email_download_body failed");
+       else {
+               testapp_print("email_download_body success\n");
+               testapp_print("Do u want to cancel download job>>>>>1/0\n");
+               result_from_scanf = scanf("%d",&yes);
+               if(1 == yes) {
+                       if(email_cancel_job(account_id, handle , EMAIL_CANCELED_BY_USER) < 0)
+                               testapp_print("email_cancel_job failed..!");
+                       else {
+                               testapp_print("email_cancel_job success..!");
+                               testapp_print("handle[%d]\n", handle);
+                       }
+               }
+                       
+       }
+       return TRUE;
+}
+static gboolean testapp_test_download_attachment ()
+{
+       int mail_id = 0;
+       int attachment_no = 0;
+       int handle = 0;
+       int result_from_scanf = 0;
+       
+       testapp_print("\n > Enter Mail Id: ");
+       result_from_scanf = scanf("%d", &mail_id);
+
+       testapp_print("\n > Enter attachment number: ");
+       result_from_scanf = scanf("%d", &attachment_no);
+       
+       if( email_download_attachment(mail_id, attachment_no ,&handle) < 0)
+               testapp_print("email_download_attachment failed");
+       else {
+               testapp_print("email_download_attachment success");
+               testapp_print("handle[%d]\n", handle);
+       }
+       return TRUE;
+
+}
+
+static gboolean testapp_test_retry_send()
+{
+       int mail_id = 0;
+       int timeout = 0;
+       int result_from_scanf = 0;
+       
+       email_mailbox_t mailbox;
+       memset(&mailbox, 0x00, sizeof(email_mailbox_t));
+
+       testapp_print("\n > Enter Mail Id: ");
+       result_from_scanf = scanf("%d", &mail_id);
+       
+       testapp_print("\n > Enter timeout in seconds: ");
+       result_from_scanf = scanf("%d", &timeout);
+
+       if( email_retry_sending_mail(mail_id, timeout) < 0)
+               testapp_print("email_retry_sending_mail failed");               
+       return TRUE;            
+}
+
+static gboolean testapp_test_move_all_mails_to_mailbox()
+{
+       int err = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+       int src_mailbox_id;
+       int dest_mailbox_id;
+
+       testapp_print("src mailbox id> ");
+       result_from_scanf = scanf("%d", &src_mailbox_id);
+
+       testapp_print("dest mailbox id> ");
+       result_from_scanf = scanf("%d", &dest_mailbox_id);
+       
+       err = email_move_all_mails_to_mailbox(src_mailbox_id, dest_mailbox_id);
+       if ( err < 0 ) {
+               testapp_print("email_move_all_mails_to_mailbox failed: err[%d]\n", err);
+       }
+       else {
+               testapp_print("email_move_all_mails_to_mailbox suceeded\n");
+       }
+
+       return false;
+}
+
+static gboolean testapp_test_get_totaldiskusage()
+{
+       unsigned long total_size = 0;
+       int err_code = EMAIL_ERROR_NONE ;
+       
+       err_code = email_get_disk_space_usage(&total_size);
+       if ( err_code < 0)
+               testapp_print("email_get_disk_space_usage failed err : %d\n",err_code);
+       else
+               testapp_print("email_get_disk_space_usage SUCCESS, total disk usage in KB : %ld \n", total_size);               
+
+       return FALSE;
+}
+
+
+
+static gboolean testapp_test_db_test()
+{
+       int err = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+       int mail_id;
+       int account_id;
+       char *to = NULL;
+       char *cc = NULL;
+       char *bcc = NULL;
+
+       to = (char *) malloc(500000);
+       cc = (char *) malloc(500000);
+       bcc = (char *) malloc(500000);
+       
+       memset(to, 0x00, sizeof(to));
+       memset(cc, 0x00, sizeof(to));
+       memset(bcc, 0x00, sizeof(to));
+
+       testapp_print("Input Mail id:\n");
+       result_from_scanf = scanf("%d", &mail_id);
+       testapp_print("Input Account id:\n");
+       result_from_scanf = scanf("%d", &account_id);
+       testapp_print("Input TO field:\n");
+       result_from_scanf = scanf("%s", to);
+       testapp_print("Input CC field:\n");
+       result_from_scanf = scanf("%s", cc);
+       testapp_print("Input BCC field:\n");
+       result_from_scanf = scanf("%s", bcc);
+       
+       if ( emstorage_test(mail_id, account_id, to, cc, bcc, &err) == true ) {
+               testapp_print(">> Saving Succeeded\n");
+       }
+       else {
+               testapp_print(">> Saving Failed[%d]\n", err);
+       }
+       
+       free(to);
+       free(cc);
+       free(bcc);
+       
+       return false;
+}
+
+static gboolean testapp_test_address_format_check_test()
+{
+       /*
+       int i;
+       int type;
+       int index;
+       int check_yn;
+       int err = EMAIL_ERROR_NONE;
+       char *pAddress = NULL;
+       char input_address[8096];
+       char *address_list[] = {
+               "tom@gmail.com",
+               "tom@gmail,com",
+               "tom@gmail.com@gmail.com",
+               "[tom@gmail.com]",
+               "\"Tom\"<tom@gmail.com>", 
+               "\"Tom\"[tom@gmail.com]",
+               "\"Tom\"<tom,@gmail.com>",
+               "<tom@gmail.com>",
+               "<tom@gmail,com>",
+               "<tom@gmail.>",
+               "<tom@gmail.com>,tom@gmail.com",
+               "<tom@gmail.com>;tom@gmail.com",
+               "tom @gmail.com",
+               "tom@ gmail.com",
+               "tom@gmail..com",
+               "tom@",
+               "tom@gmail",
+               "tom@gmail.",
+               "tom@gmail.c",
+               "tom@.",
+               "\"\"Tom\"<tom,@gmail.com>",
+               "tom@gmail.com,tom@gmail.com",
+               "tom@gmail.com.",
+               "<tom@gmail.com>,tom@.gmail.com",
+               "&& tom@live.com ----",
+               "madhu <tom@gmail.com>",
+               "tom@gmail.com, && tom@live.com",
+               "tom@gmail.com , && tom@live.com",
+               "< tom@gmail.com    > , <           tom@.gmail.com     >",
+               "tom@gmail.com ,           tom@gmail.com",
+               "<tom@gmail.com          >",
+               "<to     m@gmail.com          >",
+               "<tom@gmail.com>;tom@gmail.com",        
+              "Tom< tom@gmail.com > ,       Tom <tom@gmail.com>",      
+               " \"Tom\"  < tom@gmail.com>  ,  \"Tom\"   < tom@gmail.com> ,  Tom  < tom@gmail.com> ; Tom  < tom@gmail.com>,\"tomtom\" <   tom@aol.com>,\"tomtom\" <   tom@aol.com>    ,\"tomtom\" <tom@aol.com>;<tom@live.com>,  <tom@live.com>; \"tomtomtomtom\" <tom@live.com>  ; \"tomtomtomtom\" <tom@live.com>,\"Tom\"  < tom@gmail.com>",
+               "<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>,<tom@gmail.com>",
+               "             tom@gmail.com         ;   <  tom@gmail.com   > ",
+               "\"Tom\" <        tom@gmail.com >  ;  mama <  tom@gmail.com    >  ,   abcd@gmail.com     ,   abc@gmail.com ,\"tomtom\" <tom@aol.com>,\"tomtom\"  < tom@aol.com> ;\"tomtom\" <   tom@aol.com   >    ,\"tomtom\" <tom@aol.com> , \"tomtomtomtom\" <tom@live.com>  ",
+               "             \"tomtom\" <tom@aol.com>    ;\"tomtom\" <tom@aol.com> ;          ",
+               "  tom@gmail.com  ,   tom@gmail.com ,   tom@gmail.com; Tom  < tom@gmail.com   >  ,<   tom@aol.com>, <tom@aol.com>    ,<tom@aol.com>;<tom@live.com>,  tom@live.com;tom@live.com; \"tomtomtomtom\" <tom@live.com>,\"Tom\"  < tom@gmail.com> ;    ",
+               "<tom@aol.com>    , \"tomtomtomtom\" <tom@live.com>,\"Tom\"  < tom@gmail.com> ;    ",
+               " Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <   tom@gmail.com>  ,<tom@gmail.com>,Tom <tom@gmail.com       >,Tom< tom@gmail.com > ,       Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <tom@gmail.com>,Tom <tom@gmail.com>",
+               NULL
+       };
+       int address_count = 0;
+       
+       testapp_print("Select input method:\n");
+       testapp_print("1. Test data\n");
+       testapp_print("2. Keyboard\n");
+       result_from_scanf = scanf("%d", &type);
+
+       switch ( type ) {
+               case 1:
+                       do  {
+                               for ( i = 0; address_list[i] != NULL; i++ ) {
+                                       testapp_print("[%d] addr[%s]\n", i, address_list[i]);
+                                       address_count++;
+                               }
+                               testapp_print("Choose address to be tested:[99:quit]\n");
+                               result_from_scanf = scanf("%d", &index);
+                               if ( index == 99 )
+                                       break;
+
+                               testapp_print(">> [%d] Checking? (1:Yes, Other:No) [%s]\n", index, address_list[index]);
+                               result_from_scanf = scanf("%d", &check_yn);
+                               if ( check_yn == 1 ) {
+                                       pAddress = strdup(address_list[index]);
+                                       if ( em_verify_email_address(pAddress, false, &err ) == true ) {
+                                               testapp_print("<< [%d] Checking Succeeded : addr[%s]\n", index, address_list[index]);
+                                       }
+                                       else {
+                                               testapp_print("<< [%d] Checking Failed    : addr[%s], err[%d]\n", index, address_list[index], err);
+                                       }                       
+                                       if(pAddress) {
+                                               free(pAddress);
+                                               pAddress = NULL;
+                                       }
+                               }
+                               else {
+                                       testapp_print("<< [%d]  Skipped            : addr[%s]\n", index, address_list[index]);
+                               }
+                       } 
+                       while (1);
+                       break;
+               case 2:
+                       testapp_print("Input address: \n");
+                       result_from_scanf = scanf("%s", input_address);
+                       if ( em_verify_email_address(input_address, false, &err ) == true ) {
+                               testapp_print(">> Saving Succeeded : addr[%s]\n", input_address);
+                       }
+                       else {
+                               testapp_print(">> Saving Failed : addr[%s], err[%d]\n", input_address, err);
+                       }
+                       break;
+               default:
+                       testapp_print("wrong nuber... [%d]\n", type);
+                       break;
+       }
+       */
+       return FALSE;
+}
+
+static gboolean testapp_test_get_max_mail_count()
+{
+       int max_count = -1;
+       int err = EMAIL_ERROR_NONE;
+
+       err = email_get_max_mail_count(&max_count);
+       testapp_print("\n\t>>>>> email_get_max_mail_count() return [%d]\n\n", max_count);
+       
+       return false;
+}
+
+#include "email-storage.h"
+static gboolean testapp_test_test_get_thread_information()
+{
+       int error_code, thread_id= 38;
+       email_mail_list_item_t *result_mail;
+       
+       if( (error_code = email_get_thread_information_ex(thread_id, &result_mail)) == EMAIL_ERROR_NONE) {
+               testapp_print("email_get_thread_information returns = %d\n", error_code);
+               testapp_print("subject = %s\n", result_mail->subject);
+               testapp_print("mail_id = %d\n", result_mail->mail_id);
+               testapp_print("full_address_from = %s\n", result_mail->full_address_from);
+               testapp_print("thrad_id = %d\n", result_mail->thread_id);
+               testapp_print("count = %d\n", result_mail->thread_item_count);
+       }
+
+       return TRUE;
+}
+
+static gboolean testapp_test_get_address_info_list()
+{
+       testapp_print(" >>> testapp_test_get_address_info_list : Entered \n");
+
+       char buf[1024];
+       int i = 0;
+       int mail_id = 0;
+       int result_from_scanf = 0;
+       email_address_info_list_t *address_info_list= NULL;
+       email_address_info_t *p_address_info = NULL;
+       GList *list = NULL;
+       GList *node = NULL;
+
+       memset(buf, 0x00, sizeof(buf));
+       testapp_print("\n > Enter mail_id: ");
+       result_from_scanf = scanf("%d",&mail_id);
+
+       email_get_address_info_list(mail_id, &address_info_list);
+
+       testapp_print("===================================================\n");
+       testapp_print("\t\t\t address info list\n");
+       testapp_print("===================================================\n");
+       testapp_print("address_type\t address \t\tdisplay_name\t contact id\n");
+       testapp_print("===================================================\n");
+
+       for ( i = EMAIL_ADDRESS_TYPE_FROM; i <= EMAIL_ADDRESS_TYPE_BCC; i++ ) {
+               switch ( i ) {
+                       case EMAIL_ADDRESS_TYPE_FROM:
+                               list = address_info_list->from;
+                               break;
+                       case EMAIL_ADDRESS_TYPE_TO:
+                               list = address_info_list->to;
+                               break;
+                       case EMAIL_ADDRESS_TYPE_CC:
+                               list = address_info_list->cc;
+                               break;
+                       case EMAIL_ADDRESS_TYPE_BCC:
+                               list = address_info_list->bcc;
+                               break;
+               }
+
+               /*  delete dynamic-allocated memory for each item */
+               node = g_list_first(list);
+               while ( node != NULL ) {
+                       p_address_info = (email_address_info_t*)node->data;
+                       testapp_print("%d\t\t%s\t%s\t%d\n", p_address_info->address_type, p_address_info->address, p_address_info->display_name, p_address_info->contact_id);
+
+                       node = g_list_next(node);
+               }
+               testapp_print("\n");
+       }
+       testapp_print("===================================================\n");
+
+       if(address_info_list)
+               email_free_address_info_list(&address_info_list);
+
+       testapp_print(" >>> testapp_test_get_address_info_list : END \n");
+       return TRUE;
+}
+
+static gboolean testapp_test_search_mail_on_server()
+{
+       testapp_print(" >>> testapp_test_search_mail_on_server : Entered \n");
+
+       int err_code = EMAIL_ERROR_NONE;
+       int account_id = 0;
+       int mailbox_id = 0;
+       int search_key_value_integer = 0;
+       int result_from_scanf = 0;
+       email_search_filter_type search_filter_type = 0;
+       email_search_filter_t search_filter;
+       int handle = 0;
+       time_t current_time = 0;
+       char search_key_value_string[MAX_EMAIL_ADDRESS_LENGTH];
+
+       testapp_print("input account id : ");
+       result_from_scanf = scanf("%d",&account_id);
+
+       testapp_print("input mailbox id : ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print(
+               "       EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO       =  1,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_UID              =  2,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_BCC              =  7,  ( string type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_CC               =  9,  ( string type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_FROM             = 10,  ( string type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_KEYWORD          = 11,  ( string type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_SUBJECT          = 13,  ( string type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_TO               = 15,  ( string type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER      = 16,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER     = 17,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE = 20,  ( time type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON     = 21,  ( time type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE  = 22,  ( time type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED   = 26,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED    = 28,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT      = 30,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED     = 32,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT     = 34,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN       = 36,  ( integet type ) \n"
+               "       EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       = 43,  ( string type ) \n");
+       testapp_print("input search filter type : ");
+       result_from_scanf = scanf("%d", (int*)&search_filter_type);
+
+       search_filter.search_filter_type = search_filter_type;
+
+       switch(search_filter_type) {
+               case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_NO       :
+               case EMAIL_SEARCH_FILTER_TYPE_UID              :
+               case EMAIL_SEARCH_FILTER_TYPE_SIZE_LARSER      :
+               case EMAIL_SEARCH_FILTER_TYPE_SIZE_SMALLER     :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_ANSWERED   :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DELETED    :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_DRAFT      :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_FLAGED     :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_RECENT     :
+               case EMAIL_SEARCH_FILTER_TYPE_FLAGS_SEEN       :
+                       testapp_print("input search filter key value : ");
+                       result_from_scanf = scanf("%d", &search_key_value_integer);
+                       search_filter.search_filter_key_value.integer_type_key_value = search_key_value_integer;
+                       break;
+
+               case EMAIL_SEARCH_FILTER_TYPE_BCC              :
+               case EMAIL_SEARCH_FILTER_TYPE_CC               :
+               case EMAIL_SEARCH_FILTER_TYPE_FROM             :
+               case EMAIL_SEARCH_FILTER_TYPE_KEYWORD          :
+               case EMAIL_SEARCH_FILTER_TYPE_SUBJECT          :
+               case EMAIL_SEARCH_FILTER_TYPE_TO               :
+               case EMAIL_SEARCH_FILTER_TYPE_MESSAGE_ID       :
+                       testapp_print("input search filter key value : ");
+                       result_from_scanf = scanf("%s", search_key_value_string);
+                       search_filter.search_filter_key_value.string_type_key_value = search_key_value_string;
+                       break;
+
+               case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_BEFORE :
+               case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_ON     :
+               case EMAIL_SEARCH_FILTER_TYPE_SENT_DATE_SINCE  :
+                       time(&current_time);
+                       /* TODO : write codes for converting string to time */
+                       /* search_filter.search_filter_key_value.time_type_key_value = search_key_value_string; */
+                       search_filter.search_filter_key_value.time_type_key_value = current_time;
+                       break;
+               default :
+                       testapp_print("Invalid filter type [%d]", search_filter_type);
+                       return FALSE;
+       }
+
+       if( (err_code = email_search_mail_on_server(account_id, mailbox_id, &search_filter,1, &handle)) != EMAIL_ERROR_NONE) {
+               testapp_print("email_search_mail_on_server failed [%d]", err_code);
+       }
+
+       testapp_print(" >>> testapp_test_search_mail_on_server : END \n");
+       return TRUE;
+}
+
+static gboolean testapp_test_add_mail_to_search_result_box()
+{
+       int                    i = 0;
+       int                    account_id = 0;
+       int                    from_eas = 0;
+       int                    attachment_count = 0;
+       int                    err = EMAIL_ERROR_NONE;
+       int                    result_from_scanf = 0;
+       char                   arg[50] = { 0 , };
+       char                  *body_file_path = MAIL_TEMP_BODY;
+       email_mailbox_t         *mailbox_data = NULL;
+       email_mail_data_t       *test_mail_data = NULL;
+       email_attachment_data_t *attachment_data = NULL;
+       email_meeting_request_t *meeting_req = NULL;
+       FILE                  *body_file = NULL;
+
+       testapp_print("\n > Enter account id : ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       email_get_mailbox_by_mailbox_type(account_id, EMAIL_MAILBOX_TYPE_SEARCH_RESULT, &mailbox_data);
+
+       test_mail_data = malloc(sizeof(email_mail_data_t));
+       memset(test_mail_data, 0x00, sizeof(email_mail_data_t));
+
+       testapp_print("\n From EAS? [0/1]> ");
+       result_from_scanf = scanf("%d", &from_eas);
+
+       test_mail_data->account_id           = account_id;
+       test_mail_data->save_status          = 1;
+       test_mail_data->body_download_status = 1;
+       test_mail_data->flags_seen_field     = 1;
+       test_mail_data->file_path_plain      = strdup(body_file_path);
+       test_mail_data->mailbox_id           = mailbox_data->mailbox_id;
+       test_mail_data->mailbox_type         = mailbox_data->mailbox_type;
+       test_mail_data->full_address_from    = strdup("<test1@test.com>");
+       test_mail_data->full_address_to      = strdup("<test2@test.com>");
+       test_mail_data->full_address_cc      = strdup("<test3@test.com>");
+       test_mail_data->full_address_bcc     = strdup("<test4@test.com>");
+       test_mail_data->subject              = strdup("Into search result mailbox");
+
+       body_file = fopen(body_file_path, "w");
+
+       for(i = 0; i < 500; i++)
+               fprintf(body_file, "X2 X2 X2 X2 X2 X2 X2");
+       fflush(body_file);
+       fclose(body_file);
+
+       testapp_print(" > Attach file? [0/1] : ");
+       result_from_scanf = scanf("%d",&attachment_count);
+
+       if ( attachment_count )  {
+               memset(arg, 0x00, 50);
+               testapp_print("\n > Enter attachment name : ");
+               result_from_scanf = scanf("%s", arg);
+
+               attachment_data = malloc(sizeof(email_attachment_data_t));
+
+               attachment_data->attachment_name  = strdup(arg);
+
+               memset(arg, 0x00, 50);
+               testapp_print("\n > Enter attachment absolute path : ");
+               result_from_scanf = scanf("%s",arg);
+
+               attachment_data->attachment_path  = strdup(arg);
+               attachment_data->save_status      = 1;
+               test_mail_data->attachment_count  = attachment_count;
+       }
+
+       testapp_print("\n > Meeting Request? [0: no, 1: yes (request from server), 2: yes (response from local)]");
+       result_from_scanf = scanf("%d", (int*)&(test_mail_data->meeting_request_status));
+
+       if ( test_mail_data->meeting_request_status == 1
+               || test_mail_data->meeting_request_status == 2 ) {
+               time_t current_time;
+               /*  dummy data for meeting request */
+               meeting_req = malloc(sizeof(email_meeting_request_t));
+               memset(meeting_req, 0x00, sizeof(email_meeting_request_t));
+
+               meeting_req->meeting_response     = 1;
+               current_time = time(NULL);
+               gmtime_r(&current_time, &(meeting_req->start_time));
+               gmtime_r(&current_time, &(meeting_req->end_time));
+               meeting_req->location = malloc(strlen("Seoul") + 1);
+               memset(meeting_req->location, 0x00, strlen("Seoul") + 1);
+               strcpy(meeting_req->location, "Seoul");
+               strcpy(meeting_req->global_object_id, "abcdef12345");
+
+               meeting_req->time_zone.offset_from_GMT = 9;
+               strcpy(meeting_req->time_zone.standard_name, "STANDARD_NAME");
+               gmtime_r(&current_time, &(meeting_req->time_zone.standard_time_start_date));
+               meeting_req->time_zone.standard_bias = 3;
+
+               strcpy(meeting_req->time_zone.daylight_name, "DAYLIGHT_NAME");
+               gmtime_r(&current_time, &(meeting_req->time_zone.daylight_time_start_date));
+               meeting_req->time_zone.daylight_bias = 7;
+
+       }
+
+       if((err = email_add_mail(test_mail_data, attachment_data, attachment_count, meeting_req, from_eas)) != EMAIL_ERROR_NONE)
+               testapp_print("email_add_mail failed. [%d]\n", err);
+       else
+               testapp_print("email_add_mail success.\n");
+
+       testapp_print("saved mail id = [%d]\n", test_mail_data->mail_id);
+
+       if(attachment_data)
+               email_free_attachment_data(&attachment_data, attachment_count);
+
+       if(meeting_req)
+               email_free_meeting_request(&meeting_req, 1);
+
+       email_free_mail_data(&test_mail_data, 1);
+       email_free_mailbox(&mailbox_data, 1);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_email_parse_mime_file()
+{
+       email_mail_data_t *mail_data = NULL;
+       email_attachment_data_t *mail_attachment_data = NULL;
+       int i = 0;
+       int attachment_count = 0;
+       int err = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+       char eml_file_path[255] = {0, };
+
+       testapp_print("Input eml file path : ");
+       result_from_scanf = scanf("%s", eml_file_path);
+
+       if ((err = email_parse_mime_file(eml_file_path, &mail_data, &mail_attachment_data, &attachment_count)) != EMAIL_ERROR_NONE)
+       {
+               testapp_print("email_parse_mime_file failed : [%d]\n", err);
+               return false;   
+       }
+       
+       testapp_print("load success\n");
+       testapp_print("Return-Path: %s\n", mail_data->full_address_return);
+       testapp_print("To: %s\n", mail_data->full_address_to);
+       testapp_print("Subject: %s\n", mail_data->subject);
+       testapp_print("From: %s\n", mail_data->full_address_from);
+       testapp_print("Reply-To: %s\n", mail_data->full_address_reply);
+       testapp_print("Sender: %s\n", mail_data->email_address_sender);
+       testapp_print("Message-ID: %s\n", mail_data->message_id);
+       testapp_print("attachment_count: %d\n", mail_data->attachment_count);
+       testapp_print("inline content count : %d\n", mail_data->inline_content_count);
+
+       for (i = 0;i < mail_data->attachment_count ; i++) {
+               testapp_print("attachment_id: %d\n", mail_attachment_data[i].attachment_id);
+               testapp_print("inline_attachment_status: %d\n", mail_attachment_data[i].inline_content_status);
+               testapp_print("attachment_name: %s\n", mail_attachment_data[i].attachment_name);
+               testapp_print("attachment_path: %s\n", mail_attachment_data[i].attachment_path);
+               testapp_print("mailbox_id: %d\n", mail_attachment_data[i].mailbox_id);
+       }
+
+       testapp_print("Success : Open eml file\n");
+       
+       if ((err = email_delete_parsed_data(mail_data)) != EMAIL_ERROR_NONE) {
+               testapp_print("email_delete_eml_data failed : [%d]\n", err);
+               return false;
+       }
+
+       testapp_print("Success : email_delete_eml_data\n");
+
+       if (mail_data)
+               email_free_mail_data(&mail_data, 1);
+       
+       testapp_print("Success : email_free_mail_data\n");
+
+       if (mail_attachment_data)
+               email_free_attachment_data(&mail_attachment_data, attachment_count);
+
+       testapp_print("Success : email_free_attachment_data\n");
+
+       return true;
+
+}
+
+static gboolean testapp_test_email_write_mime_file()
+{
+       int err = EMAIL_ERROR_NONE;
+       int mail_id = 0;
+       int ret_scanf = 0;
+       int is_file_path = 0;
+       int attachment_count = 0;
+       int account_id = 0;
+       char *file_path = NULL;
+       email_mail_data_t *mail_data = NULL;
+       email_attachment_data_t *mail_attachment_data = NULL;
+
+       testapp_print("Is file path (0 or 1): ");
+       ret_scanf = scanf("%d", &is_file_path);
+       
+       if (is_file_path) {
+               file_path = malloc(512);
+               memset(file_path, 0x00, 512);
+
+               testapp_print("Input output file path : ");
+               ret_scanf = scanf("%s", file_path);     
+       }
+       testapp_print("Input mail id : ");
+       ret_scanf = scanf("%d", &mail_id);
+
+
+       err = email_get_mail_data(mail_id, &mail_data);
+       if (err != EMAIL_ERROR_NONE || mail_data == NULL) {
+               testapp_print("email_get_mail_data failed : [%d]\n", err);
+               return false;
+       }
+
+       err = email_get_attachment_data_list(mail_id, &mail_attachment_data, &attachment_count);
+       if (err != EMAIL_ERROR_NONE) {
+               testapp_print("email_get_attachment_data_list failed : [%d]\n", err);
+               return false;
+       }
+
+       testapp_print("Input Account id : ");
+       ret_scanf = scanf("%d", &account_id);
+
+       mail_data->account_id = account_id;
+
+       err = email_write_mime_file(mail_data, mail_attachment_data, attachment_count, &file_path);
+       if (err != EMAIL_ERROR_NONE) {
+               testapp_print("email_write_mime_file failed : [%d]\n", err);
+               return false;
+       }
+
+       testapp_print("file path : [%s]\n", file_path);
+
+       if (mail_data)
+               email_free_mail_data(&mail_data, 1);
+       
+       if (mail_attachment_data)
+               email_free_attachment_data(&mail_attachment_data, attachment_count);
+
+       if (file_path)
+               free(file_path);
+
+       return true;
+}
+
+static gboolean testapp_test_smime_verify_signature()
+{
+       int mail_id = 0;
+       int ret_scanf = 0;
+       int verify = 0;
+       int err = EMAIL_ERROR_NONE;
+
+       testapp_print("input mail_id :");
+       ret_scanf = scanf("%d", &mail_id);
+       
+       err = email_verify_signature(mail_id, &verify);
+       if (err != EMAIL_ERROR_NONE) {
+               testapp_print("Failed Verify\n");
+               return false;
+       }
+
+       testapp_print("verify value : [%d]\n", verify); 
+       return true;
+}
+
+/* internal functions */
+static gboolean testapp_test_interpret_command (int menu_number)
+{
+       gboolean go_to_loop = TRUE;
+       
+       switch (menu_number) {
+               case 1:
+                       testapp_test_get_mails();
+                       break;
+               case 2:
+                       testapp_test_mail_send(NULL);
+                       break;
+               case 3:
+                       testapp_test_get_mail_list_ex();
+                       break;
+               case 4:
+                       testapp_test_add_attachment();
+                       break;                  
+               case 5:
+                       testapp_test_set_deleted_flag();
+                       break;
+               case 6:
+                       testapp_test_expunge_mails_deleted_flagged();
+                       break;
+               case 7:
+                       testapp_test_send_read_receipt();
+                       break;
+               case 8:
+                       testapp_test_delete_attachment();
+                       break;
+               case 9:
+                       testapp_test_count();
+                       break;
+               case 10:
+                       testapp_test_move_mails_to_mailbox_of_another_account();
+                       break;
+               case 11:
+                       testapp_test_send_mail_with_downloading_attachment_of_original_mail();
+                       break;
+               case 14:
+                       testapp_test_delete();
+                       break;
+               case 16:
+                       testapp_test_download_body();
+                       break;
+               case 17:
+                       testapp_test_download_attachment();
+                       break;          
+               case 20:
+                       testapp_test_delete_all();
+                       break;
+               case 21:
+                       testapp_test_move();
+                       break;
+               case 23:
+                       testapp_test_retry_send();
+                       break;
+               case 27:
+                       testapp_test_move_all_mails_to_mailbox();
+                       break;
+               case 38:
+                       testapp_test_get_totaldiskusage();
+                       break;
+               case 40:
+                       testapp_test_address_format_check_test();
+                       break;
+               case 41:
+                       testapp_test_get_max_mail_count();
+                       break;
+               case 42:
+                       testapp_test_db_test();
+                       break;
+               case 43:
+                       testapp_test_send_cancel();
+                       break;
+               case 44:
+                       testapp_test_cancel_download_body();
+                       break;
+               case 46:
+                        testapp_test_get_mail_list_for_thread_view();
+                       break;
+               case 48:
+                       testapp_test_test_get_thread_information();
+                       break;
+               case 51:
+                       testapp_test_get_mail_list();
+                       break;
+               case 52:
+                       testapp_test_get_address_info_list();
+                       break;
+               case 55:
+                       testapp_test_set_flags_field();
+                       break;
+               case 56:
+                       testapp_test_add_mail(NULL);
+                       break;
+               case 57:
+                       testapp_test_update_mail();
+                       break;
+               case 58:
+                       testapp_test_search_mail_on_server();
+                       break;
+               case 59:
+                       testapp_test_add_mail_to_search_result_box();
+                       break;
+               case 60:
+                       testapp_test_email_parse_mime_file();
+                       break;
+               case 62:
+                       testapp_test_smime_verify_signature();
+                       break;
+               case 61:
+                       testapp_test_email_write_mime_file();
+                       break;
+               case 0:
+                       go_to_loop = FALSE;
+                       break;
+               default:
+                       break;
+       }
+
+       return go_to_loop;
+}
+
+void testapp_mail_main()
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+       int result_from_scanf = 0;
+       
+       while (go_to_loop) {
+               testapp_show_menu(EMAIL_MAIL_MENU);
+               testapp_show_prompt(EMAIL_MAIL_MENU);
+                       
+               result_from_scanf = scanf("%d", &menu_number);
+
+               go_to_loop = testapp_test_interpret_command (menu_number);
+       }
+}
+
diff --git a/utilities/test-application/testapp-mailbox.c b/utilities/test-application/testapp-mailbox.c
new file mode 100755 (executable)
index 0000000..915a11f
--- /dev/null
@@ -0,0 +1,470 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/* common header */
+#include <stdio.h>
+#include <string.h>
+
+
+/* open header */
+#include <glib.h>
+
+#include "email-api-account.h"
+#include "email-api-network.h"
+#include "email-api-mailbox.h"
+
+/* internal header */
+#include "testapp-utility.h"
+#include "testapp-mailbox.h"
+
+static gboolean testapp_print_mailbox_list(email_mailbox_t *input_mailbox_list, int input_count)
+{
+       int i;
+       char time_string[40] = { 0, };
+
+
+
+       testapp_print("There are %d mailboxes\n", input_count);
+
+       testapp_print("============================================================================\n");
+       testapp_print("id   a_id  name\t\t\t         alias\t\t unread\t total\t total_on_ server\tmailbox_type\t last_sync_time\n");
+       testapp_print("============================================================================\n");
+       if ( input_count == 0 ) {
+               testapp_print("No mailbox is matched\n");
+       }
+       else {
+               for(i=0;i<input_count;i++) {
+                       strftime(time_string, 40, "%Y-%m-%d %H:%M:%S", localtime(&(input_mailbox_list[i].last_sync_time)));
+                       testapp_print("[%2d]", input_mailbox_list[i].mailbox_id);
+                       testapp_print("  %2d  [%2d]\t[%-12s]  ", input_mailbox_list[i].account_id, input_mailbox_list[i].mailbox_id, input_mailbox_list[i].alias);
+                       testapp_print(" %3d\t %3d\t %3d\t %3d\t %s\n"
+                                       , input_mailbox_list[i].unread_count
+                                       , input_mailbox_list[i].total_mail_count_on_local
+                                       , input_mailbox_list[i].total_mail_count_on_server
+                                       , input_mailbox_list[i].mailbox_type
+                                       , time_string);
+               }
+       }
+       testapp_print("============================================================================\n");
+
+       return FALSE;
+}
+
+static gboolean testapp_test_add_mailbox()
+{
+       email_mailbox_t  mailbox;
+       int account_id,mailbox_type = 0;
+       int local_yn = 0;
+       char arg[500];
+       int ret;
+    int handle;
+    int result_from_scanf = 0;
+
+       memset(arg, 0x00, 500);
+       testapp_print("\n> Enter mailbox name: ");
+       result_from_scanf = scanf("%s",arg);
+       mailbox.mailbox_name = strdup(arg);
+       
+       memset(arg, 0x00, 500);
+       testapp_print("> Enter mailbox alias name: ");
+       result_from_scanf = scanf("%s",arg);
+       mailbox.alias = strdup(arg);
+
+       testapp_print("> Enter account id: ");
+       result_from_scanf = scanf("%d", &account_id);
+       mailbox.account_id = account_id;
+
+       testapp_print("> Enter local_yn (1/0): ");
+       result_from_scanf = scanf("%d", &local_yn);
+       mailbox.local= local_yn;        
+
+
+       testapp_print("> Enter mailbox type: ");
+       result_from_scanf = scanf("%d", &mailbox_type);
+       mailbox.mailbox_type= mailbox_type;
+
+       ret = email_add_mailbox(&mailbox, local_yn?0:1, &handle);
+
+       if (ret  < 0) {
+               testapp_print("\n email_add_mailbox failed");
+       }
+       else {
+               testapp_print("\n email_add_mailbox succeed : handle[%d], mailbox_id [%d]\n", handle, mailbox.mailbox_id);
+       }
+       
+       return FALSE;
+}
+
+static gboolean testapp_test_delete_mailbox()
+{
+       int mailbox_id = 0;
+       int on_server = 0;
+       int ret;
+       int handle;
+       int result_from_scanf = 0;
+
+       testapp_print("\n> Enter mailbox id:");
+       result_from_scanf = scanf("%d", &mailbox_id);
+       
+       testapp_print("> Enter on_server (1/0): ");
+       result_from_scanf = scanf("%d", &on_server);
+
+       ret = email_delete_mailbox(mailbox_id, on_server, &handle);
+
+       if ( ret < 0) {
+               testapp_print("\n email_delete_mailbox failed");
+       }
+       else {
+               testapp_print("\n email_delete_mailbox succeed : handle[%d]\n", handle);
+       }
+       
+       return FALSE;
+
+}
+
+static gboolean testapp_test_rename_mailbox()
+{
+       testapp_print ("testapp_test_rename_mailbox\n");
+       int mailbox_id;
+       char mailbox_name[500] = { 0, };
+       char mailbox_alias[500] = { 0, };
+       int err;
+       int result_from_scanf = 0;
+       int handle = 0;
+       
+       testapp_print("> Enter mailbox id: ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print("> Enter new mailbox name: ");
+       result_from_scanf = scanf("%s", mailbox_name);
+
+       testapp_print("> Enter new mailbox name: ");
+       result_from_scanf = scanf("%s", mailbox_alias);
+
+       
+       if ( (err = email_rename_mailbox(mailbox_id, mailbox_name, mailbox_alias, true, &handle)) < 0) {
+               testapp_print("\n email_rename_mailbox failed[%d]\n", err);
+       }
+       else {
+               testapp_print("\n email_rename_mailbox succeed\n");
+       }
+
+       return FALSE;
+}
+
+static gboolean testapp_test_get_imap_mailbox_list()
+{
+       int account_id = 0;
+       int handle = 0;
+       int result_from_scanf = 0;
+       
+       testapp_print("> Enter account id: ");
+       result_from_scanf = scanf("%d", &account_id);
+       
+       if(  email_sync_imap_mailbox_list(account_id, &handle) < 0)
+               testapp_print("email_sync_imap_mailbox_list failed");
+
+       return FALSE;
+
+}
+
+static gboolean testapp_test_set_local_mailbox()
+{
+       int mailbox_id = 0;
+       int is_local_mailbox = 0;
+       int result_from_scanf = 0;
+
+       testapp_print("> Enter mailbox id: ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print("> Enter local: ");
+       result_from_scanf = scanf("%d", &is_local_mailbox);
+
+       if( email_set_local_mailbox(mailbox_id, is_local_mailbox) < 0)
+               testapp_print("email_set_local_mailbox failed");
+
+       return FALSE;
+}
+
+static gboolean testapp_test_delete_mailbox_ex()
+{
+       int  err = EMAIL_ERROR_NONE;
+       int  mailbox_id_count = 0 ;
+       int *mailbox_id_array = NULL;
+       int  account_id = 0;
+       int  on_server = 0;
+       int  handle = 0;
+       int  i = 0;
+       int  result_from_scanf = 0;
+
+       testapp_print("\n > Enter account_id: ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n > Enter mailbox_id_count: ");
+       result_from_scanf = scanf("%d", &mailbox_id_count);
+
+       testapp_print("\n > Enter on_server: ");
+       result_from_scanf = scanf("%d", &on_server);
+
+       mailbox_id_count = (mailbox_id_count < 5000)?mailbox_id_count:5000;
+
+       if(mailbox_id_count > 0) {
+               mailbox_id_array = malloc(sizeof(int) * mailbox_id_count);
+       }
+
+       for(i = 0; i < mailbox_id_count; i++) {
+               testapp_print("\n > Enter mailbox id: ");
+               result_from_scanf = scanf("%d", (mailbox_id_array + i));
+       }
+
+       err = email_delete_mailbox_ex(account_id, mailbox_id_array, mailbox_id_count, on_server, &handle);
+
+       testapp_print("\nemail_delete_mailbox_ex returns [%d], handle [%d] \n", err, handle);
+       return 0;
+}
+
+static gboolean testapp_test_get_mailbox_by_type()
+{
+
+       int account_id =0;      
+       int err_code = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+       email_mailbox_t *mailbox =NULL;
+       email_mailbox_type_e mailbox_type =0;
+       
+       testapp_print("\n > Enter account id: ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n > Enter mailbox_type: ");
+       result_from_scanf = scanf("%d", (int*)&mailbox_type);
+
+       if( (err_code = email_get_mailbox_by_mailbox_type(account_id,mailbox_type,&mailbox)) < 0) {
+               testapp_print("   email_get_mailbox_by_mailbox_type error : %d\n",err_code);
+               return false ;
+       }
+
+       testapp_print_mailbox_list(mailbox, 1);
+       
+       email_free_mailbox(&mailbox, 1);
+       return FALSE;
+}
+
+static gboolean testapp_test_set_mailbox_type()
+{
+       int  mailbox_id = 0;
+       int  mailbox_type = 0;
+       int  err_code = EMAIL_ERROR_NONE;
+       int  result_from_scanf = 0;
+
+       testapp_print("\n > Enter mailbox id : ");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print("\n > Enter mailbox type : ");
+       result_from_scanf = scanf("%d", &mailbox_type);
+
+       if( (err_code = email_set_mailbox_type(mailbox_id, mailbox_type) ) != EMAIL_ERROR_NONE) {
+               testapp_print("\nemail_set_mailbox_type error : %d\n", err_code);
+       }
+
+       return FALSE;
+}
+
+static gboolean testapp_test_set_mail_slot_size ()
+{
+       int account_id = 0;
+       int mailbox_id = 0;
+       int mail_slot_size = 0;
+       int err_code = EMAIL_ERROR_NONE;
+       int result_from_scanf = 0;
+       
+       testapp_print("\n > Enter account id (0: All account): ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n> Enter mailbox id (0 : All mailboxes):");
+       result_from_scanf = scanf("%d", &mailbox_id);
+
+       testapp_print("\n > Enter mailbox slot size: ");
+       result_from_scanf = scanf("%d", &mail_slot_size);
+
+       if( (err_code = email_set_mail_slot_size(account_id, mailbox_id, mail_slot_size) ) < 0) {
+               testapp_print("   testapp_test_set_mail_slot_size error : %d\n", err_code);
+               return false ;
+       }
+
+       return FALSE;
+}
+
+static gboolean testapp_test_get_mailbox_list ()
+{
+       int result_from_scanf = 0;
+       int account_id =0;
+       int mailbox_sync_type;
+       int count = 0;
+       int error_code = EMAIL_ERROR_NONE;
+       email_mailbox_t *mailbox_list=NULL;
+       testapp_print("\n > Enter account id: ");
+       result_from_scanf = scanf("%d", &account_id);
+       testapp_print("\n > Enter mailbox_sync_type\n[-1 :for all mailboxes, 0 : for mailboxes from server, 1 : local mailboxes\n : ");
+       result_from_scanf = scanf("%d", &mailbox_sync_type);
+
+       if((error_code = email_get_mailbox_list(account_id, mailbox_sync_type, &mailbox_list, &count)) < 0) {
+               testapp_print("   email_get_mailbox_list error %d\n", error_code);
+               return false ;
+       }
+
+       testapp_print_mailbox_list(mailbox_list, count);
+
+       email_free_mailbox(&mailbox_list, count);
+
+       if((error_code = email_get_mailbox_list_ex(account_id, mailbox_sync_type, 1, &mailbox_list, &count)) < 0) {
+               testapp_print("   email_get_mailbox_list_ex error %d\n", error_code);
+               return false ;
+       }
+
+       testapp_print_mailbox_list(mailbox_list, count);
+
+       email_free_mailbox(&mailbox_list, count);
+       return FALSE;
+}
+
+static gboolean testapp_test_sync_mailbox()
+{
+       int result_from_scanf = 0;
+       int account_id = 0;
+       int handle = 0;
+       int mailbox_id = 0;
+
+       testapp_print("\n > Enter Account id (0: for all account) : ");
+       result_from_scanf = scanf("%d",&account_id);
+
+       testapp_print("\n > Enter Mailbox id (0: for all mailboxes) : ");
+       result_from_scanf = scanf("%d",&mailbox_id);
+
+       if(account_id == ALL_ACCOUNT) {
+               if(email_sync_header_for_all_account(&handle) < 0)
+                       testapp_print("\n email_sync_header_for_all_account failed\n");
+               else
+                       testapp_print("\n email_sync_header_for_all_account success. Handle[%d]\n", handle);
+       }
+       else {
+               if(email_sync_header(account_id, mailbox_id, &handle) < 0)
+                       testapp_print("\n email_sync_header failed\n");
+               else
+                       testapp_print("\n email_sync_header success. Handle[%d]\n", handle);
+       }
+
+       return FALSE;
+}
+
+static gboolean testapp_test_stamp_sync_time()
+{
+       int result_from_scanf;
+       int input_mailbox_id = 0;
+
+       testapp_print("\n > Enter Mailbox id : ");
+       result_from_scanf = scanf("%d",&input_mailbox_id);
+
+       email_stamp_sync_time_of_mailbox(input_mailbox_id);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_interpret_command (int menu_number)
+{
+       gboolean go_to_loop = TRUE;
+       
+       switch (menu_number) {
+               case 1:
+                       testapp_test_add_mailbox();
+                       break;
+
+               case 2:
+                       testapp_test_delete_mailbox();
+                       break;
+
+               case 3:
+                       testapp_test_rename_mailbox();
+                       break;
+
+               case 4:
+                       testapp_test_get_imap_mailbox_list();
+                       break;
+
+               case 5:
+                       testapp_test_set_local_mailbox();
+                       break;
+
+               case 6:
+                       testapp_test_delete_mailbox_ex();
+                       break;
+
+               case 7:
+                       testapp_test_get_mailbox_by_type();
+                       break;
+
+               case 8:
+                       testapp_test_set_mailbox_type();
+                       break;  
+
+               case 9:
+                       testapp_test_set_mail_slot_size();
+                       break;  
+
+               case 10:
+                       testapp_test_get_mailbox_list ();
+                       break;
+
+               case 11:
+                       testapp_test_sync_mailbox();
+                       break;
+
+               case 12:
+                       testapp_test_stamp_sync_time();
+                       break;
+
+               case 0:
+                       go_to_loop = FALSE;
+                       break;
+               default:
+                       break;
+       }
+
+       return go_to_loop;
+}
+
+void email_test_mailbox_main()
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+       int result_from_scanf = 0;
+       
+       while (go_to_loop) {
+               testapp_show_menu (EMAIL_MAILBOX_MENU);
+               testapp_show_prompt (EMAIL_MAILBOX_MENU);
+                       
+               result_from_scanf = scanf("%d", &menu_number);
+
+               go_to_loop = testapp_test_interpret_command (menu_number);
+       }
+}
+
diff --git a/utilities/test-application/testapp-others.c b/utilities/test-application/testapp-others.c
new file mode 100755 (executable)
index 0000000..92f8e5a
--- /dev/null
@@ -0,0 +1,487 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+/* common header */
+#include <stdio.h>
+#include <string.h>
+
+/* open header */
+#include <glib.h>
+#include <dlfcn.h>
+#include <vconf.h>
+#include "c-client.h" 
+
+
+#include "email-api.h"
+#include "email-api-account.h"
+#include "email-api-network.h"
+
+
+/* internal header */
+#include "testapp-utility.h"
+#include "testapp-others.h"
+#include "email-ipc.h"
+#include "email-core-utils.h"
+
+static gboolean testapp_test_get_network_status()
+{
+       int on_sending = 0;
+       int on_receiving = 0;
+       email_get_network_status(&on_sending, &on_receiving);
+       testapp_print("\tNetwork status : \n On sending - %d \n On Receiving - %d \n", on_sending, on_receiving);
+       return FALSE;
+}
+
+static gboolean testapp_test_get_pending_job()
+{
+       int action = -1;
+       int account_id = 0;
+       int mail_id = 0;
+       int result_from_scanf = 0;
+       email_event_status_type_t status = -1;
+       testapp_print( " Enter Action \n SEND_MAIL = 0 \n SYNC_HEADER = 1 \n" \
+                           " DOWNLOAD_BODY,= 2 \n DOWNLOAD_ATTACHMENT = 3 \n" \
+                           " DELETE_MAIL = 4 \n SEARCH_MAIL = 5 \n SAVE_MAIL = 6 \n" \
+                           " NUM = 7 \n");
+       result_from_scanf = scanf("%d",&action);
+
+       testapp_print("\n > Enter account_id: ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n > Enter Mail Id: ");
+       result_from_scanf = scanf("%d", &mail_id);
+
+       if( email_get_pending_job( action, account_id, mail_id, &status) >= 0)
+               testapp_print("\t status - %d \n",status);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_cancel_job        ()
+{
+       int account_id = 0;
+       int handle = 0;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter account_id (0: all account): ");
+       result_from_scanf = scanf("%d", &account_id);
+
+       testapp_print("\n > Enter handle: ");
+       result_from_scanf = scanf("%d", &handle);
+
+       if(email_cancel_job(account_id, handle, EMAIL_CANCELED_BY_USER) < 0)
+               testapp_print("email_cancel_job failed..!");
+       return FALSE;
+}
+
+static gboolean testapp_test_set_dnet_proper_profile_type()
+{
+       testapp_print("NOT Support\n");
+       
+       return TRUE;
+}
+
+static gboolean testapp_test_get_dnet_proper_profile_type()
+{
+       testapp_print("NOT Support\n");
+
+       return TRUE;
+}
+
+static gboolean testapp_test_get_preview_text_from_file()
+{
+       int   result_from_scanf;
+       char *preview_buffer = NULL;
+       char  html_file_path[1024] = { 0, };
+
+       testapp_print("\n > Enter file path : ");
+       result_from_scanf = scanf("%s", html_file_path);
+
+       emcore_get_preview_text_from_file(NULL, html_file_path, 1024, &preview_buffer);
+
+       testapp_print("\n result :\n %s ", preview_buffer);
+
+       return TRUE;
+}
+
+static gboolean testapp_test_print_receving_queue_via_debug_msg()
+{
+       int err;
+       void* hAPI = (void*)emipc_create_email_api(_EMAIL_API_PRINT_RECEIVING_EVENT_QUEUE);
+
+       if(hAPI == NULL)
+               return EMAIL_ERROR_NULL_VALUE;
+               
+       if(emipc_execute_proxy_api(hAPI) != EMAIL_ERROR_NONE) {
+               testapp_print("testapp_test_print_receving_queue_via_debug_msg - emipc_execute_proxy_api failed \n ");
+               if(hAPI == NULL)
+                       return EMAIL_ERROR_NULL_VALUE;
+       }
+
+       emipc_get_parameter(hAPI, 1, 0, sizeof(int), &err);
+       
+       testapp_print(" >>>> RETURN VALUE : %d \n", err);
+
+       emipc_destroy_email_api(hAPI);
+
+       hAPI = NULL;
+       testapp_print("testapp_test_print_receving_queue_via_debug_msg  ..........End\n");
+       return err;
+}
+
+static gboolean testapp_test_create_db_full()
+{
+       int err;
+
+       err = email_create_db_full();
+       
+       testapp_print("testapp_test_create_db_full returns [%d]", err);
+
+       return err;
+}
+
+static int encode_base64(char *src, unsigned long src_len, char **enc, unsigned long* enc_len, int *err_code)
+{
+       unsigned char *content = NULL;
+       int ret = true; 
+       int err = EMAIL_ERROR_NONE;
+
+       if (err_code != NULL) {
+               *err_code = EMAIL_ERROR_NONE;
+       }
+
+       content = rfc822_binary(src, src_len, enc_len);
+
+       if (content)
+               *enc = (char *)content;
+       else {
+               err = EMAIL_ERROR_UNKNOWN;
+               ret = false;
+       }
+
+       if (err_code)
+           *err_code = err;
+
+       return ret;
+}
+
+
+static gboolean testapp_test_encoding_test()
+{
+       int error = EMAIL_ERROR_NONE;
+       int has_special_character = 0, base64_file_name_length = 0, i;
+       gsize bytes_read, bytes_written;
+       char *encoded_file_name = NULL, *base64_file_name = NULL;
+       SIZEDTEXT source_text;
+       GError *glib_error = NULL;
+       CHARSET *result_charset = NULL;
+       char filename[] = {0xEB, 0xB0, 0x94, 0xED, 0x83, 0x95, 0x32, 0x2E, 0x70, 0x6E, 0x67, 0x00}; /* UTF-8 */
+
+       source_text.data = (unsigned char*)filename; 
+       source_text.size = strlen(filename);
+
+       result_charset = (CHARSET*)utf8_infercharset(&source_text);
+
+       if(result_charset) {
+               testapp_print("return_charset->name [%s]", result_charset->name);
+               encoded_file_name = (char*)g_convert (filename, -1, "UTF-8", result_charset->name, &bytes_read, &bytes_written, &glib_error);
+       }
+       else {
+               i = 0;
+               while(filename[i++] & 0x80)
+                       has_special_character = 1;
+               testapp_print("has_special_character [%d]", has_special_character);
+               if(has_special_character)
+                       encoded_file_name = (char*)g_convert (filename, -1, "UTF-8", "EUC-KR", &bytes_read, &bytes_written, &glib_error);
+       }
+       
+       if(encoded_file_name == NULL)
+               encoded_file_name = strdup(filename);
+
+       testapp_print("encoded_file_name [%s]", encoded_file_name);
+
+       if(!encode_base64(encoded_file_name, strlen(encoded_file_name), &base64_file_name, (unsigned long*)&base64_file_name_length, &error)) {
+               testapp_print("encode_base64 failed. error [%d]", error);
+               goto FINISH_OFF;
+       }
+
+       testapp_print("base64_file_name [%s]", base64_file_name);
+
+       if(base64_file_name) {
+               free(encoded_file_name);
+               encoded_file_name = malloc(strlen(base64_file_name) + 15);
+               if(!encoded_file_name) {
+                       testapp_print("em_malloc failed.");
+                       goto FINISH_OFF;
+               }
+               snprintf(encoded_file_name, strlen(base64_file_name) + 15, "=?UTF-8?B?%s?=", base64_file_name);
+               testapp_print("encoded_file_name [%s]", encoded_file_name);
+       }
+FINISH_OFF:
+
+       if (encoded_file_name)
+               free(encoded_file_name);
+
+       if (base64_file_name)
+               free(base64_file_name);
+
+       return error;
+}
+
+#define LIB_EMAIL_SERVICE_PATH "/usr/lib/libemail-api.so"
+
+int (*Datastore_FI_EMTB)(char **);
+int (*Datastore_FI_EMSB)(char **);
+int (*Datastore_FI_EMOB)(char **);
+int (*Datastore_FI_EMDR)(char **);
+int (*Datastore_FI_EMMF)(char **);
+int (*Datastore_FI_EMTR)(char **);
+int (*Datastore_FI_EMSP)(char **);
+
+static gboolean email_test_dtt_Datastore_FI()
+{
+       void *handle = NULL;
+       char *dl_error = NULL, *output_str = NULL;
+
+       handle = dlopen(LIB_EMAIL_SERVICE_PATH, RTLD_LAZY | RTLD_GLOBAL);
+       if (!handle) {
+               dl_error = dlerror();
+               if (dl_error)
+                       testapp_print("\t dlopen error : Open Library with absolute path return  :  %s\n", dl_error);
+               return false;
+       }       
+
+       Datastore_FI_EMTB = dlsym(handle, "Datastore_FI_EMTB");
+       Datastore_FI_EMSB = dlsym(handle, "Datastore_FI_EMSB");
+       Datastore_FI_EMOB = dlsym(handle, "Datastore_FI_EMOB");
+       Datastore_FI_EMDR = dlsym(handle, "Datastore_FI_EMDR");
+       Datastore_FI_EMMF = dlsym(handle, "Datastore_FI_EMMF");
+       Datastore_FI_EMTR = dlsym(handle, "Datastore_FI_EMTR");
+       Datastore_FI_EMSP = dlsym(handle, "Datastore_FI_EMSP");
+
+       Datastore_FI_EMTB(&output_str);
+
+       testapp_print("\nemail_test_dtt_Datastore_FI\n%s\n", output_str);
+       
+       if(output_str)
+               free(output_str);
+
+       if (handle) {
+               dlclose(handle);
+               dl_error = dlerror();
+               if (dl_error)
+                       testapp_print("\t Close handle return  :  %s\n", dl_error);
+       }
+
+       return true;
+}
+
+int (*Datastore_R_EMTB)(char **);
+int (*Datastore_R_EMSB)(char **);
+int (*Datastore_R_EMOB)(char **);
+int (*Datastore_R_EMDR)(char **);
+int (*Datastore_R_EMMF)(char **);
+int (*Datastore_R_EMTR)(char **);
+int (*Datastore_R_EMSP)(char **);
+
+
+static gboolean email_test_dtt_Datastore_R()
+{
+       void *handle = NULL;
+       char *dl_error = NULL, *output_str = NULL;
+
+       handle = dlopen(LIB_EMAIL_SERVICE_PATH, RTLD_LAZY | RTLD_GLOBAL);
+       if (!handle) {
+               dl_error = dlerror();
+               if (dl_error)
+                       testapp_print("\t dlopen error : Open Library with absolute path return  :  %s\n", dl_error);
+               return false;
+       }       
+
+       Datastore_R_EMTB = dlsym(handle, "Datastore_R_EMTB");
+       Datastore_R_EMSB = dlsym(handle, "Datastore_R_EMSB");
+       Datastore_R_EMOB = dlsym(handle, "Datastore_R_EMOB");
+       Datastore_R_EMDR = dlsym(handle, "Datastore_R_EMDR");
+       Datastore_R_EMMF = dlsym(handle, "Datastore_R_EMMF");
+       Datastore_R_EMTR = dlsym(handle, "Datastore_R_EMTR");
+       Datastore_R_EMSP = dlsym(handle, "Datastore_R_EMSP");
+
+       Datastore_R_EMTB(&output_str);
+
+       testapp_print("\nemail_test_dtt_Datastore_R\n%s\n", output_str);
+
+       if(output_str)
+               free(output_str);
+
+       if (handle) {
+               dlclose(handle);
+               dl_error = dlerror();
+               if (dl_error)
+                       testapp_print("\t Close handle return  :  %s\n", dl_error);
+       }
+
+       return true;
+}
+
+int (*Datastore_C_EMTB)(char **);
+int (*Datastore_C_EMSB)(char **);
+int (*Datastore_C_EMOB)(char **);
+int (*Datastore_C_EMDR)(char **);
+int (*Datastore_C_EMMF)(char **);
+int (*Datastore_C_EMTR)(char **);
+int (*Datastore_C_EMSP)(char **);
+
+static gboolean email_test_dtt_Datastore_C()
+{
+       void *handle = NULL;
+       char *dl_error = NULL, *output_str = NULL;
+
+       handle = dlopen(LIB_EMAIL_SERVICE_PATH, RTLD_LAZY | RTLD_GLOBAL);
+       if (!handle) {
+               dl_error = dlerror();
+               if (dl_error)
+                       testapp_print("\t dlopen error : Open Library with absolute path return  :  %s\n", dl_error);
+               return false;
+       }       
+
+       Datastore_C_EMTB = dlsym(handle, "Datastore_C_EMTB");
+       Datastore_C_EMSB = dlsym(handle, "Datastore_C_EMSB");
+       Datastore_C_EMOB = dlsym(handle, "Datastore_C_EMOB");
+       Datastore_C_EMDR = dlsym(handle, "Datastore_C_EMDR");
+       Datastore_C_EMMF = dlsym(handle, "Datastore_C_EMMF");
+       Datastore_C_EMTR = dlsym(handle, "Datastore_C_EMTR");
+       Datastore_C_EMSP = dlsym(handle, "Datastore_C_EMSP");
+
+       Datastore_C_EMTB(&output_str);
+
+
+       testapp_print("\nemail_test_dtt_Datastore_C\n%s\n", output_str);
+       
+       if(output_str)
+               free(output_str);
+
+       if (handle) {
+               dlclose(handle);
+               dl_error = dlerror();
+               if (dl_error)
+                       testapp_print("\t Close handle return  :  %s\n", dl_error);
+       }
+
+       return true;
+}
+
+static gboolean testapp_test_show_user_message()
+{
+       int mail_id;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter mail id : ");
+       result_from_scanf = scanf("%d", &mail_id);
+
+       email_show_user_message(mail_id, EMAIL_ACTION_SEND_MAIL, EMAIL_ERROR_NETWORK_NOT_AVAILABLE);
+       return FALSE;
+}
+
+static gboolean testapp_test_get_mime_entity()
+{
+       char mime_path[512] = {0, };
+       int result_from_scanf = 0;
+       char *mime_entity = NULL;
+
+       testapp_print("\n > Enter mime path for parsing : ");
+       result_from_scanf = scanf("%s", mime_path);
+       
+       email_get_mime_entity(mime_path, &mime_entity);
+
+       testapp_print("\nmime_entity = %s\n", mime_entity);
+       return true;
+}
+
+static gboolean testapp_test_interpret_command (int menu_number)
+{
+       gboolean go_to_loop = TRUE;
+
+       switch (menu_number) {
+               case 1:
+                       testapp_test_get_network_status();
+                       break;
+               case 2:
+                       testapp_test_get_pending_job ();
+                       break;
+               case 3:
+                       testapp_test_cancel_job ();
+                       break;
+               case 5: 
+                       testapp_test_set_dnet_proper_profile_type();
+                       break;
+               case 6:
+                       testapp_test_get_dnet_proper_profile_type();
+                       break;
+               case 7:
+                       testapp_test_get_preview_text_from_file();
+                       break;
+               case 11:
+                       testapp_test_print_receving_queue_via_debug_msg();
+                       break;
+               case 12:
+                       testapp_test_create_db_full();
+                       break;
+               case 13:
+                       testapp_test_encoding_test();
+                       break;
+               case 14:
+                       email_test_dtt_Datastore_FI();
+                       email_test_dtt_Datastore_C();
+                       email_test_dtt_Datastore_R();
+                       break;
+               case 15:
+                       testapp_test_show_user_message();
+                       break;
+               case 16:
+                       testapp_test_get_mime_entity();
+                       break;
+               case 0:
+                       go_to_loop = FALSE;
+                       break;
+               default:
+                       break;
+       }
+
+       return go_to_loop;
+}
+
+void testapp_others_main()
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+       int result_from_scanf = 0;
+
+       while (go_to_loop) {
+               testapp_show_menu (EMAIL_OTHERS_MENU);
+               testapp_show_prompt (EMAIL_OTHERS_MENU);
+
+               result_from_scanf = scanf ("%d", &menu_number);
+
+               go_to_loop = testapp_test_interpret_command (menu_number);
+       }
+}
+
diff --git a/utilities/test-application/testapp-rule.c b/utilities/test-application/testapp-rule.c
new file mode 100755 (executable)
index 0000000..ca8dfed
--- /dev/null
@@ -0,0 +1,252 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/* common header */
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+
+/* open header */
+#include <glib.h>
+
+#include "email-api-rule.h"
+
+/* internal header */
+#include "testapp-utility.h"
+#include "testapp-mailbox.h"
+
+static gboolean testapp_test_add_rule()
+{
+       email_rule_t*  rule = NULL;
+       int account_id = 0;
+       int target_mailbox_id = 0;
+       int action = 0;
+       int type = 0;
+       int flag = 0;
+       char arg[500];
+       int result_from_scanf = 0;
+
+       rule = malloc(sizeof(email_rule_t));
+       testapp_print("> Enter account id: ");
+       result_from_scanf = scanf("%d", &account_id);
+       rule->account_id = account_id;
+
+       testapp_print("> Enter Type(FROM - 1 / SUBJECT - 2): ");
+       result_from_scanf = scanf("%d", &type);
+       rule->type= type;               
+
+       memset(arg, 0x00, 500);
+       testapp_print("\n> Enter Filtering Value:");
+       result_from_scanf = scanf("%s",arg);
+       rule->value= strdup(arg);       
+
+       testapp_print("> Enter Action(MOVE - 1, BLOCK - 2, DELETE - 3): ");
+       result_from_scanf = scanf("%d", &action);
+       rule->faction= action;  
+
+       if (action == 1) {
+               testapp_print("\n> Enter target mailbox id:");
+               result_from_scanf = scanf("%d", &target_mailbox_id);
+               rule->target_mailbox_id = target_mailbox_id;
+       }
+
+       testapp_print("> Enter Flag1 value: ");
+       result_from_scanf = scanf("%d", &flag);
+       rule->flag1= flag;
+
+       testapp_print("> Enter Flag2 value: ");
+       result_from_scanf = scanf("%d", &flag);
+       rule->flag2= flag;
+
+       if ( email_add_rule(rule) < 0)
+               testapp_print("\n email_add_rule failed");
+
+       
+       email_free_rule(&rule, 1);
+       
+       return FALSE;
+}
+
+static gboolean testapp_test_delete_rule()
+{
+       int result_from_scanf = 0;
+       int filter_id = 0;
+
+       testapp_print("> Enter filter id: ");
+       result_from_scanf = scanf("%d", &filter_id);
+
+       if(email_delete_rule(filter_id) < 0)
+               testapp_print("email_delete_rule failed..! ");
+               
+       return FALSE;
+}
+
+
+static gboolean testapp_test_update_rule()
+{
+       int result_from_scanf = 0;
+       email_rule_t*  rule = NULL;
+       int account_id = 0;
+       int target_mailbox_id = 0;
+       int action = 0;
+       int type = 0;
+       int flag = 0;
+       char arg[500];
+       int filter_id = 0;
+
+       rule = malloc(sizeof(email_rule_t));
+       memset(rule,0X00,sizeof(email_rule_t));
+       testapp_print("> Enter filter id: ");
+       result_from_scanf = scanf("%d", &filter_id);
+       
+       testapp_print("> Enter account id: ");
+       result_from_scanf = scanf("%d", &account_id);
+       rule->account_id = account_id;
+
+       testapp_print("> Enter Type(FROM - 1 / SUBJECT - 2): ");
+       result_from_scanf = scanf("%d", &type);
+       rule->type= type;               
+
+       memset(arg, 0x00, 500);
+       testapp_print("\n> Enter Filtering Value:");
+       result_from_scanf = scanf("%s",arg);
+       rule->value= strdup(arg);       
+
+       testapp_print("> Enter Action(MOVE - 1, BLOCK - 2, DELETE - 3): ");
+       result_from_scanf = scanf("%d", &action);
+       rule->faction= action;  
+
+       if (action == 1) {
+               testapp_print("\n> Enter target mailbox id:");
+               result_from_scanf = scanf("%d", &target_mailbox_id);
+               rule->target_mailbox_id = target_mailbox_id;
+       }
+
+       testapp_print("> Enter Flag1 value: ");
+       result_from_scanf = scanf("%d", &flag);
+       rule->flag1= flag;
+
+       testapp_print("> Enter Flag2 value: ");
+       result_from_scanf = scanf("%d", &flag);
+       rule->flag2= flag;
+       
+       if( !email_update_rule(filter_id, rule) < 0)
+               testapp_print("email_update_rule failed..! ");
+               
+       email_free_rule(&rule, 1);
+               
+       return FALSE;
+}
+
+
+static gboolean testapp_test_get_rule(void)
+{
+       email_rule_t*  rule = NULL;
+       int filter_id = 0;
+       int result_from_scanf = 0;
+
+       testapp_print("> Enter filter id: ");
+       result_from_scanf = scanf("%d", &filter_id);
+
+       if(email_get_rule(filter_id, &rule) >= 0)       
+               testapp_print("\n Got rule of account_id = %d and type = %d\n", rule->account_id, rule->type);
+
+       email_free_rule(&rule, 1);
+       
+       return FALSE;
+       
+}
+
+static gboolean testapp_test_get_rule_list     (void)
+{
+       int count, i;
+       email_rule_t* rule_list=NULL;
+
+       if(email_get_rule_list(&rule_list, &count) < 0) {
+               testapp_print("   email_get_rule_list error\n");
+               return false ;
+       }
+       
+       for(i=0;i<count;i++){
+               testapp_print("   %2d) Fileter_Id: %d | Account_id: %d  | Type: %d | Value %s \n", i+1, 
+                       rule_list[i].filter_id,
+                       rule_list[i].account_id, 
+                       rule_list[i].type,
+                       rule_list[i].value);
+       }
+
+       email_free_rule(&rule_list, count);
+       return FALSE;
+
+}
+
+
+
+static gboolean testapp_test_interpret_command (int menu_number)
+{
+       gboolean go_to_loop = TRUE;
+       
+       switch (menu_number) {
+               case 1:
+                       testapp_test_add_rule();
+                       break;
+               case 2:
+                       testapp_test_delete_rule ();
+                       break;
+               case 3:
+                       testapp_test_update_rule();
+                       break;
+               case 5:
+                       testapp_test_get_rule ();
+                       break;
+               case 6:
+                       testapp_test_get_rule_list();
+                       break;
+
+               case 0:
+                       go_to_loop = FALSE;
+                       break;
+               default:
+                       break;
+       }
+
+       return go_to_loop;
+}
+
+void email_test_rule_main()
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+       int result_from_scanf = 0;
+       
+       while (go_to_loop) {
+               testapp_show_menu (EMAIL_RULE_MENU);
+               testapp_show_prompt (EMAIL_RULE_MENU);
+                       
+               result_from_scanf = scanf("%d", &menu_number);
+
+               go_to_loop = testapp_test_interpret_command (menu_number);
+       }
+}
+
diff --git a/utilities/test-application/testapp-thread.c b/utilities/test-application/testapp-thread.c
new file mode 100755 (executable)
index 0000000..34b913e
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/* common header */
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+
+/* open header */
+#include <glib.h>
+
+#include "email-api-account.h"
+#include "email-api-mail.h"
+
+/* internal header */
+#include "testapp-utility.h"
+#include "testapp-thread.h"
+
+static gboolean testapp_test_move_thread()
+{
+       int thread_id, move_always_flag;
+       int target_mailbox_id;
+       int result;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter thread_id: ");
+       result_from_scanf = scanf("%d", &thread_id);
+
+       testapp_print("\n > Enter target_mailbox_id: ");
+       result_from_scanf = scanf("%d", &target_mailbox_id);
+
+       testapp_print("\n > Enter move_always_flag: ");
+       result_from_scanf = scanf("%d", &move_always_flag);
+       
+       result = email_move_thread_to_mailbox(thread_id, target_mailbox_id, move_always_flag);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_delete_thread()
+{
+       int thread_id, delete_always_flag;
+       int result;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter thread_id: ");
+       result_from_scanf = scanf("%d", &thread_id);
+
+       testapp_print("\n > Enter delete_always_flag: ");
+       result_from_scanf = scanf("%d", &delete_always_flag);
+
+       result = email_delete_thread(thread_id, delete_always_flag);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_set_seen_flag_of_thread()
+{
+       int thread_id, seen_flag, on_server;
+       int result;
+       int result_from_scanf = 0;
+
+       testapp_print("\n > Enter thread_id: ");
+       result_from_scanf = scanf("%d", &thread_id);
+
+       testapp_print("\n > Enter seen_flag: ");
+       result_from_scanf = scanf("%d", &seen_flag);
+
+       testapp_print("\n > Enter on_server: ");
+       result_from_scanf = scanf("%d", &on_server);
+
+       result = email_modify_seen_flag_of_thread(thread_id, seen_flag, on_server);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_interpret_command (int menu_number)
+{
+       gboolean go_to_loop = TRUE;
+
+       switch (menu_number) {
+               case 1:
+                       testapp_test_move_thread();
+                       break;
+
+               case 2:
+                       testapp_test_delete_thread();
+                       break;
+
+               case 3:
+                       testapp_test_set_seen_flag_of_thread();
+                       break;
+
+               case 0:
+                       go_to_loop = FALSE;
+                       break;
+               default:
+                       break;
+       }
+
+       return go_to_loop;
+}
+
+void testapp_thread_main()
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+       int result_from_scanf = 0;
+
+       while (go_to_loop) {
+               testapp_show_menu (EMAIL_THREAD_MENU);
+               testapp_show_prompt (EMAIL_THREAD_MENU);
+
+               result_from_scanf = scanf("%d", &menu_number);
+
+               go_to_loop = testapp_test_interpret_command (menu_number);
+       }
+}
diff --git a/utilities/test-application/testapp-utility.c b/utilities/test-application/testapp-utility.c
new file mode 100755 (executable)
index 0000000..acf39ae
--- /dev/null
@@ -0,0 +1,235 @@
+/*
+*  email-service
+*
+* Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact: Kyuho Jo <kyuho.jo@samsung.com>, Sunghyun Kwon <sh0701.kwon@samsung.com>
+* 
+* 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.
+*
+*/
+
+
+
+/* common header */
+#include <stdarg.h>
+#include <string.h>
+
+/* open header */
+#include <glib.h>
+#include <glib/gprintf.h>
+
+/* internal header */
+#include "testapp-utility.h"
+
+/* internal data struct */
+
+void testapp_print (char *fmt, ...)
+{
+       va_list args = {0};
+       va_start(args, fmt);
+       vfprintf (stdout, fmt, args);
+       va_end (args);
+       fflush (stdout);
+}
+
+void testapp_show_menu (eEMAIL_MENU menu)
+{
+       switch (menu) {
+               case EMAIL_MAIN_MENU:
+                       testapp_print ("==========================================\n");
+                       testapp_print ("    Email test application \n");
+                       testapp_print ("==========================================\n");
+                       testapp_print ("1. Account Test\n");
+                       testapp_print ("2. Mail Test\n");
+                       testapp_print ("3. Mailbox Test\n");
+                       testapp_print ("5. Rule Test\n");
+                       testapp_print ("6. Thread Test\n");
+                       testapp_print ("7. Others\n");
+                       testapp_print ("0. Exit \n");
+                       testapp_print ("------------------------------------------\n");
+                       break;
+                       
+               case EMAIL_ACCOUNT_MENU:
+                       testapp_print ("==========================================\n");
+                       testapp_print ("    ACCOUNT MENU \n");
+                       testapp_print ("==========================================\n");
+                       testapp_print (" 1.  Create account\n");
+                       testapp_print (" 2.  Update account\n");
+                       testapp_print (" 3.  Delete account\n");
+                       testapp_print (" 4.  Get account\n");
+                       testapp_print (" 5.  Get account list\n");
+                       testapp_print (" 7.  Validate account\n");
+                       testapp_print (" 8.  Cancel validate Account\n");
+                       testapp_print (" 9.  Backup All accounts\n");
+                       testapp_print (" 10. Restore accounts\n");
+                       testapp_print (" 11. Get password length of account\n");
+                       testapp_print (" 12. Query server info\n");
+                       testapp_print (" 13. Clear all notifications\n");
+                       testapp_print (" 14. Save default account ID\n");
+                       testapp_print (" 15. Load default account ID\n");
+                       testapp_print (" 16. Add certificate\n");
+                       testapp_print (" 17. Get certificate\n");
+                       testapp_print (" 18. Delete certificate\n");
+                       testapp_print (" 0.  Go to Main Menu\n");
+                       testapp_print ("------------------------------------------\n");
+                       break;
+                       
+               case EMAIL_MAIL_MENU:
+                       testapp_print ("==========================================\n");
+                       testapp_print ("    MAIL MENU\n");
+                       testapp_print ("==========================================\n");
+                       testapp_print ("1.  Get mails\n");
+                       testapp_print ("2.  Send a mail\n");
+                       testapp_print ("3.  Get mail list ex\n");
+                       testapp_print ("4.  Add Attachment\n");
+                       testapp_print ("5.  Set deleted flag\n");
+                       testapp_print ("6.  Expunge deleted flagged mails\n");
+                       testapp_print ("7.  Send read receipt\n");
+                       testapp_print ("8.  Delete attachment\n");
+                       testapp_print ("9.  Mail Count \n");
+                       testapp_print ("10. Move mails to another account\n");
+                       testapp_print ("11. Send mail with downloading attachment of original mail\n");
+                       testapp_print ("14. Delete a mail \n");
+                       testapp_print ("16. Download mail body\n");
+                       testapp_print ("17. Download an attachment\n");
+                       testapp_print ("20. Delete all mail\n");
+                       testapp_print ("21. Move Mail \n");
+                       testapp_print ("23. Resend Mail \n");
+                       testapp_print ("27. Move all mails to mailbox\n");
+                       testapp_print ("38. Get total email disk usage \n");    
+                       testapp_print ("40. Verify Email Address Format\n");
+                       testapp_print ("41. Get Max Mail Count\n");
+                       testapp_print ("42. Storage test : (Input : to fields)\n");
+                       testapp_print ("43. Send mail Cancel\n");
+                       testapp_print ("44. Cancel Download Body\n");
+                       testapp_print ("46. Get thread list\n");
+                       testapp_print ("48. Get thread information\n");
+                       testapp_print ("51. Get mail list\n");
+                       testapp_print ("52. Get address info list\n");
+                       testapp_print ("55. Set a field of flags\n");
+                       testapp_print ("56. Add mail\n");
+                       testapp_print ("57. Update mail\n");
+                       testapp_print ("58. Search on server\n");
+                       testapp_print ("59. Add mail to search result table\n");
+                       testapp_print ("60. Parse mime file\n");
+                       testapp_print ("61. Write mime file\n");
+                       testapp_print ("0.  Go to Main Menu\n");
+                       testapp_print ("------------------------------------------\n");
+                       break;
+                       
+               case EMAIL_MAILBOX_MENU:
+                       testapp_print ("==========================================\n");
+                       testapp_print ("   MAILBOX MENU\n");
+                       testapp_print ("==========================================\n");
+                       testapp_print (" 1. Add mailbox\n");
+                       testapp_print (" 2. Delete mailbox\n");
+                       testapp_print (" 3. Raname mailbox\n");
+                       testapp_print (" 4. Get IMAP mailbox List\n");
+                       testapp_print (" 5. Set local mailbox\n");
+                       testapp_print (" 6. Delete mailbox ex\n");
+                       testapp_print (" 7. Get mailbox by mailbox type\n");
+                       testapp_print (" 8. Set mailbox type\n");
+                       testapp_print (" 9. Set mail slot size\n");
+                       testapp_print ("10. Get mailbox list\n");
+                       testapp_print ("11. Sync mailbox\n");
+                       testapp_print ("12. Stamp sync time\n");
+                       testapp_print ("0. Go to Main Menu\n");
+                       testapp_print ("------------------------------------------\n");
+                       break;
+                       
+               case EMAIL_RULE_MENU:
+                       testapp_print ("==========================================\n");
+                       testapp_print ("   RULE MENU\n");
+                       testapp_print ("==========================================\n");
+                       testapp_print ("1. Add Rule\n");
+                       testapp_print ("2. Delete Rule\n");
+                       testapp_print ("3. Update Rule\n");
+                       testapp_print ("5. Get Rule\n");
+                       testapp_print ("6. Get Rule List\n");
+                       testapp_print ("0. Go to Main Menu\n");
+                       testapp_print ("------------------------------------------\n");
+                       break;
+                       
+               case EMAIL_THREAD_MENU:
+                       testapp_print ("==========================================\n");
+                       testapp_print ("   TRHEAD MENU\n");
+                       testapp_print ("==========================================\n");
+                       testapp_print ("1. Move Thread\n");
+                       testapp_print ("2. Delete Thread\n");
+                       testapp_print ("3. Set Seen Flag of Thread\n");
+                       testapp_print ("0. Go to Main Menu\n");
+                       testapp_print ("------------------------------------------\n");
+                       break;
+                       
+               case EMAIL_OTHERS_MENU:
+                       testapp_print ("==========================================\n");
+                       testapp_print ("   OTHERS\n");
+                       testapp_print ("==========================================\n");
+                       testapp_print ("1.  Get Network Status\n");
+                       testapp_print ("2.  Get Pending Job\n");
+                       testapp_print ("3.  Cancel Job\n");
+                       testapp_print ("5.  Set DNET Proper Profile Type\n");
+                       testapp_print ("6.  Get DNET Proper Profile Type\n");
+                       testapp_print ("7.  Get preview text\n");
+                       testapp_print ("11. Print receiving event queue via debug msg\n");
+                       testapp_print ("12. Create DB full\n");
+                       testapp_print ("13. Encoding Test\n");
+                       testapp_print ("14. DTT Test\n");
+                       testapp_print ("15. Show User Message\n");
+                       testapp_print ("16. Get mime entity in signed file\n");
+                       testapp_print ("0.  Go to Main Menu\n");
+                       testapp_print ("------------------------------------------\n");
+                       break;
+                       
+               default:
+                       break;
+       }
+}
+void testapp_show_prompt (eEMAIL_MENU menu)
+{
+       switch (menu) {
+               case EMAIL_MAIN_MENU:
+                       testapp_print ("[MAIN]# ");
+                       break;
+                       
+               case EMAIL_ACCOUNT_MENU:
+                       testapp_print ("[ACCOUNT]# ");
+                       break;
+                       
+               case EMAIL_MAIL_MENU:
+                       testapp_print ("[MAIL]# ");
+                       break;
+                       
+               case EMAIL_MAILBOX_MENU:
+                       testapp_print ("[MAILBOX]# ");
+                       break;
+                       
+               case EMAIL_RULE_MENU:
+                       testapp_print ("[RULE]# ");
+                       break;
+                       
+               case EMAIL_THREAD_MENU:
+                       testapp_print ("[THREAD]# ");
+                       break;
+                       
+               case EMAIL_OTHERS_MENU:
+                       testapp_print ("[OTHERS]# ");
+                       break;
+                       
+               default:
+                       break;
+       }
+}
+
+