Browse Source

Applied AStyle code formating as discussed on tid:74602.
Removed /SAFESEH option from MSVC11 projects.

git-svn-id: https://svn.code.sf.net/p/rathena/svn/trunk@16968 54d463be-8e91-2dee-dedb-b68131a5f0ec

greenboxal2 12 years ago
parent
commit
a7c32653f7
100 changed files with 21624 additions and 21592 deletions
  1. 1056 1093
      src/char/char.c
  2. 9 10
      src/char/char.h
  3. 378 376
      src/char/int_auction.c
  4. 149 117
      src/char/int_elemental.c
  5. 649 649
      src/char/int_guild.c
  6. 13 13
      src/char/int_guild.h
  7. 240 229
      src/char/int_homun.c
  8. 2 2
      src/char/int_homun.h
  9. 373 348
      src/char/int_mail.c
  10. 2 2
      src/char/int_mail.h
  11. 138 128
      src/char/int_mercenary.c
  12. 570 569
      src/char/int_party.c
  13. 6 6
      src/char/int_party.h
  14. 266 239
      src/char/int_pet.c
  15. 122 128
      src/char/int_quest.c
  16. 183 169
      src/char/int_storage.c
  17. 1 1
      src/char/int_storage.h
  18. 715 693
      src/char/inter.c
  19. 2 2
      src/char/inter.h
  20. 77 62
      src/common/atomic.h
  21. 75 72
      src/common/cbasetypes.h
  22. 73 74
      src/common/conf.c
  23. 222 225
      src/common/core.c
  24. 14 15
      src/common/core.h
  25. 453 453
      src/common/db.c
  26. 400 401
      src/common/db.h
  27. 155 161
      src/common/des.c
  28. 7 5
      src/common/des.h
  29. 149 167
      src/common/ers.c
  30. 53 53
      src/common/ers.h
  31. 65 65
      src/common/evdp.h
  32. 183 173
      src/common/evdp_epoll.c
  33. 610 595
      src/common/grfio.c
  34. 7 7
      src/common/grfio.h
  35. 481 491
      src/common/malloc.c
  36. 29 29
      src/common/malloc.h
  37. 124 127
      src/common/mapindex.c
  38. 5 5
      src/common/mapindex.h
  39. 205 157
      src/common/md5calc.c
  40. 3 3
      src/common/md5calc.h
  41. 454 445
      src/common/mempool.c
  42. 31 31
      src/common/mempool.h
  43. 464 465
      src/common/mmo.h
  44. 133 123
      src/common/mutex.c
  45. 25 25
      src/common/mutex.h
  46. 183 166
      src/common/netbuffer.c
  47. 39 39
      src/common/netbuffer.h
  48. 909 900
      src/common/network.c
  49. 110 110
      src/common/network.h
  50. 47 49
      src/common/nullpo.c
  51. 15 15
      src/common/nullpo.h
  52. 524 513
      src/common/raconf.c
  53. 17 17
      src/common/raconf.h
  54. 18 18
      src/common/random.c
  55. 462 518
      src/common/showmsg.c
  56. 52 52
      src/common/showmsg.h
  57. 511 519
      src/common/socket.c
  58. 37 38
      src/common/socket.h
  59. 56 52
      src/common/spinlock.h
  60. 600 616
      src/common/sql.c
  61. 69 70
      src/common/sql.h
  62. 424 450
      src/common/strlib.c
  63. 58 61
      src/common/strlib.h
  64. 199 185
      src/common/thread.c
  65. 31 31
      src/common/thread.h
  66. 236 243
      src/common/timer.c
  67. 16 16
      src/common/timer.h
  68. 198 205
      src/common/utils.c
  69. 4 4
      src/common/utils.h
  70. 3 3
      src/common/winapi.h
  71. 37 37
      src/config/const.h
  72. 112 115
      src/login/account.h
  73. 543 580
      src/login/account_sql.c
  74. 1 1
      src/login/ipban.h
  75. 159 181
      src/login/ipban_sql.c
  76. 1080 1084
      src/login/login.c
  77. 61 62
      src/login/login.h
  78. 2 2
      src/login/loginlog.h
  79. 113 128
      src/login/loginlog_sql.c
  80. 505 498
      src/map/atcommand.c
  81. 14 14
      src/map/atcommand.h
  82. 781 783
      src/map/battle.c
  83. 424 425
      src/map/battle.h
  84. 164 165
      src/map/battleground.c
  85. 13 13
      src/map/battleground.h
  86. 398 406
      src/map/buyingstore.c
  87. 15 17
      src/map/buyingstore.h
  88. 280 290
      src/map/chat.c
  89. 25 25
      src/map/chat.h
  90. 480 452
      src/map/chrif.c
  91. 19 19
      src/map/chrif.h
  92. 442 444
      src/map/clif.c
  93. 413 415
      src/map/clif.h
  94. 33 33
      src/map/date.c
  95. 124 124
      src/map/duel.c
  96. 10 10
      src/map/duel.h
  97. 744 714
      src/map/elemental.c
  98. 28 28
      src/map/elemental.h
  99. 402 421
      src/map/guild.c
  100. 13 13
      src/map/guild.h

File diff suppressed because it is too large
+ 1056 - 1093
src/char/char.c


+ 9 - 10
src/char/char.h

@@ -6,11 +6,10 @@
 
 #include "../common/core.h" // CORE_ST_LAST
 
-enum E_CHARSERVER_ST
-{
-	CHARSERVER_ST_RUNNING = CORE_ST_LAST,
-	CHARSERVER_ST_SHUTDOWN,
-	CHARSERVER_ST_LAST
+enum E_CHARSERVER_ST {
+    CHARSERVER_ST_RUNNING = CORE_ST_LAST,
+    CHARSERVER_ST_SHUTDOWN,
+    CHARSERVER_ST_LAST
 };
 
 struct mmo_charstatus;
@@ -20,10 +19,10 @@ struct mmo_charstatus;
 #define DEFAULT_AUTOSAVE_INTERVAL 300*1000
 
 enum {
-	TABLE_INVENTORY,
-	TABLE_CART,
-	TABLE_STORAGE,
-	TABLE_GUILD_STORAGE,
+    TABLE_INVENTORY,
+    TABLE_CART,
+    TABLE_STORAGE,
+    TABLE_GUILD_STORAGE,
 };
 
 int memitemdata_to_sql(const struct item items[], int max, int id, int tableswitch);
@@ -37,7 +36,7 @@ int char_child(int parent_id, int child_id);
 int char_family(int pl1,int pl2,int pl3);
 
 int request_accreg2(int account_id, int char_id);
-int save_accreg2(unsigned char* buf, int len);
+int save_accreg2(unsigned char *buf, int len);
 
 extern int char_name_option;
 extern char char_name_letters[];

+ 378 - 376
src/char/int_auction.c

@@ -18,442 +18,435 @@
 #include <string.h>
 #include <stdlib.h>
 
-static DBMap* auction_db_ = NULL; // int auction_id -> struct auction_data*
+static DBMap *auction_db_ = NULL; // int auction_id -> struct auction_data*
 
 void auction_delete(struct auction_data *auction);
 static int auction_end_timer(int tid, unsigned int tick, int id, intptr_t data);
 
 static int auction_count(int char_id, bool buy)
 {
-	int i = 0;
-	struct auction_data *auction;
-	DBIterator *iter = db_iterator(auction_db_);
-
-	for( auction = dbi_first(iter); dbi_exists(iter); auction = dbi_next(iter) )
-	{
-		if( (buy && auction->buyer_id == char_id) || (!buy && auction->seller_id == char_id) )
-			i++;
-	}
-	dbi_destroy(iter);
-
-	return i;
+    int i = 0;
+    struct auction_data *auction;
+    DBIterator *iter = db_iterator(auction_db_);
+
+    for (auction = dbi_first(iter); dbi_exists(iter); auction = dbi_next(iter)) {
+        if ((buy && auction->buyer_id == char_id) || (!buy && auction->seller_id == char_id))
+            i++;
+    }
+    dbi_destroy(iter);
+
+    return i;
 }
 
 void auction_save(struct auction_data *auction)
 {
-	int j;
-	StringBuf buf;
-	SqlStmt* stmt;
-
-	if( !auction )
-		return;
-
-	StringBuf_Init(&buf);
-	StringBuf_Printf(&buf, "UPDATE `%s` SET `seller_id` = '%d', `seller_name` = ?, `buyer_id` = '%d', `buyer_name` = ?, `price` = '%d', `buynow` = '%d', `hours` = '%d', `timestamp` = '%lu', `nameid` = '%d', `item_name` = ?, `type` = '%d', `refine` = '%d', `attribute` = '%d'",
-		auction_db, auction->seller_id, auction->buyer_id, auction->price, auction->buynow, auction->hours, (unsigned long)auction->timestamp, auction->item.nameid, auction->type, auction->item.refine, auction->item.attribute);
-	for( j = 0; j < MAX_SLOTS; j++ )
-		StringBuf_Printf(&buf, ", `card%d` = '%d'", j, auction->item.card[j]);
-	StringBuf_Printf(&buf, " WHERE `auction_id` = '%d'", auction->auction_id);
-
-	stmt = SqlStmt_Malloc(sql_handle);
-	if( SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, auction->seller_name, strnlen(auction->seller_name, NAME_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, auction->buyer_name, strnlen(auction->buyer_name, NAME_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, auction->item_name, strnlen(auction->item_name, ITEM_NAME_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_Execute(stmt) )
-	{
-		SqlStmt_ShowDebug(stmt);
-	}
-
-	SqlStmt_Free(stmt);
-	StringBuf_Destroy(&buf);
+    int j;
+    StringBuf buf;
+    SqlStmt *stmt;
+
+    if (!auction)
+        return;
+
+    StringBuf_Init(&buf);
+    StringBuf_Printf(&buf, "UPDATE `%s` SET `seller_id` = '%d', `seller_name` = ?, `buyer_id` = '%d', `buyer_name` = ?, `price` = '%d', `buynow` = '%d', `hours` = '%d', `timestamp` = '%lu', `nameid` = '%d', `item_name` = ?, `type` = '%d', `refine` = '%d', `attribute` = '%d'",
+                     auction_db, auction->seller_id, auction->buyer_id, auction->price, auction->buynow, auction->hours, (unsigned long)auction->timestamp, auction->item.nameid, auction->type, auction->item.refine, auction->item.attribute);
+    for (j = 0; j < MAX_SLOTS; j++)
+        StringBuf_Printf(&buf, ", `card%d` = '%d'", j, auction->item.card[j]);
+    StringBuf_Printf(&buf, " WHERE `auction_id` = '%d'", auction->auction_id);
+
+    stmt = SqlStmt_Malloc(sql_handle);
+    if (SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, auction->seller_name, strnlen(auction->seller_name, NAME_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, auction->buyer_name, strnlen(auction->buyer_name, NAME_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, auction->item_name, strnlen(auction->item_name, ITEM_NAME_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_Execute(stmt)) {
+        SqlStmt_ShowDebug(stmt);
+    }
+
+    SqlStmt_Free(stmt);
+    StringBuf_Destroy(&buf);
 }
 
 unsigned int auction_create(struct auction_data *auction)
 {
-	int j;
-	StringBuf buf;
-	SqlStmt* stmt;
-
-	if( !auction )
-		return false;
-
-	auction->timestamp = time(NULL) + (auction->hours * 3600);
-
-	StringBuf_Init(&buf);
-	StringBuf_Printf(&buf, "INSERT INTO `%s` (`seller_id`,`seller_name`,`buyer_id`,`buyer_name`,`price`,`buynow`,`hours`,`timestamp`,`nameid`,`item_name`,`type`,`refine`,`attribute`", auction_db);
-	for( j = 0; j < MAX_SLOTS; j++ )
-		StringBuf_Printf(&buf, ",`card%d`", j);
-	StringBuf_Printf(&buf, ") VALUES ('%d',?,'%d',?,'%d','%d','%d','%lu','%d',?,'%d','%d','%d'",
-		auction->seller_id, auction->buyer_id, auction->price, auction->buynow, auction->hours, (unsigned long)auction->timestamp, auction->item.nameid, auction->type, auction->item.refine, auction->item.attribute);
-	for( j = 0; j < MAX_SLOTS; j++ )
-		StringBuf_Printf(&buf, ",'%d'", auction->item.card[j]);
-	StringBuf_AppendStr(&buf, ")");
-	
-	stmt = SqlStmt_Malloc(sql_handle);
-	if( SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, auction->seller_name, strnlen(auction->seller_name, NAME_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, auction->buyer_name, strnlen(auction->buyer_name, NAME_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, auction->item_name, strnlen(auction->item_name, ITEM_NAME_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_Execute(stmt) )
-	{
-		SqlStmt_ShowDebug(stmt);
-		auction->auction_id = 0;
-	}
-	else
-	{
-		struct auction_data *auction_;
-		unsigned int tick = auction->hours * 3600000;
-
-		auction->item.amount = 1;
-		auction->item.identify = 1;
-		auction->item.expire_time = 0;
-
-		auction->auction_id = (unsigned int)SqlStmt_LastInsertId(stmt);
-		auction->auction_end_timer = add_timer( gettick() + tick , auction_end_timer, auction->auction_id, 0);
-		ShowInfo("New Auction %u | time left %u ms | By %s.\n", auction->auction_id, tick, auction->seller_name);
-
-		CREATE(auction_, struct auction_data, 1);
-		memcpy(auction_, auction, sizeof(struct auction_data));
-		idb_put(auction_db_, auction_->auction_id, auction_);
-	}
-
-	SqlStmt_Free(stmt);
-	StringBuf_Destroy(&buf);
-
-	return auction->auction_id;
+    int j;
+    StringBuf buf;
+    SqlStmt *stmt;
+
+    if (!auction)
+        return false;
+
+    auction->timestamp = time(NULL) + (auction->hours * 3600);
+
+    StringBuf_Init(&buf);
+    StringBuf_Printf(&buf, "INSERT INTO `%s` (`seller_id`,`seller_name`,`buyer_id`,`buyer_name`,`price`,`buynow`,`hours`,`timestamp`,`nameid`,`item_name`,`type`,`refine`,`attribute`", auction_db);
+    for (j = 0; j < MAX_SLOTS; j++)
+        StringBuf_Printf(&buf, ",`card%d`", j);
+    StringBuf_Printf(&buf, ") VALUES ('%d',?,'%d',?,'%d','%d','%d','%lu','%d',?,'%d','%d','%d'",
+                     auction->seller_id, auction->buyer_id, auction->price, auction->buynow, auction->hours, (unsigned long)auction->timestamp, auction->item.nameid, auction->type, auction->item.refine, auction->item.attribute);
+    for (j = 0; j < MAX_SLOTS; j++)
+        StringBuf_Printf(&buf, ",'%d'", auction->item.card[j]);
+    StringBuf_AppendStr(&buf, ")");
+
+    stmt = SqlStmt_Malloc(sql_handle);
+    if (SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, auction->seller_name, strnlen(auction->seller_name, NAME_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, auction->buyer_name, strnlen(auction->buyer_name, NAME_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, auction->item_name, strnlen(auction->item_name, ITEM_NAME_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_Execute(stmt)) {
+        SqlStmt_ShowDebug(stmt);
+        auction->auction_id = 0;
+    } else {
+        struct auction_data *auction_;
+        unsigned int tick = auction->hours * 3600000;
+
+        auction->item.amount = 1;
+        auction->item.identify = 1;
+        auction->item.expire_time = 0;
+
+        auction->auction_id = (unsigned int)SqlStmt_LastInsertId(stmt);
+        auction->auction_end_timer = add_timer(gettick() + tick , auction_end_timer, auction->auction_id, 0);
+        ShowInfo("New Auction %u | time left %u ms | By %s.\n", auction->auction_id, tick, auction->seller_name);
+
+        CREATE(auction_, struct auction_data, 1);
+        memcpy(auction_, auction, sizeof(struct auction_data));
+        idb_put(auction_db_, auction_->auction_id, auction_);
+    }
+
+    SqlStmt_Free(stmt);
+    StringBuf_Destroy(&buf);
+
+    return auction->auction_id;
 }
 
 static void mapif_Auction_message(int char_id, unsigned char result)
 {
-	unsigned char buf[74];
-	
-	WBUFW(buf,0) = 0x3854;
-	WBUFL(buf,2) = char_id;
-	WBUFL(buf,6) = result;
-	mapif_sendall(buf,7);
+    unsigned char buf[74];
+
+    WBUFW(buf,0) = 0x3854;
+    WBUFL(buf,2) = char_id;
+    WBUFL(buf,6) = result;
+    mapif_sendall(buf,7);
 }
 
 static int auction_end_timer(int tid, unsigned int tick, int id, intptr_t data)
 {
-	struct auction_data *auction;
-	if( (auction = (struct auction_data *)idb_get(auction_db_, id)) != NULL )
-	{
-		if( auction->buyer_id )
-		{
-			mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Thanks, you won the auction!.", 0, &auction->item);
-			mapif_Auction_message(auction->buyer_id, 6); // You have won the auction
-			mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Payment for your auction!.", auction->price, NULL);
-		}
-		else
-			mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "No buyers have been found for your auction.", 0, &auction->item);
-		
-		ShowInfo("Auction End: id %u.\n", auction->auction_id);
-
-		auction->auction_end_timer = INVALID_TIMER;
-		auction_delete(auction);
-	}
-
-	return 0;
+    struct auction_data *auction;
+    if ((auction = (struct auction_data *)idb_get(auction_db_, id)) != NULL) {
+        if (auction->buyer_id) {
+            mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Thanks, you won the auction!.", 0, &auction->item);
+            mapif_Auction_message(auction->buyer_id, 6); // You have won the auction
+            mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Payment for your auction!.", auction->price, NULL);
+        } else
+            mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "No buyers have been found for your auction.", 0, &auction->item);
+
+        ShowInfo("Auction End: id %u.\n", auction->auction_id);
+
+        auction->auction_end_timer = INVALID_TIMER;
+        auction_delete(auction);
+    }
+
+    return 0;
 }
 
 void auction_delete(struct auction_data *auction)
 {
-	unsigned int auction_id = auction->auction_id;
+    unsigned int auction_id = auction->auction_id;
 
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `auction_id` = '%d'", auction_db, auction_id) )
-		Sql_ShowDebug(sql_handle);
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `auction_id` = '%d'", auction_db, auction_id))
+        Sql_ShowDebug(sql_handle);
 
-	if( auction->auction_end_timer != INVALID_TIMER )
-		delete_timer(auction->auction_end_timer, auction_end_timer);
+    if (auction->auction_end_timer != INVALID_TIMER)
+        delete_timer(auction->auction_end_timer, auction_end_timer);
 
-	idb_remove(auction_db_, auction_id);
+    idb_remove(auction_db_, auction_id);
 }
 
 void inter_auctions_fromsql(void)
 {
-	int i;
-	struct auction_data *auction;
-	struct item *item;
-	char *data;
-	StringBuf buf;
-	unsigned int tick = gettick(), endtick;
-	time_t now = time(NULL);
-
-	StringBuf_Init(&buf);
-	StringBuf_AppendStr(&buf, "SELECT `auction_id`,`seller_id`,`seller_name`,`buyer_id`,`buyer_name`,"
-		"`price`,`buynow`,`hours`,`timestamp`,`nameid`,`item_name`,`type`,`refine`,`attribute`");
-	for( i = 0; i < MAX_SLOTS; i++ )
-		StringBuf_Printf(&buf, ",`card%d`", i);
-	StringBuf_Printf(&buf, " FROM `%s` ORDER BY `auction_id` DESC", auction_db);
-
-	if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) )
-		Sql_ShowDebug(sql_handle);
-
-	StringBuf_Destroy(&buf);
-
-	while( SQL_SUCCESS == Sql_NextRow(sql_handle) )
-	{
-		CREATE(auction, struct auction_data, 1);
-		Sql_GetData(sql_handle, 0, &data, NULL); auction->auction_id = atoi(data);
-		Sql_GetData(sql_handle, 1, &data, NULL); auction->seller_id = atoi(data);
-		Sql_GetData(sql_handle, 2, &data, NULL); safestrncpy(auction->seller_name, data, NAME_LENGTH);
-		Sql_GetData(sql_handle, 3, &data, NULL); auction->buyer_id = atoi(data);
-		Sql_GetData(sql_handle, 4, &data, NULL); safestrncpy(auction->buyer_name, data, NAME_LENGTH);
-		Sql_GetData(sql_handle, 5, &data, NULL); auction->price	= atoi(data);
-		Sql_GetData(sql_handle, 6, &data, NULL); auction->buynow = atoi(data);
-		Sql_GetData(sql_handle, 7, &data, NULL); auction->hours = atoi(data);
-		Sql_GetData(sql_handle, 8, &data, NULL); auction->timestamp = atoi(data);
-
-		item = &auction->item;
-		Sql_GetData(sql_handle, 9, &data, NULL); item->nameid = atoi(data);
-		Sql_GetData(sql_handle,10, &data, NULL); safestrncpy(auction->item_name, data, ITEM_NAME_LENGTH);
-		Sql_GetData(sql_handle,11, &data, NULL); auction->type = atoi(data);
-
-		Sql_GetData(sql_handle,12, &data, NULL); item->refine = atoi(data);
-		Sql_GetData(sql_handle,13, &data, NULL); item->attribute = atoi(data);
-
-		item->identify = 1;
-		item->amount = 1;
-		item->expire_time = 0;
-
-		for( i = 0; i < MAX_SLOTS; i++ )
-		{
-			Sql_GetData(sql_handle, 14 + i, &data, NULL);
-			item->card[i] = atoi(data);
-		}
-
-		if( auction->timestamp > now )
-			endtick = ((unsigned int)(auction->timestamp - now) * 1000) + tick;
-		else
-			endtick = tick + 10000; // 10 Second's to process ended auctions
-
-		auction->auction_end_timer = add_timer(endtick, auction_end_timer, auction->auction_id, 0);
-		idb_put(auction_db_, auction->auction_id, auction);
-	}
-
-	Sql_FreeResult(sql_handle);
+    int i;
+    struct auction_data *auction;
+    struct item *item;
+    char *data;
+    StringBuf buf;
+    unsigned int tick = gettick(), endtick;
+    time_t now = time(NULL);
+
+    StringBuf_Init(&buf);
+    StringBuf_AppendStr(&buf, "SELECT `auction_id`,`seller_id`,`seller_name`,`buyer_id`,`buyer_name`,"
+                        "`price`,`buynow`,`hours`,`timestamp`,`nameid`,`item_name`,`type`,`refine`,`attribute`");
+    for (i = 0; i < MAX_SLOTS; i++)
+        StringBuf_Printf(&buf, ",`card%d`", i);
+    StringBuf_Printf(&buf, " FROM `%s` ORDER BY `auction_id` DESC", auction_db);
+
+    if (SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)))
+        Sql_ShowDebug(sql_handle);
+
+    StringBuf_Destroy(&buf);
+
+    while (SQL_SUCCESS == Sql_NextRow(sql_handle)) {
+        CREATE(auction, struct auction_data, 1);
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        auction->auction_id = atoi(data);
+        Sql_GetData(sql_handle, 1, &data, NULL);
+        auction->seller_id = atoi(data);
+        Sql_GetData(sql_handle, 2, &data, NULL);
+        safestrncpy(auction->seller_name, data, NAME_LENGTH);
+        Sql_GetData(sql_handle, 3, &data, NULL);
+        auction->buyer_id = atoi(data);
+        Sql_GetData(sql_handle, 4, &data, NULL);
+        safestrncpy(auction->buyer_name, data, NAME_LENGTH);
+        Sql_GetData(sql_handle, 5, &data, NULL);
+        auction->price = atoi(data);
+        Sql_GetData(sql_handle, 6, &data, NULL);
+        auction->buynow = atoi(data);
+        Sql_GetData(sql_handle, 7, &data, NULL);
+        auction->hours = atoi(data);
+        Sql_GetData(sql_handle, 8, &data, NULL);
+        auction->timestamp = atoi(data);
+
+        item = &auction->item;
+        Sql_GetData(sql_handle, 9, &data, NULL);
+        item->nameid = atoi(data);
+        Sql_GetData(sql_handle,10, &data, NULL);
+        safestrncpy(auction->item_name, data, ITEM_NAME_LENGTH);
+        Sql_GetData(sql_handle,11, &data, NULL);
+        auction->type = atoi(data);
+
+        Sql_GetData(sql_handle,12, &data, NULL);
+        item->refine = atoi(data);
+        Sql_GetData(sql_handle,13, &data, NULL);
+        item->attribute = atoi(data);
+
+        item->identify = 1;
+        item->amount = 1;
+        item->expire_time = 0;
+
+        for (i = 0; i < MAX_SLOTS; i++) {
+            Sql_GetData(sql_handle, 14 + i, &data, NULL);
+            item->card[i] = atoi(data);
+        }
+
+        if (auction->timestamp > now)
+            endtick = ((unsigned int)(auction->timestamp - now) * 1000) + tick;
+        else
+            endtick = tick + 10000; // 10 Second's to process ended auctions
+
+        auction->auction_end_timer = add_timer(endtick, auction_end_timer, auction->auction_id, 0);
+        idb_put(auction_db_, auction->auction_id, auction);
+    }
+
+    Sql_FreeResult(sql_handle);
 }
 
 static void mapif_Auction_sendlist(int fd, int char_id, short count, short pages, unsigned char *buf)
 {
-	int len = (sizeof(struct auction_data) * count) + 12;
-
-	WFIFOHEAD(fd, len);
-	WFIFOW(fd,0) = 0x3850;
-	WFIFOW(fd,2) = len;
-	WFIFOL(fd,4) = char_id;
-	WFIFOW(fd,8) = count;
-	WFIFOW(fd,10) = pages;
-	memcpy(WFIFOP(fd,12), buf, len - 12);
-	WFIFOSET(fd,len);
+    int len = (sizeof(struct auction_data) * count) + 12;
+
+    WFIFOHEAD(fd, len);
+    WFIFOW(fd,0) = 0x3850;
+    WFIFOW(fd,2) = len;
+    WFIFOL(fd,4) = char_id;
+    WFIFOW(fd,8) = count;
+    WFIFOW(fd,10) = pages;
+    memcpy(WFIFOP(fd,12), buf, len - 12);
+    WFIFOSET(fd,len);
 }
 
 static void mapif_parse_Auction_requestlist(int fd)
 {
-	char searchtext[NAME_LENGTH];
-	int char_id = RFIFOL(fd,4), len = sizeof(struct auction_data);
-	int price = RFIFOL(fd,10);
-	short type = RFIFOW(fd,8), page = max(1,RFIFOW(fd,14));
-	unsigned char buf[5 * sizeof(struct auction_data)];
-	DBIterator *iter = db_iterator(auction_db_);
-	struct auction_data *auction;
-	short i = 0, j = 0, pages = 1;
-
-	memcpy(searchtext, RFIFOP(fd,16), NAME_LENGTH);
-
-	for( auction = dbi_first(iter); dbi_exists(iter); auction = dbi_next(iter) )
-	{
-		if( (type == 0 && auction->type != IT_ARMOR && auction->type != IT_PETARMOR) || 
-			(type == 1 && auction->type != IT_WEAPON) ||
-			(type == 2 && auction->type != IT_CARD) ||
-			(type == 3 && auction->type != IT_ETC) ||
-			(type == 4 && !strstr(auction->item_name, searchtext)) ||
-			(type == 5 && auction->price > price) ||
-			(type == 6 && auction->seller_id != char_id) ||
-			(type == 7 && auction->buyer_id != char_id) )
-			continue;
-
-		i++;
-		if( i > 5 )
-		{ // Counting Pages of Total Results (5 Results per Page)
-			pages++;
-			i = 1; // First Result of This Page
-		}
-
-		if( page != pages )
-			continue; // This is not the requested Page
-
-		memcpy(WBUFP(buf, j * len), auction, len);
-		j++; // Found Results
-	}
-	dbi_destroy(iter);
-
-	mapif_Auction_sendlist(fd, char_id, j, pages, buf);
+    char searchtext[NAME_LENGTH];
+    int char_id = RFIFOL(fd,4), len = sizeof(struct auction_data);
+    int price = RFIFOL(fd,10);
+    short type = RFIFOW(fd,8), page = max(1,RFIFOW(fd,14));
+    unsigned char buf[5 * sizeof(struct auction_data)];
+    DBIterator *iter = db_iterator(auction_db_);
+    struct auction_data *auction;
+    short i = 0, j = 0, pages = 1;
+
+    memcpy(searchtext, RFIFOP(fd,16), NAME_LENGTH);
+
+    for (auction = dbi_first(iter); dbi_exists(iter); auction = dbi_next(iter)) {
+        if ((type == 0 && auction->type != IT_ARMOR && auction->type != IT_PETARMOR) ||
+            (type == 1 && auction->type != IT_WEAPON) ||
+            (type == 2 && auction->type != IT_CARD) ||
+            (type == 3 && auction->type != IT_ETC) ||
+            (type == 4 && !strstr(auction->item_name, searchtext)) ||
+            (type == 5 && auction->price > price) ||
+            (type == 6 && auction->seller_id != char_id) ||
+            (type == 7 && auction->buyer_id != char_id))
+            continue;
+
+        i++;
+        if (i > 5) {
+            // Counting Pages of Total Results (5 Results per Page)
+            pages++;
+            i = 1; // First Result of This Page
+        }
+
+        if (page != pages)
+            continue; // This is not the requested Page
+
+        memcpy(WBUFP(buf, j * len), auction, len);
+        j++; // Found Results
+    }
+    dbi_destroy(iter);
+
+    mapif_Auction_sendlist(fd, char_id, j, pages, buf);
 }
 
 static void mapif_Auction_register(int fd, struct auction_data *auction)
 {
-	int len = sizeof(struct auction_data) + 4;
+    int len = sizeof(struct auction_data) + 4;
 
-	WFIFOHEAD(fd,len);
-	WFIFOW(fd,0) = 0x3851;
-	WFIFOW(fd,2) = len;
-	memcpy(WFIFOP(fd,4), auction, sizeof(struct auction_data));
-	WFIFOSET(fd,len);
+    WFIFOHEAD(fd,len);
+    WFIFOW(fd,0) = 0x3851;
+    WFIFOW(fd,2) = len;
+    memcpy(WFIFOP(fd,4), auction, sizeof(struct auction_data));
+    WFIFOSET(fd,len);
 }
 
 static void mapif_parse_Auction_register(int fd)
 {
-	struct auction_data auction;
-	if( RFIFOW(fd,2) != sizeof(struct auction_data) + 4 )
-		return;
+    struct auction_data auction;
+    if (RFIFOW(fd,2) != sizeof(struct auction_data) + 4)
+        return;
 
-	memcpy(&auction, RFIFOP(fd,4), sizeof(struct auction_data));
-	if( auction_count(auction.seller_id, false) < 5 )
-		auction.auction_id = auction_create(&auction);
+    memcpy(&auction, RFIFOP(fd,4), sizeof(struct auction_data));
+    if (auction_count(auction.seller_id, false) < 5)
+        auction.auction_id = auction_create(&auction);
 
-	mapif_Auction_register(fd, &auction);
+    mapif_Auction_register(fd, &auction);
 }
 
 static void mapif_Auction_cancel(int fd, int char_id, unsigned char result)
 {
-	WFIFOHEAD(fd,7);
-	WFIFOW(fd,0) = 0x3852;
-	WFIFOL(fd,2) = char_id;
-	WFIFOB(fd,6) = result;
-	WFIFOSET(fd,7);
+    WFIFOHEAD(fd,7);
+    WFIFOW(fd,0) = 0x3852;
+    WFIFOL(fd,2) = char_id;
+    WFIFOB(fd,6) = result;
+    WFIFOSET(fd,7);
 }
 
 static void mapif_parse_Auction_cancel(int fd)
 {
-	int char_id = RFIFOL(fd,2), auction_id = RFIFOL(fd,6);
-	struct auction_data *auction;
-
-	if( (auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL )
-	{
-		mapif_Auction_cancel(fd, char_id, 1); // Bid Number is Incorrect
-		return;
-	}
-
-	if( auction->seller_id != char_id )
-	{
-		mapif_Auction_cancel(fd, char_id, 2); // You cannot end the auction
-		return;
-	}
-
-	if( auction->buyer_id > 0 )
-	{
-		mapif_Auction_cancel(fd, char_id, 3); // An auction with at least one bidder cannot be canceled
-		return;
-	}
-
-	mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Auction canceled.", 0, &auction->item);
-	auction_delete(auction);
-
-	mapif_Auction_cancel(fd, char_id, 0); // The auction has been canceled
+    int char_id = RFIFOL(fd,2), auction_id = RFIFOL(fd,6);
+    struct auction_data *auction;
+
+    if ((auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL) {
+        mapif_Auction_cancel(fd, char_id, 1); // Bid Number is Incorrect
+        return;
+    }
+
+    if (auction->seller_id != char_id) {
+        mapif_Auction_cancel(fd, char_id, 2); // You cannot end the auction
+        return;
+    }
+
+    if (auction->buyer_id > 0) {
+        mapif_Auction_cancel(fd, char_id, 3); // An auction with at least one bidder cannot be canceled
+        return;
+    }
+
+    mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Auction canceled.", 0, &auction->item);
+    auction_delete(auction);
+
+    mapif_Auction_cancel(fd, char_id, 0); // The auction has been canceled
 }
 
 static void mapif_Auction_close(int fd, int char_id, unsigned char result)
 {
-	WFIFOHEAD(fd,7);
-	WFIFOW(fd,0) = 0x3853;
-	WFIFOL(fd,2) = char_id;
-	WFIFOB(fd,6) = result;
-	WFIFOSET(fd,7);
+    WFIFOHEAD(fd,7);
+    WFIFOW(fd,0) = 0x3853;
+    WFIFOL(fd,2) = char_id;
+    WFIFOB(fd,6) = result;
+    WFIFOSET(fd,7);
 }
 
 static void mapif_parse_Auction_close(int fd)
 {
-	int char_id = RFIFOL(fd,2), auction_id = RFIFOL(fd,6);
-	struct auction_data *auction;
-
-	if( (auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL )
-	{
-		mapif_Auction_close(fd, char_id, 2); // Bid Number is Incorrect
-		return;
-	}
-
-	if( auction->seller_id != char_id )
-	{
-		mapif_Auction_close(fd, char_id, 1); // You cannot end the auction
-		return;
-	}
-
-	if( auction->buyer_id == 0 )
-	{
-		mapif_Auction_close(fd, char_id, 1); // You cannot end the auction
-		return;
-	}
-
-	// Send Money to Seller
-	mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Auction closed.", auction->price, NULL);
-	// Send Item to Buyer
-	mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Auction winner.", 0, &auction->item);
-	mapif_Auction_message(auction->buyer_id, 6); // You have won the auction
-	auction_delete(auction);
-
-	mapif_Auction_close(fd, char_id, 0); // You have ended the auction
+    int char_id = RFIFOL(fd,2), auction_id = RFIFOL(fd,6);
+    struct auction_data *auction;
+
+    if ((auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL) {
+        mapif_Auction_close(fd, char_id, 2); // Bid Number is Incorrect
+        return;
+    }
+
+    if (auction->seller_id != char_id) {
+        mapif_Auction_close(fd, char_id, 1); // You cannot end the auction
+        return;
+    }
+
+    if (auction->buyer_id == 0) {
+        mapif_Auction_close(fd, char_id, 1); // You cannot end the auction
+        return;
+    }
+
+    // Send Money to Seller
+    mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Auction closed.", auction->price, NULL);
+    // Send Item to Buyer
+    mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Auction winner.", 0, &auction->item);
+    mapif_Auction_message(auction->buyer_id, 6); // You have won the auction
+    auction_delete(auction);
+
+    mapif_Auction_close(fd, char_id, 0); // You have ended the auction
 }
 
 static void mapif_Auction_bid(int fd, int char_id, int bid, unsigned char result)
 {
-	WFIFOHEAD(fd,11);
-	WFIFOW(fd,0) = 0x3855;
-	WFIFOL(fd,2) = char_id;
-	WFIFOL(fd,6) = bid; // To Return Zeny
-	WFIFOB(fd,10) = result;
-	WFIFOSET(fd,11);
+    WFIFOHEAD(fd,11);
+    WFIFOW(fd,0) = 0x3855;
+    WFIFOL(fd,2) = char_id;
+    WFIFOL(fd,6) = bid; // To Return Zeny
+    WFIFOB(fd,10) = result;
+    WFIFOSET(fd,11);
 }
 
 static void mapif_parse_Auction_bid(int fd)
 {
-	int char_id = RFIFOL(fd,4), bid = RFIFOL(fd,12);
-	unsigned int auction_id = RFIFOL(fd,8);
-	struct auction_data *auction;
-
-	if( (auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL || auction->price >= bid || auction->seller_id == char_id )
-	{
-		mapif_Auction_bid(fd, char_id, bid, 0); // You have failed to bid in the auction
-		return;
-	}
-
-	if( auction_count(char_id, true) > 4 && bid < auction->buynow && auction->buyer_id != char_id )
-	{
-		mapif_Auction_bid(fd, char_id, bid, 9); // You cannot place more than 5 bids at a time
-		return;
-	}
-
-	if( auction->buyer_id > 0 )
-	{ // Send Money back to the previous Buyer
-		if( auction->buyer_id != char_id )
-		{
-			mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Someone has placed a higher bid.", auction->price, NULL);
-			mapif_Auction_message(auction->buyer_id, 7); // You have failed to win the auction
-		}
-		else
-			mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "You have placed a higher bid.", auction->price, NULL);
-	}
-
-	auction->buyer_id = char_id;
-	safestrncpy(auction->buyer_name, (char*)RFIFOP(fd,16), NAME_LENGTH);
-	auction->price = bid;
-
-	if( bid >= auction->buynow )
-	{ // Automatic won the auction
-		mapif_Auction_bid(fd, char_id, bid - auction->buynow, 1); // You have successfully bid in the auction
-
-		mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "You have won the auction.", 0, &auction->item);
-		mapif_Auction_message(char_id, 6); // You have won the auction
-		mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Payment for your auction!.", auction->buynow, NULL);
-
-		auction_delete(auction);
-		return;
-	}
-
-	auction_save(auction);
-
-	mapif_Auction_bid(fd, char_id, 0, 1); // You have successfully bid in the auction
+    int char_id = RFIFOL(fd,4), bid = RFIFOL(fd,12);
+    unsigned int auction_id = RFIFOL(fd,8);
+    struct auction_data *auction;
+
+    if ((auction = (struct auction_data *)idb_get(auction_db_, auction_id)) == NULL || auction->price >= bid || auction->seller_id == char_id) {
+        mapif_Auction_bid(fd, char_id, bid, 0); // You have failed to bid in the auction
+        return;
+    }
+
+    if (auction_count(char_id, true) > 4 && bid < auction->buynow && auction->buyer_id != char_id) {
+        mapif_Auction_bid(fd, char_id, bid, 9); // You cannot place more than 5 bids at a time
+        return;
+    }
+
+    if (auction->buyer_id > 0) {
+        // Send Money back to the previous Buyer
+        if (auction->buyer_id != char_id) {
+            mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "Someone has placed a higher bid.", auction->price, NULL);
+            mapif_Auction_message(auction->buyer_id, 7); // You have failed to win the auction
+        } else
+            mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "You have placed a higher bid.", auction->price, NULL);
+    }
+
+    auction->buyer_id = char_id;
+    safestrncpy(auction->buyer_name, (char *)RFIFOP(fd,16), NAME_LENGTH);
+    auction->price = bid;
+
+    if (bid >= auction->buynow) {
+        // Automatic won the auction
+        mapif_Auction_bid(fd, char_id, bid - auction->buynow, 1); // You have successfully bid in the auction
+
+        mail_sendmail(0, "Auction Manager", auction->buyer_id, auction->buyer_name, "Auction", "You have won the auction.", 0, &auction->item);
+        mapif_Auction_message(char_id, 6); // You have won the auction
+        mail_sendmail(0, "Auction Manager", auction->seller_id, auction->seller_name, "Auction", "Payment for your auction!.", auction->buynow, NULL);
+
+        auction_delete(auction);
+        return;
+    }
+
+    auction_save(auction);
+
+    mapif_Auction_bid(fd, char_id, 0, 1); // You have successfully bid in the auction
 }
 
 /*==========================================
@@ -461,30 +454,39 @@ static void mapif_parse_Auction_bid(int fd)
  *------------------------------------------*/
 int inter_auction_parse_frommap(int fd)
 {
-	switch(RFIFOW(fd,0))
-	{
-		case 0x3050: mapif_parse_Auction_requestlist(fd); break;
-		case 0x3051: mapif_parse_Auction_register(fd); break;
-		case 0x3052: mapif_parse_Auction_cancel(fd); break;
-		case 0x3053: mapif_parse_Auction_close(fd); break;
-		case 0x3055: mapif_parse_Auction_bid(fd); break;
-		default:
-			return 0;
-	}
-	return 1;
+    switch (RFIFOW(fd,0)) {
+        case 0x3050:
+            mapif_parse_Auction_requestlist(fd);
+            break;
+        case 0x3051:
+            mapif_parse_Auction_register(fd);
+            break;
+        case 0x3052:
+            mapif_parse_Auction_cancel(fd);
+            break;
+        case 0x3053:
+            mapif_parse_Auction_close(fd);
+            break;
+        case 0x3055:
+            mapif_parse_Auction_bid(fd);
+            break;
+        default:
+            return 0;
+    }
+    return 1;
 }
 
 int inter_auction_sql_init(void)
 {
-	auction_db_ = idb_alloc(DB_OPT_RELEASE_DATA);
-	inter_auctions_fromsql();
+    auction_db_ = idb_alloc(DB_OPT_RELEASE_DATA);
+    inter_auctions_fromsql();
 
-	return 0;
+    return 0;
 }
 
 void inter_auction_sql_final(void)
 {
-	auction_db_->destroy(auction_db_,NULL);
+    auction_db_->destroy(auction_db_,NULL);
 
-	return;
+    return;
 }

+ 149 - 117
src/char/int_elemental.c

@@ -15,147 +15,179 @@
 #include <stdlib.h>
 #include <string.h>
 
-bool mapif_elemental_save(struct s_elemental* ele) {
-	bool flag = true;
-	
-	if( ele->elemental_id == 0 ) { // Create new DB entry
-		if( SQL_ERROR == Sql_Query(sql_handle,
-								   "INSERT INTO `elemental` (`char_id`,`class`,`mode`,`hp`,`sp`,`max_hp`,`max_sp`,`str`,`agi`,`vit`,`int`,`dex`,`luk`,`life_time`)"
-								   "VALUES ('%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%u')",
-								   ele->char_id, ele->class_, ele->mode, ele->hp, ele->sp, ele->max_hp, ele->max_sp, ele->str, ele->agi, ele->vit, ele->int_, ele->dex, ele->luk, ele->life_time) )
-		{
-			Sql_ShowDebug(sql_handle);
-			flag = false;
-		}
-		else
-			ele->elemental_id = (int)Sql_LastInsertId(sql_handle);
-	} else if( SQL_ERROR == Sql_Query(sql_handle,
-									"UPDATE `elemental` SET `char_id` = '%d', `class` = '%d', `mode` = '%d', `hp` = '%d', `sp` = '%d',"
-									"`max_hp` = '%d', `max_sp` = '%d', `str` = '%d', `agi` = '%d', `vit` = '%d', `int` = '%d', `dex` = '%d',"
-									"`luk` = '%d', `life_time` = '%u' WHERE `ele_id` = '%d'",
-									ele->char_id, ele->class_, ele->mode, ele->hp, ele->sp, ele->max_hp, ele->max_sp, ele->str, ele->agi,
-									ele->vit, ele->int_, ele->dex, ele->luk, ele->life_time, ele->elemental_id) )
-	{ // Update DB entry
-		Sql_ShowDebug(sql_handle);
-		flag = false;
-	}
-	return flag;
+bool mapif_elemental_save(struct s_elemental *ele)
+{
+    bool flag = true;
+
+    if (ele->elemental_id == 0) {  // Create new DB entry
+        if (SQL_ERROR == Sql_Query(sql_handle,
+                                   "INSERT INTO `elemental` (`char_id`,`class`,`mode`,`hp`,`sp`,`max_hp`,`max_sp`,`str`,`agi`,`vit`,`int`,`dex`,`luk`,`life_time`)"
+                                   "VALUES ('%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%d','%u')",
+                                   ele->char_id, ele->class_, ele->mode, ele->hp, ele->sp, ele->max_hp, ele->max_sp, ele->str, ele->agi, ele->vit, ele->int_, ele->dex, ele->luk, ele->life_time)) {
+            Sql_ShowDebug(sql_handle);
+            flag = false;
+        } else
+            ele->elemental_id = (int)Sql_LastInsertId(sql_handle);
+    } else if (SQL_ERROR == Sql_Query(sql_handle,
+                                      "UPDATE `elemental` SET `char_id` = '%d', `class` = '%d', `mode` = '%d', `hp` = '%d', `sp` = '%d',"
+                                      "`max_hp` = '%d', `max_sp` = '%d', `str` = '%d', `agi` = '%d', `vit` = '%d', `int` = '%d', `dex` = '%d',"
+                                      "`luk` = '%d', `life_time` = '%u' WHERE `ele_id` = '%d'",
+                                      ele->char_id, ele->class_, ele->mode, ele->hp, ele->sp, ele->max_hp, ele->max_sp, ele->str, ele->agi,
+                                      ele->vit, ele->int_, ele->dex, ele->luk, ele->life_time, ele->elemental_id)) {
+        // Update DB entry
+        Sql_ShowDebug(sql_handle);
+        flag = false;
+    }
+    return flag;
 }
 
-bool mapif_elemental_load(int ele_id, int char_id, struct s_elemental *ele) {
-	char* data;
-	
-	memset(ele, 0, sizeof(struct s_elemental));
-	ele->elemental_id = ele_id;
-	ele->char_id = char_id;
-	
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `class`, `mode`, `hp`, `sp`, `max_hp`, `max_sp`, `str`, `agi`, `vit`, `int`, `dex`,"
-							   "`luk`, `life_time` FROM `elemental` WHERE `ele_id` = '%d' AND `char_id` = '%d'",
-							   ele_id, char_id) ) {
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-	
-	if( SQL_SUCCESS != Sql_NextRow(sql_handle) ) {
-		Sql_FreeResult(sql_handle);
-		return false;
-	}
-	
-	Sql_GetData(sql_handle,  0, &data, NULL); ele->class_ = atoi(data);
-	Sql_GetData(sql_handle,  1, &data, NULL); ele->mode = atoi(data);
-	Sql_GetData(sql_handle,  2, &data, NULL); ele->hp = atoi(data);
-	Sql_GetData(sql_handle,  3, &data, NULL); ele->sp = atoi(data);
-	Sql_GetData(sql_handle,  4, &data, NULL); ele->max_hp = atoi(data);
-	Sql_GetData(sql_handle,  5, &data, NULL); ele->max_sp = atoi(data);
-	Sql_GetData(sql_handle,  6, &data, NULL); ele->str = atoi(data);
-	Sql_GetData(sql_handle,  7, &data, NULL); ele->agi = atoi(data);
-	Sql_GetData(sql_handle,  8, &data, NULL); ele->vit = atoi(data);
-	Sql_GetData(sql_handle,  9, &data, NULL); ele->int_ = atoi(data);
-	Sql_GetData(sql_handle, 10, &data, NULL); ele->dex = atoi(data);
-	Sql_GetData(sql_handle, 11, &data, NULL); ele->luk = atoi(data);
-	Sql_GetData(sql_handle, 12, &data, NULL); ele->life_time = atoi(data);
-	Sql_FreeResult(sql_handle);
-	if( save_log )
-		ShowInfo("Elemental loaded (%d - %d).\n", ele->elemental_id, ele->char_id);
-	
-	return true;
+bool mapif_elemental_load(int ele_id, int char_id, struct s_elemental *ele)
+{
+    char *data;
+
+    memset(ele, 0, sizeof(struct s_elemental));
+    ele->elemental_id = ele_id;
+    ele->char_id = char_id;
+
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `class`, `mode`, `hp`, `sp`, `max_hp`, `max_sp`, `str`, `agi`, `vit`, `int`, `dex`,"
+                               "`luk`, `life_time` FROM `elemental` WHERE `ele_id` = '%d' AND `char_id` = '%d'",
+                               ele_id, char_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+
+    if (SQL_SUCCESS != Sql_NextRow(sql_handle)) {
+        Sql_FreeResult(sql_handle);
+        return false;
+    }
+
+    Sql_GetData(sql_handle,  0, &data, NULL);
+    ele->class_ = atoi(data);
+    Sql_GetData(sql_handle,  1, &data, NULL);
+    ele->mode = atoi(data);
+    Sql_GetData(sql_handle,  2, &data, NULL);
+    ele->hp = atoi(data);
+    Sql_GetData(sql_handle,  3, &data, NULL);
+    ele->sp = atoi(data);
+    Sql_GetData(sql_handle,  4, &data, NULL);
+    ele->max_hp = atoi(data);
+    Sql_GetData(sql_handle,  5, &data, NULL);
+    ele->max_sp = atoi(data);
+    Sql_GetData(sql_handle,  6, &data, NULL);
+    ele->str = atoi(data);
+    Sql_GetData(sql_handle,  7, &data, NULL);
+    ele->agi = atoi(data);
+    Sql_GetData(sql_handle,  8, &data, NULL);
+    ele->vit = atoi(data);
+    Sql_GetData(sql_handle,  9, &data, NULL);
+    ele->int_ = atoi(data);
+    Sql_GetData(sql_handle, 10, &data, NULL);
+    ele->dex = atoi(data);
+    Sql_GetData(sql_handle, 11, &data, NULL);
+    ele->luk = atoi(data);
+    Sql_GetData(sql_handle, 12, &data, NULL);
+    ele->life_time = atoi(data);
+    Sql_FreeResult(sql_handle);
+    if (save_log)
+        ShowInfo("Elemental loaded (%d - %d).\n", ele->elemental_id, ele->char_id);
+
+    return true;
 }
 
-bool mapif_elemental_delete(int ele_id) {
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `elemental` WHERE `ele_id` = '%d'", ele_id) ) {
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-	
-	return true;
+bool mapif_elemental_delete(int ele_id)
+{
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `elemental` WHERE `ele_id` = '%d'", ele_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+
+    return true;
 }
 
-static void mapif_elemental_send(int fd, struct s_elemental *ele, unsigned char flag) {
-	int size = sizeof(struct s_elemental) + 5;
-	
-	WFIFOHEAD(fd,size);
-	WFIFOW(fd,0) = 0x387c;
-	WFIFOW(fd,2) = size;
-	WFIFOB(fd,4) = flag;
-	memcpy(WFIFOP(fd,5),ele,sizeof(struct s_elemental));
-	WFIFOSET(fd,size);
+static void mapif_elemental_send(int fd, struct s_elemental *ele, unsigned char flag)
+{
+    int size = sizeof(struct s_elemental) + 5;
+
+    WFIFOHEAD(fd,size);
+    WFIFOW(fd,0) = 0x387c;
+    WFIFOW(fd,2) = size;
+    WFIFOB(fd,4) = flag;
+    memcpy(WFIFOP(fd,5),ele,sizeof(struct s_elemental));
+    WFIFOSET(fd,size);
 }
 
-static void mapif_parse_elemental_create(int fd, struct s_elemental* ele) {
-	bool result = mapif_elemental_save(ele);
-	mapif_elemental_send(fd, ele, result);
+static void mapif_parse_elemental_create(int fd, struct s_elemental *ele)
+{
+    bool result = mapif_elemental_save(ele);
+    mapif_elemental_send(fd, ele, result);
 }
 
-static void mapif_parse_elemental_load(int fd, int ele_id, int char_id) {
-	struct s_elemental ele;
-	bool result = mapif_elemental_load(ele_id, char_id, &ele);
-	mapif_elemental_send(fd, &ele, result);
+static void mapif_parse_elemental_load(int fd, int ele_id, int char_id)
+{
+    struct s_elemental ele;
+    bool result = mapif_elemental_load(ele_id, char_id, &ele);
+    mapif_elemental_send(fd, &ele, result);
 }
 
-static void mapif_elemental_deleted(int fd, unsigned char flag) {
-	WFIFOHEAD(fd,3);
-	WFIFOW(fd,0) = 0x387d;
-	WFIFOB(fd,2) = flag;
-	WFIFOSET(fd,3);
+static void mapif_elemental_deleted(int fd, unsigned char flag)
+{
+    WFIFOHEAD(fd,3);
+    WFIFOW(fd,0) = 0x387d;
+    WFIFOB(fd,2) = flag;
+    WFIFOSET(fd,3);
 }
 
-static void mapif_parse_elemental_delete(int fd, int ele_id) {
-	bool result = mapif_elemental_delete(ele_id);
-	mapif_elemental_deleted(fd, result);
+static void mapif_parse_elemental_delete(int fd, int ele_id)
+{
+    bool result = mapif_elemental_delete(ele_id);
+    mapif_elemental_deleted(fd, result);
 }
 
-static void mapif_elemental_saved(int fd, unsigned char flag) {
-	WFIFOHEAD(fd,3);
-	WFIFOW(fd,0) = 0x387e;
-	WFIFOB(fd,2) = flag;
-	WFIFOSET(fd,3);
+static void mapif_elemental_saved(int fd, unsigned char flag)
+{
+    WFIFOHEAD(fd,3);
+    WFIFOW(fd,0) = 0x387e;
+    WFIFOB(fd,2) = flag;
+    WFIFOSET(fd,3);
 }
 
-static void mapif_parse_elemental_save(int fd, struct s_elemental* ele) {
-	bool result = mapif_elemental_save(ele);
-	mapif_elemental_saved(fd, result);
+static void mapif_parse_elemental_save(int fd, struct s_elemental *ele)
+{
+    bool result = mapif_elemental_save(ele);
+    mapif_elemental_saved(fd, result);
 }
 
-void inter_elemental_sql_init(void) {
-	return;
+void inter_elemental_sql_init(void)
+{
+    return;
 }
-void inter_elemental_sql_final(void) {
-	return;
+void inter_elemental_sql_final(void)
+{
+    return;
 }
 
 /*==========================================
  * Inter Packets
  *------------------------------------------*/
-int inter_elemental_parse_frommap(int fd) {
-	unsigned short cmd = RFIFOW(fd,0);
-	
-	switch( cmd ) {
-		case 0x307c: mapif_parse_elemental_create(fd, (struct s_elemental*)RFIFOP(fd,4)); break;
-		case 0x307d: mapif_parse_elemental_load(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6)); break;
-		case 0x307e: mapif_parse_elemental_delete(fd, (int)RFIFOL(fd,2)); break;
-		case 0x307f: mapif_parse_elemental_save(fd, (struct s_elemental*)RFIFOP(fd,4)); break;
-		default:
-			return 0;
-	}
-	return 1;
+int inter_elemental_parse_frommap(int fd)
+{
+    unsigned short cmd = RFIFOW(fd,0);
+
+    switch (cmd) {
+        case 0x307c:
+            mapif_parse_elemental_create(fd, (struct s_elemental *)RFIFOP(fd,4));
+            break;
+        case 0x307d:
+            mapif_parse_elemental_load(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6));
+            break;
+        case 0x307e:
+            mapif_parse_elemental_delete(fd, (int)RFIFOL(fd,2));
+            break;
+        case 0x307f:
+            mapif_parse_elemental_save(fd, (struct s_elemental *)RFIFOP(fd,4));
+            break;
+        default:
+            return 0;
+    }
+    return 1;
 }

File diff suppressed because it is too large
+ 649 - 649
src/char/int_guild.c


+ 13 - 13
src/char/int_guild.h

@@ -5,19 +5,19 @@
 #define _INT_GUILD_SQL_H_
 
 enum {
-	GS_BASIC = 0x0001,
-	GS_MEMBER = 0x0002,
-	GS_POSITION = 0x0004,
-	GS_ALLIANCE = 0x0008,
-	GS_EXPULSION = 0x0010,
-	GS_SKILL = 0x0020,
-	GS_EMBLEM = 0x0040,
-	GS_CONNECT = 0x0080,
-	GS_LEVEL = 0x0100,
-	GS_MES = 0x0200,
-	GS_MASK = 0x03FF,
-	GS_BASIC_MASK = (GS_BASIC | GS_EMBLEM | GS_CONNECT | GS_LEVEL | GS_MES),
-	GS_REMOVE = 0x8000,
+    GS_BASIC = 0x0001,
+    GS_MEMBER = 0x0002,
+    GS_POSITION = 0x0004,
+    GS_ALLIANCE = 0x0008,
+    GS_EXPULSION = 0x0010,
+    GS_SKILL = 0x0020,
+    GS_EMBLEM = 0x0040,
+    GS_CONNECT = 0x0080,
+    GS_LEVEL = 0x0100,
+    GS_MES = 0x0200,
+    GS_MASK = 0x03FF,
+    GS_BASIC_MASK = (GS_BASIC | GS_EMBLEM | GS_CONNECT | GS_LEVEL | GS_MES),
+    GS_REMOVE = 0x8000,
 };
 
 struct guild;

+ 240 - 229
src/char/int_homun.c

@@ -18,279 +18,281 @@
 
 int inter_homunculus_sql_init(void)
 {
-	return 0;
+    return 0;
 }
 void inter_homunculus_sql_final(void)
 {
-	return;
+    return;
 }
 
 static void mapif_homunculus_created(int fd, int account_id, struct s_homunculus *sh, unsigned char flag)
 {
-	WFIFOHEAD(fd, sizeof(struct s_homunculus)+9);
-	WFIFOW(fd,0) = 0x3890;
-	WFIFOW(fd,2) = sizeof(struct s_homunculus)+9;
-	WFIFOL(fd,4) = account_id;
-	WFIFOB(fd,8)= flag;
-	memcpy(WFIFOP(fd,9),sh,sizeof(struct s_homunculus));
-	WFIFOSET(fd, WFIFOW(fd,2));
+    WFIFOHEAD(fd, sizeof(struct s_homunculus)+9);
+    WFIFOW(fd,0) = 0x3890;
+    WFIFOW(fd,2) = sizeof(struct s_homunculus)+9;
+    WFIFOL(fd,4) = account_id;
+    WFIFOB(fd,8)= flag;
+    memcpy(WFIFOP(fd,9),sh,sizeof(struct s_homunculus));
+    WFIFOSET(fd, WFIFOW(fd,2));
 }
 
 static void mapif_homunculus_deleted(int fd, int flag)
 {
-	WFIFOHEAD(fd, 3);
-	WFIFOW(fd, 0) = 0x3893;
-	WFIFOB(fd,2) = flag; //Flag 1 = success
-	WFIFOSET(fd, 3);
+    WFIFOHEAD(fd, 3);
+    WFIFOW(fd, 0) = 0x3893;
+    WFIFOB(fd,2) = flag; //Flag 1 = success
+    WFIFOSET(fd, 3);
 }
 
 static void mapif_homunculus_loaded(int fd, int account_id, struct s_homunculus *hd)
 {
-	WFIFOHEAD(fd, sizeof(struct s_homunculus)+9);
-	WFIFOW(fd,0) = 0x3891;
-	WFIFOW(fd,2) = sizeof(struct s_homunculus)+9;
-	WFIFOL(fd,4) = account_id;
-	if( hd != NULL )
-	{
-		WFIFOB(fd,8) = 1; // success
-		memcpy(WFIFOP(fd,9), hd, sizeof(struct s_homunculus));
-	}
-	else
-	{
-		WFIFOB(fd,8) = 0; // not found.
-		memset(WFIFOP(fd,9), 0, sizeof(struct s_homunculus));
-	}
-	WFIFOSET(fd, sizeof(struct s_homunculus)+9);
+    WFIFOHEAD(fd, sizeof(struct s_homunculus)+9);
+    WFIFOW(fd,0) = 0x3891;
+    WFIFOW(fd,2) = sizeof(struct s_homunculus)+9;
+    WFIFOL(fd,4) = account_id;
+    if (hd != NULL) {
+        WFIFOB(fd,8) = 1; // success
+        memcpy(WFIFOP(fd,9), hd, sizeof(struct s_homunculus));
+    } else {
+        WFIFOB(fd,8) = 0; // not found.
+        memset(WFIFOP(fd,9), 0, sizeof(struct s_homunculus));
+    }
+    WFIFOSET(fd, sizeof(struct s_homunculus)+9);
 }
 
 static void mapif_homunculus_saved(int fd, int account_id, bool flag)
 {
-	WFIFOHEAD(fd, 7);
-	WFIFOW(fd,0) = 0x3892;
-	WFIFOL(fd,2) = account_id;
-	WFIFOB(fd,6) = flag; // 1:success, 0:failure
-	WFIFOSET(fd, 7);
+    WFIFOHEAD(fd, 7);
+    WFIFOW(fd,0) = 0x3892;
+    WFIFOL(fd,2) = account_id;
+    WFIFOB(fd,6) = flag; // 1:success, 0:failure
+    WFIFOSET(fd, 7);
 }
 
-static void mapif_homunculus_renamed(int fd, int account_id, int char_id, unsigned char flag, char* name)
+static void mapif_homunculus_renamed(int fd, int account_id, int char_id, unsigned char flag, char *name)
 {
-	WFIFOHEAD(fd, NAME_LENGTH+12);
-	WFIFOW(fd, 0) = 0x3894;
-	WFIFOL(fd, 2) = account_id;
-	WFIFOL(fd, 6) = char_id;
-	WFIFOB(fd,10) = flag;
-	safestrncpy((char*)WFIFOP(fd,11), name, NAME_LENGTH);
-	WFIFOSET(fd, NAME_LENGTH+12);
+    WFIFOHEAD(fd, NAME_LENGTH+12);
+    WFIFOW(fd, 0) = 0x3894;
+    WFIFOL(fd, 2) = account_id;
+    WFIFOL(fd, 6) = char_id;
+    WFIFOB(fd,10) = flag;
+    safestrncpy((char *)WFIFOP(fd,11), name, NAME_LENGTH);
+    WFIFOSET(fd, NAME_LENGTH+12);
 }
 
-bool mapif_homunculus_save(struct s_homunculus* hd)
+bool mapif_homunculus_save(struct s_homunculus *hd)
 {
-	bool flag = true;
-	char esc_name[NAME_LENGTH*2+1];
-
-	Sql_EscapeStringLen(sql_handle, esc_name, hd->name, strnlen(hd->name, NAME_LENGTH));
-
-	if( hd->hom_id == 0 )
-	{// new homunculus
-		if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` "
-			"(`char_id`, `class`,`prev_class`,`name`,`level`,`exp`,`intimacy`,`hunger`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `hp`,`max_hp`,`sp`,`max_sp`,`skill_point`, `rename_flag`, `vaporize`) "
-			"VALUES ('%d', '%d', '%d', '%s', '%d', '%u', '%u', '%d', '%d', %d, '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')",
-			homunculus_db, hd->char_id, hd->class_, hd->prev_class, esc_name, hd->level, hd->exp, hd->intimacy, hd->hunger, hd->str, hd->agi, hd->vit, hd->int_, hd->dex, hd->luk,
-			hd->hp, hd->max_hp, hd->sp, hd->max_sp, hd->skillpts, hd->rename_flag, hd->vaporize) )
-		{
-			Sql_ShowDebug(sql_handle);
-			flag = false;
-		}
-		else
-		{
-			hd->hom_id = (int)Sql_LastInsertId(sql_handle);
-		}
-	}
-	else
-	{
-		if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `char_id`='%d', `class`='%d',`prev_class`='%d',`name`='%s',`level`='%d',`exp`='%u',`intimacy`='%u',`hunger`='%d', `str`='%d', `agi`='%d', `vit`='%d', `int`='%d', `dex`='%d', `luk`='%d', `hp`='%d',`max_hp`='%d',`sp`='%d',`max_sp`='%d',`skill_point`='%d', `rename_flag`='%d', `vaporize`='%d' WHERE `homun_id`='%d'",
-			homunculus_db, hd->char_id, hd->class_, hd->prev_class, esc_name, hd->level, hd->exp, hd->intimacy, hd->hunger, hd->str, hd->agi, hd->vit, hd->int_, hd->dex, hd->luk,
-			hd->hp, hd->max_hp, hd->sp, hd->max_sp, hd->skillpts, hd->rename_flag, hd->vaporize, hd->hom_id) )
-		{
-			Sql_ShowDebug(sql_handle);
-			flag = false;
-		}
-		else
-		{
-			SqlStmt* stmt;
-			int i;
-
-			stmt = SqlStmt_Malloc(sql_handle);
-			if( SQL_ERROR == SqlStmt_Prepare(stmt, "REPLACE INTO `%s` (`homun_id`, `id`, `lv`) VALUES (%d, ?, ?)", skill_homunculus_db, hd->hom_id) )
-				SqlStmt_ShowDebug(stmt);
-			for( i = 0; i < MAX_HOMUNSKILL; ++i )
-			{
-				if( hd->hskill[i].id > 0 && hd->hskill[i].lv != 0 )
-				{
-					SqlStmt_BindParam(stmt, 0, SQLDT_USHORT, &hd->hskill[i].id, 0);
-					SqlStmt_BindParam(stmt, 1, SQLDT_USHORT, &hd->hskill[i].lv, 0);
-					if( SQL_ERROR == SqlStmt_Execute(stmt) )
-					{
-						SqlStmt_ShowDebug(stmt);
-						SqlStmt_Free(stmt);
-						flag = false;
-						break;
-					}
-				}
-			}
-			SqlStmt_Free(stmt);
-		}
-	}
-
-	return flag;
+    bool flag = true;
+    char esc_name[NAME_LENGTH*2+1];
+
+    Sql_EscapeStringLen(sql_handle, esc_name, hd->name, strnlen(hd->name, NAME_LENGTH));
+
+    if (hd->hom_id == 0) {
+        // new homunculus
+        if (SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` "
+                                   "(`char_id`, `class`,`prev_class`,`name`,`level`,`exp`,`intimacy`,`hunger`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `hp`,`max_hp`,`sp`,`max_sp`,`skill_point`, `rename_flag`, `vaporize`) "
+                                   "VALUES ('%d', '%d', '%d', '%s', '%d', '%u', '%u', '%d', '%d', %d, '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')",
+                                   homunculus_db, hd->char_id, hd->class_, hd->prev_class, esc_name, hd->level, hd->exp, hd->intimacy, hd->hunger, hd->str, hd->agi, hd->vit, hd->int_, hd->dex, hd->luk,
+                                   hd->hp, hd->max_hp, hd->sp, hd->max_sp, hd->skillpts, hd->rename_flag, hd->vaporize)) {
+            Sql_ShowDebug(sql_handle);
+            flag = false;
+        } else {
+            hd->hom_id = (int)Sql_LastInsertId(sql_handle);
+        }
+    } else {
+        if (SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `char_id`='%d', `class`='%d',`prev_class`='%d',`name`='%s',`level`='%d',`exp`='%u',`intimacy`='%u',`hunger`='%d', `str`='%d', `agi`='%d', `vit`='%d', `int`='%d', `dex`='%d', `luk`='%d', `hp`='%d',`max_hp`='%d',`sp`='%d',`max_sp`='%d',`skill_point`='%d', `rename_flag`='%d', `vaporize`='%d' WHERE `homun_id`='%d'",
+                                   homunculus_db, hd->char_id, hd->class_, hd->prev_class, esc_name, hd->level, hd->exp, hd->intimacy, hd->hunger, hd->str, hd->agi, hd->vit, hd->int_, hd->dex, hd->luk,
+                                   hd->hp, hd->max_hp, hd->sp, hd->max_sp, hd->skillpts, hd->rename_flag, hd->vaporize, hd->hom_id)) {
+            Sql_ShowDebug(sql_handle);
+            flag = false;
+        } else {
+            SqlStmt *stmt;
+            int i;
+
+            stmt = SqlStmt_Malloc(sql_handle);
+            if (SQL_ERROR == SqlStmt_Prepare(stmt, "REPLACE INTO `%s` (`homun_id`, `id`, `lv`) VALUES (%d, ?, ?)", skill_homunculus_db, hd->hom_id))
+                SqlStmt_ShowDebug(stmt);
+            for (i = 0; i < MAX_HOMUNSKILL; ++i) {
+                if (hd->hskill[i].id > 0 && hd->hskill[i].lv != 0) {
+                    SqlStmt_BindParam(stmt, 0, SQLDT_USHORT, &hd->hskill[i].id, 0);
+                    SqlStmt_BindParam(stmt, 1, SQLDT_USHORT, &hd->hskill[i].lv, 0);
+                    if (SQL_ERROR == SqlStmt_Execute(stmt)) {
+                        SqlStmt_ShowDebug(stmt);
+                        SqlStmt_Free(stmt);
+                        flag = false;
+                        break;
+                    }
+                }
+            }
+            SqlStmt_Free(stmt);
+        }
+    }
+
+    return flag;
 }
 
 
 
 // Load an homunculus
-bool mapif_homunculus_load(int homun_id, struct s_homunculus* hd)
+bool mapif_homunculus_load(int homun_id, struct s_homunculus *hd)
 {
-	int i;
-	char* data;
-	size_t len;
-
-	memset(hd, 0, sizeof(*hd));
-
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `homun_id`,`char_id`,`class`,`prev_class`,`name`,`level`,`exp`,`intimacy`,`hunger`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `hp`,`max_hp`,`sp`,`max_sp`,`skill_point`,`rename_flag`, `vaporize` FROM `%s` WHERE `homun_id`='%u'", homunculus_db, homun_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-
-	if( !Sql_NumRows(sql_handle) )
-	{	//No homunculus found.
-		Sql_FreeResult(sql_handle);
-		return false;
-	}
-	if( SQL_SUCCESS != Sql_NextRow(sql_handle) )
-	{
-		Sql_ShowDebug(sql_handle);
-		Sql_FreeResult(sql_handle);
-		return false;
-	}
-
-	hd->hom_id = homun_id;
-	Sql_GetData(sql_handle,  1, &data, NULL); hd->char_id = atoi(data);
-	Sql_GetData(sql_handle,  2, &data, NULL); hd->class_ = atoi(data);
-	Sql_GetData(sql_handle,  3, &data, NULL); hd->prev_class = atoi(data);
-	Sql_GetData(sql_handle,  4, &data, &len); safestrncpy(hd->name, data, sizeof(hd->name));
-	Sql_GetData(sql_handle,  5, &data, NULL); hd->level = atoi(data);
-	Sql_GetData(sql_handle,  6, &data, NULL); hd->exp = atoi(data);
-	Sql_GetData(sql_handle,  7, &data, NULL); hd->intimacy = (unsigned int)strtoul(data, NULL, 10);
-	Sql_GetData(sql_handle,  8, &data, NULL); hd->hunger = atoi(data);
-	Sql_GetData(sql_handle,  9, &data, NULL); hd->str = atoi(data);
-	Sql_GetData(sql_handle, 10, &data, NULL); hd->agi = atoi(data);
-	Sql_GetData(sql_handle, 11, &data, NULL); hd->vit = atoi(data);
-	Sql_GetData(sql_handle, 12, &data, NULL); hd->int_ = atoi(data);
-	Sql_GetData(sql_handle, 13, &data, NULL); hd->dex = atoi(data);
-	Sql_GetData(sql_handle, 14, &data, NULL); hd->luk = atoi(data);
-	Sql_GetData(sql_handle, 15, &data, NULL); hd->hp = atoi(data);
-	Sql_GetData(sql_handle, 16, &data, NULL); hd->max_hp = atoi(data);
-	Sql_GetData(sql_handle, 17, &data, NULL); hd->sp = atoi(data);
-	Sql_GetData(sql_handle, 18, &data, NULL); hd->max_sp = atoi(data);
-	Sql_GetData(sql_handle, 19, &data, NULL); hd->skillpts = atoi(data);
-	Sql_GetData(sql_handle, 20, &data, NULL); hd->rename_flag = atoi(data);
-	Sql_GetData(sql_handle, 21, &data, NULL); hd->vaporize = atoi(data);
-	Sql_FreeResult(sql_handle);
-
-	hd->intimacy = cap_value(hd->intimacy, 0, 100000);
-	hd->hunger = cap_value(hd->hunger, 0, 100);
-
-	// Load Homunculus Skill
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `id`,`lv` FROM `%s` WHERE `homun_id`=%d", skill_homunculus_db, homun_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-	while( SQL_SUCCESS == Sql_NextRow(sql_handle) )
-	{
-		// id
-		Sql_GetData(sql_handle, 0, &data, NULL);
-		i = atoi(data);
-		if( i < HM_SKILLBASE || i >= HM_SKILLBASE + MAX_HOMUNSKILL )
-			continue;// invalid skill id
-		i = i - HM_SKILLBASE;
-		hd->hskill[i].id = (unsigned short)atoi(data);
-
-		// lv
-		Sql_GetData(sql_handle, 1, &data, NULL);
-		hd->hskill[i].lv = (unsigned char)atoi(data);
-	}
-	Sql_FreeResult(sql_handle);
-
-	if( save_log )
-		ShowInfo("Homunculus loaded (%d - %s).\n", hd->hom_id, hd->name);
-
-	return true;
+    int i;
+    char *data;
+    size_t len;
+
+    memset(hd, 0, sizeof(*hd));
+
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `homun_id`,`char_id`,`class`,`prev_class`,`name`,`level`,`exp`,`intimacy`,`hunger`, `str`, `agi`, `vit`, `int`, `dex`, `luk`, `hp`,`max_hp`,`sp`,`max_sp`,`skill_point`,`rename_flag`, `vaporize` FROM `%s` WHERE `homun_id`='%u'", homunculus_db, homun_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+
+    if (!Sql_NumRows(sql_handle)) {
+        //No homunculus found.
+        Sql_FreeResult(sql_handle);
+        return false;
+    }
+    if (SQL_SUCCESS != Sql_NextRow(sql_handle)) {
+        Sql_ShowDebug(sql_handle);
+        Sql_FreeResult(sql_handle);
+        return false;
+    }
+
+    hd->hom_id = homun_id;
+    Sql_GetData(sql_handle,  1, &data, NULL);
+    hd->char_id = atoi(data);
+    Sql_GetData(sql_handle,  2, &data, NULL);
+    hd->class_ = atoi(data);
+    Sql_GetData(sql_handle,  3, &data, NULL);
+    hd->prev_class = atoi(data);
+    Sql_GetData(sql_handle,  4, &data, &len);
+    safestrncpy(hd->name, data, sizeof(hd->name));
+    Sql_GetData(sql_handle,  5, &data, NULL);
+    hd->level = atoi(data);
+    Sql_GetData(sql_handle,  6, &data, NULL);
+    hd->exp = atoi(data);
+    Sql_GetData(sql_handle,  7, &data, NULL);
+    hd->intimacy = (unsigned int)strtoul(data, NULL, 10);
+    Sql_GetData(sql_handle,  8, &data, NULL);
+    hd->hunger = atoi(data);
+    Sql_GetData(sql_handle,  9, &data, NULL);
+    hd->str = atoi(data);
+    Sql_GetData(sql_handle, 10, &data, NULL);
+    hd->agi = atoi(data);
+    Sql_GetData(sql_handle, 11, &data, NULL);
+    hd->vit = atoi(data);
+    Sql_GetData(sql_handle, 12, &data, NULL);
+    hd->int_ = atoi(data);
+    Sql_GetData(sql_handle, 13, &data, NULL);
+    hd->dex = atoi(data);
+    Sql_GetData(sql_handle, 14, &data, NULL);
+    hd->luk = atoi(data);
+    Sql_GetData(sql_handle, 15, &data, NULL);
+    hd->hp = atoi(data);
+    Sql_GetData(sql_handle, 16, &data, NULL);
+    hd->max_hp = atoi(data);
+    Sql_GetData(sql_handle, 17, &data, NULL);
+    hd->sp = atoi(data);
+    Sql_GetData(sql_handle, 18, &data, NULL);
+    hd->max_sp = atoi(data);
+    Sql_GetData(sql_handle, 19, &data, NULL);
+    hd->skillpts = atoi(data);
+    Sql_GetData(sql_handle, 20, &data, NULL);
+    hd->rename_flag = atoi(data);
+    Sql_GetData(sql_handle, 21, &data, NULL);
+    hd->vaporize = atoi(data);
+    Sql_FreeResult(sql_handle);
+
+    hd->intimacy = cap_value(hd->intimacy, 0, 100000);
+    hd->hunger = cap_value(hd->hunger, 0, 100);
+
+    // Load Homunculus Skill
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `id`,`lv` FROM `%s` WHERE `homun_id`=%d", skill_homunculus_db, homun_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+    while (SQL_SUCCESS == Sql_NextRow(sql_handle)) {
+        // id
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        i = atoi(data);
+        if (i < HM_SKILLBASE || i >= HM_SKILLBASE + MAX_HOMUNSKILL)
+            continue;// invalid skill id
+        i = i - HM_SKILLBASE;
+        hd->hskill[i].id = (unsigned short)atoi(data);
+
+        // lv
+        Sql_GetData(sql_handle, 1, &data, NULL);
+        hd->hskill[i].lv = (unsigned char)atoi(data);
+    }
+    Sql_FreeResult(sql_handle);
+
+    if (save_log)
+        ShowInfo("Homunculus loaded (%d - %s).\n", hd->hom_id, hd->name);
+
+    return true;
 }
 
 bool mapif_homunculus_delete(int homun_id)
 {
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `homun_id` = '%u'", homunculus_db, homun_id)
-	||	SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `homun_id` = '%u'", skill_homunculus_db, homun_id)
-	) {
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-	return true;
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `homun_id` = '%u'", homunculus_db, homun_id)
+        ||  SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `homun_id` = '%u'", skill_homunculus_db, homun_id)
+       ) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+    return true;
 }
 
 bool mapif_homunculus_rename(char *name)
 {
-	int i;
-
-	// Check Authorised letters/symbols in the name of the homun
-	if( char_name_option == 1 )
-	{// only letters/symbols in char_name_letters are authorised
-		for( i = 0; i < NAME_LENGTH && name[i]; i++ )
-			if( strchr(char_name_letters, name[i]) == NULL )
-				return false;
-	} else
-	if( char_name_option == 2 )
-	{// letters/symbols in char_name_letters are forbidden
-		for( i = 0; i < NAME_LENGTH && name[i]; i++ )
-			if( strchr(char_name_letters, name[i]) != NULL )
-				return false;
-	}
-
-	return true;
+    int i;
+
+    // Check Authorised letters/symbols in the name of the homun
+    if (char_name_option == 1) {
+        // only letters/symbols in char_name_letters are authorised
+        for (i = 0; i < NAME_LENGTH && name[i]; i++)
+            if (strchr(char_name_letters, name[i]) == NULL)
+                return false;
+    } else if (char_name_option == 2) {
+        // letters/symbols in char_name_letters are forbidden
+        for (i = 0; i < NAME_LENGTH && name[i]; i++)
+            if (strchr(char_name_letters, name[i]) != NULL)
+                return false;
+    }
+
+    return true;
 }
 
 
-static void mapif_parse_homunculus_create(int fd, int len, int account_id, struct s_homunculus* phd)
+static void mapif_parse_homunculus_create(int fd, int len, int account_id, struct s_homunculus *phd)
 {
-	bool result = mapif_homunculus_save(phd);
-	mapif_homunculus_created(fd, account_id, phd, result);
+    bool result = mapif_homunculus_save(phd);
+    mapif_homunculus_created(fd, account_id, phd, result);
 }
 
 static void mapif_parse_homunculus_delete(int fd, int homun_id)
 {
-	bool result = mapif_homunculus_delete(homun_id);
-	mapif_homunculus_deleted(fd, result);
+    bool result = mapif_homunculus_delete(homun_id);
+    mapif_homunculus_deleted(fd, result);
 }
 
 static void mapif_parse_homunculus_load(int fd, int account_id, int homun_id)
 {
-	struct s_homunculus hd;
-	bool result = mapif_homunculus_load(homun_id, &hd);
-	mapif_homunculus_loaded(fd, account_id, ( result ? &hd : NULL ));
+    struct s_homunculus hd;
+    bool result = mapif_homunculus_load(homun_id, &hd);
+    mapif_homunculus_loaded(fd, account_id, (result ? &hd : NULL));
 }
 
-static void mapif_parse_homunculus_save(int fd, int len, int account_id, struct s_homunculus* phd)
+static void mapif_parse_homunculus_save(int fd, int len, int account_id, struct s_homunculus *phd)
 {
-	bool result = mapif_homunculus_save(phd);
-	mapif_homunculus_saved(fd, account_id, result);
+    bool result = mapif_homunculus_save(phd);
+    mapif_homunculus_saved(fd, account_id, result);
 }
 
-static void mapif_parse_homunculus_rename(int fd, int account_id, int char_id, char* name)
+static void mapif_parse_homunculus_rename(int fd, int account_id, int char_id, char *name)
 {
-	bool result = mapif_homunculus_rename(name);
-	mapif_homunculus_renamed(fd, account_id, char_id, result, name);
+    bool result = mapif_homunculus_rename(name);
+    mapif_homunculus_renamed(fd, account_id, char_id, result, name);
 }
 
 /*==========================================
@@ -298,17 +300,26 @@ static void mapif_parse_homunculus_rename(int fd, int account_id, int char_id, c
  *------------------------------------------*/
 int inter_homunculus_parse_frommap(int fd)
 {
-	unsigned short cmd = RFIFOW(fd,0);
-
-	switch( cmd )
-	{
-		case 0x3090: mapif_parse_homunculus_create(fd, (int)RFIFOW(fd,2), (int)RFIFOL(fd,4), (struct s_homunculus*)RFIFOP(fd,8)); break;
-		case 0x3091: mapif_parse_homunculus_load  (fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6)); break;
-		case 0x3092: mapif_parse_homunculus_save  (fd, (int)RFIFOW(fd,2), (int)RFIFOL(fd,4), (struct s_homunculus*)RFIFOP(fd,8)); break;
-		case 0x3093: mapif_parse_homunculus_delete(fd, (int)RFIFOL(fd,2)); break;
-		case 0x3094: mapif_parse_homunculus_rename(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6), (char*)RFIFOP(fd,10)); break;
-		default:
-			return 0;
-	}
-	return 1;
+    unsigned short cmd = RFIFOW(fd,0);
+
+    switch (cmd) {
+        case 0x3090:
+            mapif_parse_homunculus_create(fd, (int)RFIFOW(fd,2), (int)RFIFOL(fd,4), (struct s_homunculus *)RFIFOP(fd,8));
+            break;
+        case 0x3091:
+            mapif_parse_homunculus_load(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6));
+            break;
+        case 0x3092:
+            mapif_parse_homunculus_save(fd, (int)RFIFOW(fd,2), (int)RFIFOL(fd,4), (struct s_homunculus *)RFIFOP(fd,8));
+            break;
+        case 0x3093:
+            mapif_parse_homunculus_delete(fd, (int)RFIFOL(fd,2));
+            break;
+        case 0x3094:
+            mapif_parse_homunculus_rename(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6), (char *)RFIFOP(fd,10));
+            break;
+        default:
+            return 0;
+    }
+    return 1;
 }

+ 2 - 2
src/char/int_homun.h

@@ -10,8 +10,8 @@ int inter_homunculus_sql_init(void);
 void inter_homunculus_sql_final(void);
 int inter_homunculus_parse_frommap(int fd);
 
-bool mapif_homunculus_save(struct s_homunculus* hd);
-bool mapif_homunculus_load(int homun_id, struct s_homunculus* hd);
+bool mapif_homunculus_save(struct s_homunculus *hd);
+bool mapif_homunculus_load(int homun_id, struct s_homunculus *hd);
 bool mapif_homunculus_delete(int homun_id);
 bool mapif_homunculus_rename(char *name);
 

+ 373 - 348
src/char/int_mail.c

@@ -15,180 +15,200 @@
 #include <string.h>
 #include <stdlib.h>
 
-static int mail_fromsql(int char_id, struct mail_data* md)
+static int mail_fromsql(int char_id, struct mail_data *md)
 {
-	int i, j;
-	struct mail_message *msg;
-	struct item *item;
-	char *data;
-	StringBuf buf;
-
-	memset(md, 0, sizeof(struct mail_data));
-	md->amount = 0;
-	md->full = false;
-
-	StringBuf_Init(&buf);
-	StringBuf_AppendStr(&buf, "SELECT `id`,`send_name`,`send_id`,`dest_name`,`dest_id`,`title`,`message`,`time`,`status`,"
-		"`zeny`,`amount`,`nameid`,`refine`,`attribute`,`identify`");
-	for (i = 0; i < MAX_SLOTS; i++)
-		StringBuf_Printf(&buf, ",`card%d`", i);
-
-	// I keep the `status` < 3 just in case someone forget to apply the sqlfix
-	StringBuf_Printf(&buf, " FROM `%s` WHERE `dest_id`='%d' AND `status` < 3 ORDER BY `id` LIMIT %d",
-		mail_db, char_id, MAIL_MAX_INBOX + 1);
-
-	if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) )
-		Sql_ShowDebug(sql_handle);
-
-	StringBuf_Destroy(&buf);
-
-	for (i = 0; i < MAIL_MAX_INBOX && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i )
-	{
-		msg = &md->msg[i];
-		Sql_GetData(sql_handle, 0, &data, NULL); msg->id = atoi(data);
-		Sql_GetData(sql_handle, 1, &data, NULL); safestrncpy(msg->send_name, data, NAME_LENGTH);
-		Sql_GetData(sql_handle, 2, &data, NULL); msg->send_id = atoi(data);
-		Sql_GetData(sql_handle, 3, &data, NULL); safestrncpy(msg->dest_name, data, NAME_LENGTH);
-		Sql_GetData(sql_handle, 4, &data, NULL); msg->dest_id = atoi(data);
-		Sql_GetData(sql_handle, 5, &data, NULL); safestrncpy(msg->title, data, MAIL_TITLE_LENGTH);
-		Sql_GetData(sql_handle, 6, &data, NULL); safestrncpy(msg->body, data, MAIL_BODY_LENGTH);
-		Sql_GetData(sql_handle, 7, &data, NULL); msg->timestamp = atoi(data);
-		Sql_GetData(sql_handle, 8, &data, NULL); msg->status = (mail_status)atoi(data);
-		Sql_GetData(sql_handle, 9, &data, NULL); msg->zeny = atoi(data);
-		item = &msg->item;
-		Sql_GetData(sql_handle,10, &data, NULL); item->amount = (short)atoi(data);
-		Sql_GetData(sql_handle,11, &data, NULL); item->nameid = atoi(data);
-		Sql_GetData(sql_handle,12, &data, NULL); item->refine = atoi(data);
-		Sql_GetData(sql_handle,13, &data, NULL); item->attribute = atoi(data);
-		Sql_GetData(sql_handle,14, &data, NULL); item->identify = atoi(data);
-		item->expire_time = 0;
-
-		for (j = 0; j < MAX_SLOTS; j++)
-		{
-			Sql_GetData(sql_handle, 15 + j, &data, NULL);
-			item->card[j] = atoi(data);
-		}
-	}
-
-	md->full = ( Sql_NumRows(sql_handle) > MAIL_MAX_INBOX );
-
-	md->amount = i;
-	Sql_FreeResult(sql_handle);
-
-	md->unchecked = 0;
-	md->unread = 0;
-	for (i = 0; i < md->amount; i++)
-	{
-		msg = &md->msg[i];
-		if( msg->status == MAIL_NEW )
-		{
-			if ( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `status` = '%d' WHERE `id` = '%d'", mail_db, MAIL_UNREAD, msg->id) )
-				Sql_ShowDebug(sql_handle);
-
-			msg->status = MAIL_UNREAD;
-			md->unchecked++;
-		}
-		else if ( msg->status == MAIL_UNREAD )
-			md->unread++;
-	}
-
-	ShowInfo("mail load complete from DB - id: %d (total: %d)\n", char_id, md->amount);
-	return 1;
+    int i, j;
+    struct mail_message *msg;
+    struct item *item;
+    char *data;
+    StringBuf buf;
+
+    memset(md, 0, sizeof(struct mail_data));
+    md->amount = 0;
+    md->full = false;
+
+    StringBuf_Init(&buf);
+    StringBuf_AppendStr(&buf, "SELECT `id`,`send_name`,`send_id`,`dest_name`,`dest_id`,`title`,`message`,`time`,`status`,"
+                        "`zeny`,`amount`,`nameid`,`refine`,`attribute`,`identify`");
+    for (i = 0; i < MAX_SLOTS; i++)
+        StringBuf_Printf(&buf, ",`card%d`", i);
+
+    // I keep the `status` < 3 just in case someone forget to apply the sqlfix
+    StringBuf_Printf(&buf, " FROM `%s` WHERE `dest_id`='%d' AND `status` < 3 ORDER BY `id` LIMIT %d",
+                     mail_db, char_id, MAIL_MAX_INBOX + 1);
+
+    if (SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)))
+        Sql_ShowDebug(sql_handle);
+
+    StringBuf_Destroy(&buf);
+
+    for (i = 0; i < MAIL_MAX_INBOX && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i) {
+        msg = &md->msg[i];
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        msg->id = atoi(data);
+        Sql_GetData(sql_handle, 1, &data, NULL);
+        safestrncpy(msg->send_name, data, NAME_LENGTH);
+        Sql_GetData(sql_handle, 2, &data, NULL);
+        msg->send_id = atoi(data);
+        Sql_GetData(sql_handle, 3, &data, NULL);
+        safestrncpy(msg->dest_name, data, NAME_LENGTH);
+        Sql_GetData(sql_handle, 4, &data, NULL);
+        msg->dest_id = atoi(data);
+        Sql_GetData(sql_handle, 5, &data, NULL);
+        safestrncpy(msg->title, data, MAIL_TITLE_LENGTH);
+        Sql_GetData(sql_handle, 6, &data, NULL);
+        safestrncpy(msg->body, data, MAIL_BODY_LENGTH);
+        Sql_GetData(sql_handle, 7, &data, NULL);
+        msg->timestamp = atoi(data);
+        Sql_GetData(sql_handle, 8, &data, NULL);
+        msg->status = (mail_status)atoi(data);
+        Sql_GetData(sql_handle, 9, &data, NULL);
+        msg->zeny = atoi(data);
+        item = &msg->item;
+        Sql_GetData(sql_handle,10, &data, NULL);
+        item->amount = (short)atoi(data);
+        Sql_GetData(sql_handle,11, &data, NULL);
+        item->nameid = atoi(data);
+        Sql_GetData(sql_handle,12, &data, NULL);
+        item->refine = atoi(data);
+        Sql_GetData(sql_handle,13, &data, NULL);
+        item->attribute = atoi(data);
+        Sql_GetData(sql_handle,14, &data, NULL);
+        item->identify = atoi(data);
+        item->expire_time = 0;
+
+        for (j = 0; j < MAX_SLOTS; j++) {
+            Sql_GetData(sql_handle, 15 + j, &data, NULL);
+            item->card[j] = atoi(data);
+        }
+    }
+
+    md->full = (Sql_NumRows(sql_handle) > MAIL_MAX_INBOX);
+
+    md->amount = i;
+    Sql_FreeResult(sql_handle);
+
+    md->unchecked = 0;
+    md->unread = 0;
+    for (i = 0; i < md->amount; i++) {
+        msg = &md->msg[i];
+        if (msg->status == MAIL_NEW) {
+            if (SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `status` = '%d' WHERE `id` = '%d'", mail_db, MAIL_UNREAD, msg->id))
+                Sql_ShowDebug(sql_handle);
+
+            msg->status = MAIL_UNREAD;
+            md->unchecked++;
+        } else if (msg->status == MAIL_UNREAD)
+            md->unread++;
+    }
+
+    ShowInfo("mail load complete from DB - id: %d (total: %d)\n", char_id, md->amount);
+    return 1;
 }
 
 /// Stores a single message in the database.
 /// Returns the message's ID if successful (or 0 if it fails).
-int mail_savemessage(struct mail_message* msg)
+int mail_savemessage(struct mail_message *msg)
 {
-	StringBuf buf;
-	SqlStmt* stmt;
-	int j;
-
-	// build message save query
-	StringBuf_Init(&buf);
-	StringBuf_Printf(&buf, "INSERT INTO `%s` (`send_name`, `send_id`, `dest_name`, `dest_id`, `title`, `message`, `time`, `status`, `zeny`, `amount`, `nameid`, `refine`, `attribute`, `identify`", mail_db);
-	for (j = 0; j < MAX_SLOTS; j++)
-		StringBuf_Printf(&buf, ", `card%d`", j);
-	StringBuf_Printf(&buf, ") VALUES (?, '%d', ?, '%d', ?, ?, '%lu', '%d', '%d', '%d', '%d', '%d', '%d', '%d'",
-		msg->send_id, msg->dest_id, (unsigned long)msg->timestamp, msg->status, msg->zeny, msg->item.amount, msg->item.nameid, msg->item.refine, msg->item.attribute, msg->item.identify);
-	for (j = 0; j < MAX_SLOTS; j++)
-		StringBuf_Printf(&buf, ", '%d'", msg->item.card[j]);
-	StringBuf_AppendStr(&buf, ")");
-
-	// prepare and execute query
-	stmt = SqlStmt_Malloc(sql_handle);
-	if( SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, msg->send_name, strnlen(msg->send_name, NAME_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, msg->dest_name, strnlen(msg->dest_name, NAME_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, msg->title, strnlen(msg->title, MAIL_TITLE_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 3, SQLDT_STRING, msg->body, strnlen(msg->body, MAIL_BODY_LENGTH))
-	||  SQL_SUCCESS != SqlStmt_Execute(stmt) )
-	{
-		SqlStmt_ShowDebug(stmt);
-		msg->id = 0;
-	} else
-		msg->id = (int)SqlStmt_LastInsertId(stmt);
-
-	SqlStmt_Free(stmt);
-	StringBuf_Destroy(&buf);
-
-	return msg->id;
+    StringBuf buf;
+    SqlStmt *stmt;
+    int j;
+
+    // build message save query
+    StringBuf_Init(&buf);
+    StringBuf_Printf(&buf, "INSERT INTO `%s` (`send_name`, `send_id`, `dest_name`, `dest_id`, `title`, `message`, `time`, `status`, `zeny`, `amount`, `nameid`, `refine`, `attribute`, `identify`", mail_db);
+    for (j = 0; j < MAX_SLOTS; j++)
+        StringBuf_Printf(&buf, ", `card%d`", j);
+    StringBuf_Printf(&buf, ") VALUES (?, '%d', ?, '%d', ?, ?, '%lu', '%d', '%d', '%d', '%d', '%d', '%d', '%d'",
+                     msg->send_id, msg->dest_id, (unsigned long)msg->timestamp, msg->status, msg->zeny, msg->item.amount, msg->item.nameid, msg->item.refine, msg->item.attribute, msg->item.identify);
+    for (j = 0; j < MAX_SLOTS; j++)
+        StringBuf_Printf(&buf, ", '%d'", msg->item.card[j]);
+    StringBuf_AppendStr(&buf, ")");
+
+    // prepare and execute query
+    stmt = SqlStmt_Malloc(sql_handle);
+    if (SQL_SUCCESS != SqlStmt_PrepareStr(stmt, StringBuf_Value(&buf))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, msg->send_name, strnlen(msg->send_name, NAME_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, msg->dest_name, strnlen(msg->dest_name, NAME_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 2, SQLDT_STRING, msg->title, strnlen(msg->title, MAIL_TITLE_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 3, SQLDT_STRING, msg->body, strnlen(msg->body, MAIL_BODY_LENGTH))
+        ||  SQL_SUCCESS != SqlStmt_Execute(stmt)) {
+        SqlStmt_ShowDebug(stmt);
+        msg->id = 0;
+    } else
+        msg->id = (int)SqlStmt_LastInsertId(stmt);
+
+    SqlStmt_Free(stmt);
+    StringBuf_Destroy(&buf);
+
+    return msg->id;
 }
 
 /// Retrieves a single message from the database.
 /// Returns true if the operation succeeds (or false if it fails).
-static bool mail_loadmessage(int mail_id, struct mail_message* msg)
+static bool mail_loadmessage(int mail_id, struct mail_message *msg)
 {
-	int j;
-	StringBuf buf;
-
-	StringBuf_Init(&buf);
-	StringBuf_AppendStr(&buf, "SELECT `id`,`send_name`,`send_id`,`dest_name`,`dest_id`,`title`,`message`,`time`,`status`,"
-		"`zeny`,`amount`,`nameid`,`refine`,`attribute`,`identify`");
-	for( j = 0; j < MAX_SLOTS; j++ )
-		StringBuf_Printf(&buf, ",`card%d`", j);
-	StringBuf_Printf(&buf, " FROM `%s` WHERE `id` = '%d'", mail_db, mail_id);
-
-	if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf))
-	||  SQL_SUCCESS != Sql_NextRow(sql_handle) )
-	{
-		Sql_ShowDebug(sql_handle);
-		Sql_FreeResult(sql_handle);
-		StringBuf_Destroy(&buf);
-		return false;
-	}
-	else
-	{
-		char* data;
-
-		Sql_GetData(sql_handle, 0, &data, NULL); msg->id = atoi(data);
-		Sql_GetData(sql_handle, 1, &data, NULL); safestrncpy(msg->send_name, data, NAME_LENGTH);
-		Sql_GetData(sql_handle, 2, &data, NULL); msg->send_id = atoi(data);
-		Sql_GetData(sql_handle, 3, &data, NULL); safestrncpy(msg->dest_name, data, NAME_LENGTH);
-		Sql_GetData(sql_handle, 4, &data, NULL); msg->dest_id = atoi(data);
-		Sql_GetData(sql_handle, 5, &data, NULL); safestrncpy(msg->title, data, MAIL_TITLE_LENGTH);
-		Sql_GetData(sql_handle, 6, &data, NULL); safestrncpy(msg->body, data, MAIL_BODY_LENGTH);
-		Sql_GetData(sql_handle, 7, &data, NULL); msg->timestamp = atoi(data);
-		Sql_GetData(sql_handle, 8, &data, NULL); msg->status = (mail_status)atoi(data);
-		Sql_GetData(sql_handle, 9, &data, NULL); msg->zeny = atoi(data);
-		Sql_GetData(sql_handle,10, &data, NULL); msg->item.amount = (short)atoi(data);
-		Sql_GetData(sql_handle,11, &data, NULL); msg->item.nameid = atoi(data);
-		Sql_GetData(sql_handle,12, &data, NULL); msg->item.refine = atoi(data);
-		Sql_GetData(sql_handle,13, &data, NULL); msg->item.attribute = atoi(data);
-		Sql_GetData(sql_handle,14, &data, NULL); msg->item.identify = atoi(data);
-		msg->item.expire_time = 0;
-
-		for( j = 0; j < MAX_SLOTS; j++ )
-		{
-			Sql_GetData(sql_handle,15 + j, &data, NULL);
-			msg->item.card[j] = atoi(data);
-		}
-	}
-
-	StringBuf_Destroy(&buf);
-	Sql_FreeResult(sql_handle);
-
-	return true;
+    int j;
+    StringBuf buf;
+
+    StringBuf_Init(&buf);
+    StringBuf_AppendStr(&buf, "SELECT `id`,`send_name`,`send_id`,`dest_name`,`dest_id`,`title`,`message`,`time`,`status`,"
+                        "`zeny`,`amount`,`nameid`,`refine`,`attribute`,`identify`");
+    for (j = 0; j < MAX_SLOTS; j++)
+        StringBuf_Printf(&buf, ",`card%d`", j);
+    StringBuf_Printf(&buf, " FROM `%s` WHERE `id` = '%d'", mail_db, mail_id);
+
+    if (SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf))
+        ||  SQL_SUCCESS != Sql_NextRow(sql_handle)) {
+        Sql_ShowDebug(sql_handle);
+        Sql_FreeResult(sql_handle);
+        StringBuf_Destroy(&buf);
+        return false;
+    } else {
+        char *data;
+
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        msg->id = atoi(data);
+        Sql_GetData(sql_handle, 1, &data, NULL);
+        safestrncpy(msg->send_name, data, NAME_LENGTH);
+        Sql_GetData(sql_handle, 2, &data, NULL);
+        msg->send_id = atoi(data);
+        Sql_GetData(sql_handle, 3, &data, NULL);
+        safestrncpy(msg->dest_name, data, NAME_LENGTH);
+        Sql_GetData(sql_handle, 4, &data, NULL);
+        msg->dest_id = atoi(data);
+        Sql_GetData(sql_handle, 5, &data, NULL);
+        safestrncpy(msg->title, data, MAIL_TITLE_LENGTH);
+        Sql_GetData(sql_handle, 6, &data, NULL);
+        safestrncpy(msg->body, data, MAIL_BODY_LENGTH);
+        Sql_GetData(sql_handle, 7, &data, NULL);
+        msg->timestamp = atoi(data);
+        Sql_GetData(sql_handle, 8, &data, NULL);
+        msg->status = (mail_status)atoi(data);
+        Sql_GetData(sql_handle, 9, &data, NULL);
+        msg->zeny = atoi(data);
+        Sql_GetData(sql_handle,10, &data, NULL);
+        msg->item.amount = (short)atoi(data);
+        Sql_GetData(sql_handle,11, &data, NULL);
+        msg->item.nameid = atoi(data);
+        Sql_GetData(sql_handle,12, &data, NULL);
+        msg->item.refine = atoi(data);
+        Sql_GetData(sql_handle,13, &data, NULL);
+        msg->item.attribute = atoi(data);
+        Sql_GetData(sql_handle,14, &data, NULL);
+        msg->item.identify = atoi(data);
+        msg->item.expire_time = 0;
+
+        for (j = 0; j < MAX_SLOTS; j++) {
+            Sql_GetData(sql_handle,15 + j, &data, NULL);
+            msg->item.card[j] = atoi(data);
+        }
+    }
+
+    StringBuf_Destroy(&buf);
+    Sql_FreeResult(sql_handle);
+
+    return true;
 }
 
 /*==========================================
@@ -196,22 +216,22 @@ static bool mail_loadmessage(int mail_id, struct mail_message* msg)
  *------------------------------------------*/
 static void mapif_Mail_sendinbox(int fd, int char_id, unsigned char flag)
 {
-	struct mail_data md;
-	mail_fromsql(char_id, &md);
-
-	//FIXME: dumping the whole structure like this is unsafe [ultramage]
-	WFIFOHEAD(fd, sizeof(md) + 9);
-	WFIFOW(fd,0) = 0x3848;
-	WFIFOW(fd,2) = sizeof(md) + 9;
-	WFIFOL(fd,4) = char_id;
-	WFIFOB(fd,8) = flag;
-	memcpy(WFIFOP(fd,9),&md,sizeof(md));
-	WFIFOSET(fd,WFIFOW(fd,2));
+    struct mail_data md;
+    mail_fromsql(char_id, &md);
+
+    //FIXME: dumping the whole structure like this is unsafe [ultramage]
+    WFIFOHEAD(fd, sizeof(md) + 9);
+    WFIFOW(fd,0) = 0x3848;
+    WFIFOW(fd,2) = sizeof(md) + 9;
+    WFIFOL(fd,4) = char_id;
+    WFIFOB(fd,8) = flag;
+    memcpy(WFIFOP(fd,9),&md,sizeof(md));
+    WFIFOSET(fd,WFIFOW(fd,2));
 }
 
 static void mapif_parse_Mail_requestinbox(int fd)
 {
-	mapif_Mail_sendinbox(fd, RFIFOL(fd,2), RFIFOB(fd,6));
+    mapif_Mail_sendinbox(fd, RFIFOL(fd,2), RFIFOB(fd,6));
 }
 
 /*==========================================
@@ -219,9 +239,9 @@ static void mapif_parse_Mail_requestinbox(int fd)
  *------------------------------------------*/
 static void mapif_parse_Mail_read(int fd)
 {
-	int mail_id = RFIFOL(fd,2);
-	if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `status` = '%d' WHERE `id` = '%d'", mail_db, MAIL_READ, mail_id) )
-		Sql_ShowDebug(sql_handle);
+    int mail_id = RFIFOL(fd,2);
+    if (SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `status` = '%d' WHERE `id` = '%d'", mail_db, MAIL_READ, mail_id))
+        Sql_ShowDebug(sql_handle);
 }
 
 /*==========================================
@@ -229,58 +249,57 @@ static void mapif_parse_Mail_read(int fd)
  *------------------------------------------*/
 static bool mail_DeleteAttach(int mail_id)
 {
-	StringBuf buf;
-	int i;
+    StringBuf buf;
+    int i;
 
-	StringBuf_Init(&buf);
-	StringBuf_Printf(&buf, "UPDATE `%s` SET `zeny` = '0', `nameid` = '0', `amount` = '0', `refine` = '0', `attribute` = '0', `identify` = '0'", mail_db);
-	for (i = 0; i < MAX_SLOTS; i++)
-		StringBuf_Printf(&buf, ", `card%d` = '0'", i);
-	StringBuf_Printf(&buf, " WHERE `id` = '%d'", mail_id);
+    StringBuf_Init(&buf);
+    StringBuf_Printf(&buf, "UPDATE `%s` SET `zeny` = '0', `nameid` = '0', `amount` = '0', `refine` = '0', `attribute` = '0', `identify` = '0'", mail_db);
+    for (i = 0; i < MAX_SLOTS; i++)
+        StringBuf_Printf(&buf, ", `card%d` = '0'", i);
+    StringBuf_Printf(&buf, " WHERE `id` = '%d'", mail_id);
 
-	if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) )
-	{
-		Sql_ShowDebug(sql_handle);
-		StringBuf_Destroy(&buf);
+    if (SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf))) {
+        Sql_ShowDebug(sql_handle);
+        StringBuf_Destroy(&buf);
 
-		return false;
-	}
+        return false;
+    }
 
-	StringBuf_Destroy(&buf);
-	return true;
+    StringBuf_Destroy(&buf);
+    return true;
 }
 
 static void mapif_Mail_getattach(int fd, int char_id, int mail_id)
 {
-	struct mail_message msg;
+    struct mail_message msg;
 
-	if( !mail_loadmessage(mail_id, &msg) )
-		return;
+    if (!mail_loadmessage(mail_id, &msg))
+        return;
 
-	if( msg.dest_id != char_id )
-		return;
+    if (msg.dest_id != char_id)
+        return;
 
-	if( msg.status != MAIL_READ )
-		return;
+    if (msg.status != MAIL_READ)
+        return;
 
-	if( (msg.item.nameid < 1 || msg.item.amount < 1) && msg.zeny < 1 )
-		return; // No Attachment
+    if ((msg.item.nameid < 1 || msg.item.amount < 1) && msg.zeny < 1)
+        return; // No Attachment
 
-	if( !mail_DeleteAttach(mail_id) )
-		return;
+    if (!mail_DeleteAttach(mail_id))
+        return;
 
-	WFIFOHEAD(fd, sizeof(struct item) + 12);
-	WFIFOW(fd,0) = 0x384a;
-	WFIFOW(fd,2) = sizeof(struct item) + 12;
-	WFIFOL(fd,4) = char_id;
-	WFIFOL(fd,8) = (msg.zeny > 0)?msg.zeny:0;
-	memcpy(WFIFOP(fd,12), &msg.item, sizeof(struct item));
-	WFIFOSET(fd,WFIFOW(fd,2));
+    WFIFOHEAD(fd, sizeof(struct item) + 12);
+    WFIFOW(fd,0) = 0x384a;
+    WFIFOW(fd,2) = sizeof(struct item) + 12;
+    WFIFOL(fd,4) = char_id;
+    WFIFOL(fd,8) = (msg.zeny > 0)?msg.zeny:0;
+    memcpy(WFIFOP(fd,12), &msg.item, sizeof(struct item));
+    WFIFOSET(fd,WFIFOW(fd,2));
 }
 
 static void mapif_parse_Mail_getattach(int fd)
 {
-	mapif_Mail_getattach(fd, RFIFOL(fd,2), RFIFOL(fd,6));
+    mapif_Mail_getattach(fd, RFIFOL(fd,2), RFIFOL(fd,6));
 }
 
 /*==========================================
@@ -288,24 +307,23 @@ static void mapif_parse_Mail_getattach(int fd)
  *------------------------------------------*/
 static void mapif_Mail_delete(int fd, int char_id, int mail_id)
 {
-	bool failed = false;
-	if ( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `id` = '%d'", mail_db, mail_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		failed = true;
-	}
-
-	WFIFOHEAD(fd,11);
-	WFIFOW(fd,0) = 0x384b;
-	WFIFOL(fd,2) = char_id;
-	WFIFOL(fd,6) = mail_id;
-	WFIFOB(fd,10) = failed;
-	WFIFOSET(fd,11);
+    bool failed = false;
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `id` = '%d'", mail_db, mail_id)) {
+        Sql_ShowDebug(sql_handle);
+        failed = true;
+    }
+
+    WFIFOHEAD(fd,11);
+    WFIFOW(fd,0) = 0x384b;
+    WFIFOL(fd,2) = char_id;
+    WFIFOL(fd,6) = mail_id;
+    WFIFOB(fd,10) = failed;
+    WFIFOSET(fd,11);
 }
 
 static void mapif_parse_Mail_delete(int fd)
 {
-	mapif_Mail_delete(fd, RFIFOL(fd,2), RFIFOL(fd,6));
+    mapif_Mail_delete(fd, RFIFOL(fd,2), RFIFOL(fd,6));
 }
 
 /*==========================================
@@ -313,17 +331,17 @@ static void mapif_parse_Mail_delete(int fd)
  *------------------------------------------*/
 void mapif_Mail_new(struct mail_message *msg)
 {
-	unsigned char buf[74];
-	
-	if( !msg || !msg->id )
-		return;
-
-	WBUFW(buf,0) = 0x3849;
-	WBUFL(buf,2) = msg->dest_id;
-	WBUFL(buf,6) = msg->id;
-	memcpy(WBUFP(buf,10), msg->send_name, NAME_LENGTH);
-	memcpy(WBUFP(buf,34), msg->title, MAIL_TITLE_LENGTH);
-	mapif_sendall(buf, 74);
+    unsigned char buf[74];
+
+    if (!msg || !msg->id)
+        return;
+
+    WBUFW(buf,0) = 0x3849;
+    WBUFL(buf,2) = msg->dest_id;
+    WBUFL(buf,6) = msg->id;
+    memcpy(WBUFP(buf,10), msg->send_name, NAME_LENGTH);
+    memcpy(WBUFP(buf,34), msg->title, MAIL_TITLE_LENGTH);
+    mapif_sendall(buf, 74);
 }
 
 /*==========================================
@@ -331,120 +349,116 @@ void mapif_Mail_new(struct mail_message *msg)
  *------------------------------------------*/
 static void mapif_Mail_return(int fd, int char_id, int mail_id)
 {
-	struct mail_message msg;
-	int new_mail = 0;
-
-	if( mail_loadmessage(mail_id, &msg) )
-	{
-		if( msg.dest_id != char_id)
-			return;
-		else if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `id` = '%d'", mail_db, mail_id) )
-			Sql_ShowDebug(sql_handle);
-		else
-		{
-			char temp_[MAIL_TITLE_LENGTH];
-
-			// swap sender and receiver
-			swap(msg.send_id, msg.dest_id);
-			safestrncpy(temp_, msg.send_name, NAME_LENGTH);
-			safestrncpy(msg.send_name, msg.dest_name, NAME_LENGTH);
-			safestrncpy(msg.dest_name, temp_, NAME_LENGTH);
-
-			// set reply message title
-			snprintf(temp_, MAIL_TITLE_LENGTH, "RE:%s", msg.title);
-			safestrncpy(msg.title, temp_, MAIL_TITLE_LENGTH);
-
-			msg.status = MAIL_NEW;
-			msg.timestamp = time(NULL);
-
-			new_mail = mail_savemessage(&msg);
-			mapif_Mail_new(&msg);
-		}
-	}
-
-	WFIFOHEAD(fd,11);
-	WFIFOW(fd,0) = 0x384c;
-	WFIFOL(fd,2) = char_id;
-	WFIFOL(fd,6) = mail_id;
-	WFIFOB(fd,10) = (new_mail == 0);
-	WFIFOSET(fd,11);
+    struct mail_message msg;
+    int new_mail = 0;
+
+    if (mail_loadmessage(mail_id, &msg)) {
+        if (msg.dest_id != char_id)
+            return;
+        else if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `id` = '%d'", mail_db, mail_id))
+            Sql_ShowDebug(sql_handle);
+        else {
+            char temp_[MAIL_TITLE_LENGTH];
+
+            // swap sender and receiver
+            swap(msg.send_id, msg.dest_id);
+            safestrncpy(temp_, msg.send_name, NAME_LENGTH);
+            safestrncpy(msg.send_name, msg.dest_name, NAME_LENGTH);
+            safestrncpy(msg.dest_name, temp_, NAME_LENGTH);
+
+            // set reply message title
+            snprintf(temp_, MAIL_TITLE_LENGTH, "RE:%s", msg.title);
+            safestrncpy(msg.title, temp_, MAIL_TITLE_LENGTH);
+
+            msg.status = MAIL_NEW;
+            msg.timestamp = time(NULL);
+
+            new_mail = mail_savemessage(&msg);
+            mapif_Mail_new(&msg);
+        }
+    }
+
+    WFIFOHEAD(fd,11);
+    WFIFOW(fd,0) = 0x384c;
+    WFIFOL(fd,2) = char_id;
+    WFIFOL(fd,6) = mail_id;
+    WFIFOB(fd,10) = (new_mail == 0);
+    WFIFOSET(fd,11);
 }
 
 static void mapif_parse_Mail_return(int fd)
 {
-	mapif_Mail_return(fd, RFIFOL(fd,2), RFIFOL(fd,6));
+    mapif_Mail_return(fd, RFIFOL(fd,2), RFIFOL(fd,6));
 }
 
 /*==========================================
  * Send Mail
  *------------------------------------------*/
-static void mapif_Mail_send(int fd, struct mail_message* msg)
+static void mapif_Mail_send(int fd, struct mail_message *msg)
 {
-	int len = sizeof(struct mail_message) + 4;
-	
-	WFIFOHEAD(fd,len);
-	WFIFOW(fd,0) = 0x384d;
-	WFIFOW(fd,2) = len;
-	memcpy(WFIFOP(fd,4), msg, sizeof(struct mail_message));
-	WFIFOSET(fd,len);
+    int len = sizeof(struct mail_message) + 4;
+
+    WFIFOHEAD(fd,len);
+    WFIFOW(fd,0) = 0x384d;
+    WFIFOW(fd,2) = len;
+    memcpy(WFIFOP(fd,4), msg, sizeof(struct mail_message));
+    WFIFOSET(fd,len);
 }
 
 static void mapif_parse_Mail_send(int fd)
 {
-	struct mail_message msg;
-	char esc_name[NAME_LENGTH*2+1];
-	int account_id = 0;
-
-	if(RFIFOW(fd,2) != 8 + sizeof(struct mail_message))
-		return;
-
-	account_id = RFIFOL(fd,4);
-	memcpy(&msg, RFIFOP(fd,8), sizeof(struct mail_message));
-
-	// Try to find the Dest Char by Name
-	Sql_EscapeStringLen(sql_handle, esc_name, msg.dest_name, strnlen(msg.dest_name, NAME_LENGTH));
-	if ( SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id`, `char_id` FROM `%s` WHERE `name` = '%s'", char_db, esc_name) )
-		Sql_ShowDebug(sql_handle);
-	else
-	if ( SQL_SUCCESS == Sql_NextRow(sql_handle) )
-	{
-		char *data;
-		Sql_GetData(sql_handle, 0, &data, NULL);
-		if (atoi(data) != account_id)
-		{ // Cannot send mail to char in the same account
-			Sql_GetData(sql_handle, 1, &data, NULL);
-			msg.dest_id = atoi(data);
-		}
-	}
-	Sql_FreeResult(sql_handle);
-	msg.status = MAIL_NEW;
-
-	if( msg.dest_id > 0 )
-		msg.id = mail_savemessage(&msg);
-
-	mapif_Mail_send(fd, &msg); // notify sender
-	mapif_Mail_new(&msg); // notify recipient
+    struct mail_message msg;
+    char esc_name[NAME_LENGTH*2+1];
+    int account_id = 0;
+
+    if (RFIFOW(fd,2) != 8 + sizeof(struct mail_message))
+        return;
+
+    account_id = RFIFOL(fd,4);
+    memcpy(&msg, RFIFOP(fd,8), sizeof(struct mail_message));
+
+    // Try to find the Dest Char by Name
+    Sql_EscapeStringLen(sql_handle, esc_name, msg.dest_name, strnlen(msg.dest_name, NAME_LENGTH));
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id`, `char_id` FROM `%s` WHERE `name` = '%s'", char_db, esc_name))
+        Sql_ShowDebug(sql_handle);
+    else if (SQL_SUCCESS == Sql_NextRow(sql_handle)) {
+        char *data;
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        if (atoi(data) != account_id) {
+            // Cannot send mail to char in the same account
+            Sql_GetData(sql_handle, 1, &data, NULL);
+            msg.dest_id = atoi(data);
+        }
+    }
+    Sql_FreeResult(sql_handle);
+    msg.status = MAIL_NEW;
+
+    if (msg.dest_id > 0)
+        msg.id = mail_savemessage(&msg);
+
+    mapif_Mail_send(fd, &msg); // notify sender
+    mapif_Mail_new(&msg); // notify recipient
 }
 
-void mail_sendmail(int send_id, const char* send_name, int dest_id, const char* dest_name, const char* title, const char* body, int zeny, struct item *item)
+void mail_sendmail(int send_id, const char *send_name, int dest_id, const char *dest_name, const char *title, const char *body, int zeny, struct item *item)
 {
-	struct mail_message msg;
-	memset(&msg, 0, sizeof(struct mail_message));
-
-	msg.send_id = send_id;
-	safestrncpy(msg.send_name, send_name, NAME_LENGTH);
-	msg.dest_id = dest_id;
-	safestrncpy(msg.dest_name, dest_name, NAME_LENGTH);
-	safestrncpy(msg.title, title, MAIL_TITLE_LENGTH);
-	safestrncpy(msg.body, body, MAIL_BODY_LENGTH);
-	msg.zeny = zeny;
-	if( item != NULL )
-		memcpy(&msg.item, item, sizeof(struct item));
-
-	msg.timestamp = time(NULL);
-
-	mail_savemessage(&msg);
-	mapif_Mail_new(&msg);
+    struct mail_message msg;
+    memset(&msg, 0, sizeof(struct mail_message));
+
+    msg.send_id = send_id;
+    safestrncpy(msg.send_name, send_name, NAME_LENGTH);
+    msg.dest_id = dest_id;
+    safestrncpy(msg.dest_name, dest_name, NAME_LENGTH);
+    safestrncpy(msg.title, title, MAIL_TITLE_LENGTH);
+    safestrncpy(msg.body, body, MAIL_BODY_LENGTH);
+    msg.zeny = zeny;
+    if (item != NULL)
+        memcpy(&msg.item, item, sizeof(struct item));
+
+    msg.timestamp = time(NULL);
+
+    mail_savemessage(&msg);
+    mapif_Mail_new(&msg);
 }
 
 /*==========================================
@@ -452,26 +466,37 @@ void mail_sendmail(int send_id, const char* send_name, int dest_id, const char*
  *------------------------------------------*/
 int inter_mail_parse_frommap(int fd)
 {
-	switch(RFIFOW(fd,0))
-	{
-		case 0x3048: mapif_parse_Mail_requestinbox(fd); break;
-		case 0x3049: mapif_parse_Mail_read(fd); break;
-		case 0x304a: mapif_parse_Mail_getattach(fd); break;
-		case 0x304b: mapif_parse_Mail_delete(fd); break;
-		case 0x304c: mapif_parse_Mail_return(fd); break;
-		case 0x304d: mapif_parse_Mail_send(fd); break;
-		default:
-			return 0;
-	}
-	return 1;
+    switch (RFIFOW(fd,0)) {
+        case 0x3048:
+            mapif_parse_Mail_requestinbox(fd);
+            break;
+        case 0x3049:
+            mapif_parse_Mail_read(fd);
+            break;
+        case 0x304a:
+            mapif_parse_Mail_getattach(fd);
+            break;
+        case 0x304b:
+            mapif_parse_Mail_delete(fd);
+            break;
+        case 0x304c:
+            mapif_parse_Mail_return(fd);
+            break;
+        case 0x304d:
+            mapif_parse_Mail_send(fd);
+            break;
+        default:
+            return 0;
+    }
+    return 1;
 }
 
 int inter_mail_sql_init(void)
 {
-	return 1;
+    return 1;
 }
 
 void inter_mail_sql_final(void)
 {
-	return;
+    return;
 }

+ 2 - 2
src/char/int_mail.h

@@ -5,12 +5,12 @@
 #define _INT_MAIL_SQL_H_
 
 int inter_mail_parse_frommap(int fd);
-void mail_sendmail(int send_id, const char* send_name, int dest_id, const char* dest_name, const char* title, const char* body, int zeny, struct item *item);
+void mail_sendmail(int send_id, const char *send_name, int dest_id, const char *dest_name, const char *title, const char *body, int zeny, struct item *item);
 
 int inter_mail_sql_init(void);
 void inter_mail_sql_final(void);
 
-int mail_savemessage(struct mail_message* msg);
+int mail_savemessage(struct mail_message *msg);
 void mapif_Mail_new(struct mail_message *msg);
 
 #endif /* _INT_MAIL_SQL_H_ */

+ 138 - 128
src/char/int_mercenary.c

@@ -17,185 +17,188 @@
 
 bool mercenary_owner_fromsql(int char_id, struct mmo_charstatus *status)
 {
-	char* data;
-
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `merc_id`, `arch_calls`, `arch_faith`, `spear_calls`, `spear_faith`, `sword_calls`, `sword_faith` FROM `%s` WHERE `char_id` = '%d'", mercenary_owner_db, char_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-
-	if( SQL_SUCCESS != Sql_NextRow(sql_handle) )
-	{
-		Sql_FreeResult(sql_handle);
-		return false;
-	}
-
-	Sql_GetData(sql_handle,  0, &data, NULL); status->mer_id = atoi(data);
-	Sql_GetData(sql_handle,  1, &data, NULL); status->arch_calls = atoi(data);
-	Sql_GetData(sql_handle,  2, &data, NULL); status->arch_faith = atoi(data);
-	Sql_GetData(sql_handle,  3, &data, NULL); status->spear_calls = atoi(data);
-	Sql_GetData(sql_handle,  4, &data, NULL); status->spear_faith = atoi(data);
-	Sql_GetData(sql_handle,  5, &data, NULL); status->sword_calls = atoi(data);
-	Sql_GetData(sql_handle,  6, &data, NULL); status->sword_faith = atoi(data);
-	Sql_FreeResult(sql_handle);
-
-	return true;
+    char *data;
+
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `merc_id`, `arch_calls`, `arch_faith`, `spear_calls`, `spear_faith`, `sword_calls`, `sword_faith` FROM `%s` WHERE `char_id` = '%d'", mercenary_owner_db, char_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+
+    if (SQL_SUCCESS != Sql_NextRow(sql_handle)) {
+        Sql_FreeResult(sql_handle);
+        return false;
+    }
+
+    Sql_GetData(sql_handle,  0, &data, NULL);
+    status->mer_id = atoi(data);
+    Sql_GetData(sql_handle,  1, &data, NULL);
+    status->arch_calls = atoi(data);
+    Sql_GetData(sql_handle,  2, &data, NULL);
+    status->arch_faith = atoi(data);
+    Sql_GetData(sql_handle,  3, &data, NULL);
+    status->spear_calls = atoi(data);
+    Sql_GetData(sql_handle,  4, &data, NULL);
+    status->spear_faith = atoi(data);
+    Sql_GetData(sql_handle,  5, &data, NULL);
+    status->sword_calls = atoi(data);
+    Sql_GetData(sql_handle,  6, &data, NULL);
+    status->sword_faith = atoi(data);
+    Sql_FreeResult(sql_handle);
+
+    return true;
 }
 
 bool mercenary_owner_tosql(int char_id, struct mmo_charstatus *status)
 {
-	if( SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `%s` (`char_id`, `merc_id`, `arch_calls`, `arch_faith`, `spear_calls`, `spear_faith`, `sword_calls`, `sword_faith`) VALUES ('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')",
-		mercenary_owner_db, char_id, status->mer_id, status->arch_calls, status->arch_faith, status->spear_calls, status->spear_faith, status->sword_calls, status->sword_faith) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
+    if (SQL_ERROR == Sql_Query(sql_handle, "REPLACE INTO `%s` (`char_id`, `merc_id`, `arch_calls`, `arch_faith`, `spear_calls`, `spear_faith`, `sword_calls`, `sword_faith`) VALUES ('%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')",
+                               mercenary_owner_db, char_id, status->mer_id, status->arch_calls, status->arch_faith, status->spear_calls, status->spear_faith, status->sword_calls, status->sword_faith)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
 
-	return true;
+    return true;
 }
 
 bool mercenary_owner_delete(int char_id)
 {
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id` = '%d'", mercenary_owner_db, char_id) )
-		Sql_ShowDebug(sql_handle);
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id` = '%d'", mercenary_owner_db, char_id))
+        Sql_ShowDebug(sql_handle);
 
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id` = '%d'", mercenary_db, char_id) )
-		Sql_ShowDebug(sql_handle);
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `char_id` = '%d'", mercenary_db, char_id))
+        Sql_ShowDebug(sql_handle);
 
-	return true;
+    return true;
 }
 
-bool mapif_mercenary_save(struct s_mercenary* merc)
+bool mapif_mercenary_save(struct s_mercenary *merc)
 {
-	bool flag = true;
+    bool flag = true;
 
-	if( merc->mercenary_id == 0 )
-	{ // Create new DB entry
-		if( SQL_ERROR == Sql_Query(sql_handle,
-			"INSERT INTO `%s` (`char_id`,`class`,`hp`,`sp`,`kill_counter`,`life_time`) VALUES ('%d','%d','%d','%d','%u','%u')",
-			mercenary_db, merc->char_id, merc->class_, merc->hp, merc->sp, merc->kill_count, merc->life_time) )
-		{
-			Sql_ShowDebug(sql_handle);
-			flag = false;
-		}
-		else
-			merc->mercenary_id = (int)Sql_LastInsertId(sql_handle);
-	}
-	else if( SQL_ERROR == Sql_Query(sql_handle,
-		"UPDATE `%s` SET `char_id` = '%d', `class` = '%d', `hp` = '%d', `sp` = '%d', `kill_counter` = '%u', `life_time` = '%u' WHERE `mer_id` = '%d'",
-		mercenary_db, merc->char_id, merc->class_, merc->hp, merc->sp, merc->kill_count, merc->life_time, merc->mercenary_id) )
-	{ // Update DB entry
-		Sql_ShowDebug(sql_handle);
-		flag = false;
-	}
+    if (merc->mercenary_id == 0) {
+        // Create new DB entry
+        if (SQL_ERROR == Sql_Query(sql_handle,
+                                   "INSERT INTO `%s` (`char_id`,`class`,`hp`,`sp`,`kill_counter`,`life_time`) VALUES ('%d','%d','%d','%d','%u','%u')",
+                                   mercenary_db, merc->char_id, merc->class_, merc->hp, merc->sp, merc->kill_count, merc->life_time)) {
+            Sql_ShowDebug(sql_handle);
+            flag = false;
+        } else
+            merc->mercenary_id = (int)Sql_LastInsertId(sql_handle);
+    } else if (SQL_ERROR == Sql_Query(sql_handle,
+                                      "UPDATE `%s` SET `char_id` = '%d', `class` = '%d', `hp` = '%d', `sp` = '%d', `kill_counter` = '%u', `life_time` = '%u' WHERE `mer_id` = '%d'",
+                                      mercenary_db, merc->char_id, merc->class_, merc->hp, merc->sp, merc->kill_count, merc->life_time, merc->mercenary_id)) {
+        // Update DB entry
+        Sql_ShowDebug(sql_handle);
+        flag = false;
+    }
 
-	return flag;
+    return flag;
 }
 
 bool mapif_mercenary_load(int merc_id, int char_id, struct s_mercenary *merc)
 {
-	char* data;
+    char *data;
+
+    memset(merc, 0, sizeof(struct s_mercenary));
+    merc->mercenary_id = merc_id;
+    merc->char_id = char_id;
 
-	memset(merc, 0, sizeof(struct s_mercenary));
-	merc->mercenary_id = merc_id;
-	merc->char_id = char_id;
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `class`, `hp`, `sp`, `kill_counter`, `life_time` FROM `%s` WHERE `mer_id` = '%d' AND `char_id` = '%d'", mercenary_db, merc_id, char_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
 
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `class`, `hp`, `sp`, `kill_counter`, `life_time` FROM `%s` WHERE `mer_id` = '%d' AND `char_id` = '%d'", mercenary_db, merc_id, char_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
+    if (SQL_SUCCESS != Sql_NextRow(sql_handle)) {
+        Sql_FreeResult(sql_handle);
+        return false;
+    }
 
-	if( SQL_SUCCESS != Sql_NextRow(sql_handle) )
-	{
-		Sql_FreeResult(sql_handle);
-		return false;
-	}
+    Sql_GetData(sql_handle,  0, &data, NULL);
+    merc->class_ = atoi(data);
+    Sql_GetData(sql_handle,  1, &data, NULL);
+    merc->hp = atoi(data);
+    Sql_GetData(sql_handle,  2, &data, NULL);
+    merc->sp = atoi(data);
+    Sql_GetData(sql_handle,  3, &data, NULL);
+    merc->kill_count = atoi(data);
+    Sql_GetData(sql_handle,  4, &data, NULL);
+    merc->life_time = atoi(data);
+    Sql_FreeResult(sql_handle);
+    if (save_log)
+        ShowInfo("Mercenary loaded (%d - %d).\n", merc->mercenary_id, merc->char_id);
 
-	Sql_GetData(sql_handle,  0, &data, NULL); merc->class_ = atoi(data);
-	Sql_GetData(sql_handle,  1, &data, NULL); merc->hp = atoi(data);
-	Sql_GetData(sql_handle,  2, &data, NULL); merc->sp = atoi(data);
-	Sql_GetData(sql_handle,  3, &data, NULL); merc->kill_count = atoi(data);
-	Sql_GetData(sql_handle,  4, &data, NULL); merc->life_time = atoi(data);
-	Sql_FreeResult(sql_handle);
-	if( save_log )
-		ShowInfo("Mercenary loaded (%d - %d).\n", merc->mercenary_id, merc->char_id);
-	
-	return true;
+    return true;
 }
 
 bool mapif_mercenary_delete(int merc_id)
 {
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `mer_id` = '%d'", mercenary_db, merc_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `mer_id` = '%d'", mercenary_db, merc_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
 
-	return true;
+    return true;
 }
 
 static void mapif_mercenary_send(int fd, struct s_mercenary *merc, unsigned char flag)
 {
-	int size = sizeof(struct s_mercenary) + 5;
+    int size = sizeof(struct s_mercenary) + 5;
 
-	WFIFOHEAD(fd,size);
-	WFIFOW(fd,0) = 0x3870;
-	WFIFOW(fd,2) = size;
-	WFIFOB(fd,4) = flag;
-	memcpy(WFIFOP(fd,5),merc,sizeof(struct s_mercenary));
-	WFIFOSET(fd,size);
+    WFIFOHEAD(fd,size);
+    WFIFOW(fd,0) = 0x3870;
+    WFIFOW(fd,2) = size;
+    WFIFOB(fd,4) = flag;
+    memcpy(WFIFOP(fd,5),merc,sizeof(struct s_mercenary));
+    WFIFOSET(fd,size);
 }
 
-static void mapif_parse_mercenary_create(int fd, struct s_mercenary* merc)
+static void mapif_parse_mercenary_create(int fd, struct s_mercenary *merc)
 {
-	bool result = mapif_mercenary_save(merc);
-	mapif_mercenary_send(fd, merc, result);
+    bool result = mapif_mercenary_save(merc);
+    mapif_mercenary_send(fd, merc, result);
 }
 
 static void mapif_parse_mercenary_load(int fd, int merc_id, int char_id)
 {
-	struct s_mercenary merc;
-	bool result = mapif_mercenary_load(merc_id, char_id, &merc);
-	mapif_mercenary_send(fd, &merc, result);
+    struct s_mercenary merc;
+    bool result = mapif_mercenary_load(merc_id, char_id, &merc);
+    mapif_mercenary_send(fd, &merc, result);
 }
 
 static void mapif_mercenary_deleted(int fd, unsigned char flag)
 {
-	WFIFOHEAD(fd,3);
-	WFIFOW(fd,0) = 0x3871;
-	WFIFOB(fd,2) = flag;
-	WFIFOSET(fd,3);
+    WFIFOHEAD(fd,3);
+    WFIFOW(fd,0) = 0x3871;
+    WFIFOB(fd,2) = flag;
+    WFIFOSET(fd,3);
 }
 
 static void mapif_parse_mercenary_delete(int fd, int merc_id)
 {
-	bool result = mapif_mercenary_delete(merc_id);
-	mapif_mercenary_deleted(fd, result);
+    bool result = mapif_mercenary_delete(merc_id);
+    mapif_mercenary_deleted(fd, result);
 }
 
 static void mapif_mercenary_saved(int fd, unsigned char flag)
 {
-	WFIFOHEAD(fd,3);
-	WFIFOW(fd,0) = 0x3872;
-	WFIFOB(fd,2) = flag;
-	WFIFOSET(fd,3);
+    WFIFOHEAD(fd,3);
+    WFIFOW(fd,0) = 0x3872;
+    WFIFOB(fd,2) = flag;
+    WFIFOSET(fd,3);
 }
 
-static void mapif_parse_mercenary_save(int fd, struct s_mercenary* merc)
+static void mapif_parse_mercenary_save(int fd, struct s_mercenary *merc)
 {
-	bool result = mapif_mercenary_save(merc);
-	mapif_mercenary_saved(fd, result);
+    bool result = mapif_mercenary_save(merc);
+    mapif_mercenary_saved(fd, result);
 }
 
 int inter_mercenary_sql_init(void)
 {
-	return 0;
+    return 0;
 }
 void inter_mercenary_sql_final(void)
 {
-	return;
+    return;
 }
 
 /*==========================================
@@ -203,16 +206,23 @@ void inter_mercenary_sql_final(void)
  *------------------------------------------*/
 int inter_mercenary_parse_frommap(int fd)
 {
-	unsigned short cmd = RFIFOW(fd,0);
-
-	switch( cmd )
-	{
-		case 0x3070: mapif_parse_mercenary_create(fd, (struct s_mercenary*)RFIFOP(fd,4)); break;
-		case 0x3071: mapif_parse_mercenary_load(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6)); break;
-		case 0x3072: mapif_parse_mercenary_delete(fd, (int)RFIFOL(fd,2)); break;
-		case 0x3073: mapif_parse_mercenary_save(fd, (struct s_mercenary*)RFIFOP(fd,4)); break;
-		default:
-			return 0;
-	}
-	return 1;
+    unsigned short cmd = RFIFOW(fd,0);
+
+    switch (cmd) {
+        case 0x3070:
+            mapif_parse_mercenary_create(fd, (struct s_mercenary *)RFIFOP(fd,4));
+            break;
+        case 0x3071:
+            mapif_parse_mercenary_load(fd, (int)RFIFOL(fd,2), (int)RFIFOL(fd,6));
+            break;
+        case 0x3072:
+            mapif_parse_mercenary_delete(fd, (int)RFIFOL(fd,2));
+            break;
+        case 0x3073:
+            mapif_parse_mercenary_save(fd, (struct s_mercenary *)RFIFOP(fd,4));
+            break;
+        default:
+            return 0;
+    }
+    return 1;
 }

File diff suppressed because it is too large
+ 570 - 569
src/char/int_party.c


+ 6 - 6
src/char/int_party.h

@@ -6,12 +6,12 @@
 
 //Party Flags on what to save/delete.
 enum {
-	PS_CREATE = 0x01, //Create a new party entry (index holds leader's info) 
-	PS_BASIC = 0x02, //Update basic party info.
-	PS_LEADER = 0x04, //Update party's leader
-	PS_ADDMEMBER = 0x08, //Specify new party member (index specifies which party member)
-	PS_DELMEMBER = 0x10, //Specify member that left (index specifies which party member)
-	PS_BREAK = 0x20, //Specify that this party must be deleted.
+    PS_CREATE = 0x01, //Create a new party entry (index holds leader's info)
+    PS_BASIC = 0x02, //Update basic party info.
+    PS_LEADER = 0x04, //Update party's leader
+    PS_ADDMEMBER = 0x08, //Specify new party member (index specifies which party member)
+    PS_DELMEMBER = 0x10, //Specify member that left (index specifies which party member)
+    PS_BREAK = 0x20, //Specify that this party must be deleted.
 };
 
 struct party;

+ 266 - 239
src/char/int_pet.c

@@ -18,292 +18,319 @@
 struct s_pet *pet_pt;
 
 //---------------------------------------------------------
-int inter_pet_tosql(int pet_id, struct s_pet* p)
+int inter_pet_tosql(int pet_id, struct s_pet *p)
 {
-	//`pet` (`pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`)
-	char esc_name[NAME_LENGTH*2+1];// escaped pet name
-
-	Sql_EscapeStringLen(sql_handle, esc_name, p->name, strnlen(p->name, NAME_LENGTH));
-	p->hungry = cap_value(p->hungry, 0, 100);
-	p->intimate = cap_value(p->intimate, 0, 1000);
-
-	if( pet_id == -1 )
-	{// New pet.
-		if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` "
-			"(`class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`) "
-			"VALUES ('%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')",
-			pet_db, p->class_, esc_name, p->account_id, p->char_id, p->level, p->egg_id,
-			p->equip, p->intimate, p->hungry, p->rename_flag, p->incuvate) )
-		{
-			Sql_ShowDebug(sql_handle);
-			return 0;
-		}
-		p->pet_id = (int)Sql_LastInsertId(sql_handle);
-	}
-	else
-	{// Update pet.
-		if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `class`='%d',`name`='%s',`account_id`='%d',`char_id`='%d',`level`='%d',`egg_id`='%d',`equip`='%d',`intimate`='%d',`hungry`='%d',`rename_flag`='%d',`incuvate`='%d' WHERE `pet_id`='%d'",
-			pet_db, p->class_, esc_name, p->account_id, p->char_id, p->level, p->egg_id,
-			p->equip, p->intimate, p->hungry, p->rename_flag, p->incuvate, p->pet_id) )
-		{
-			Sql_ShowDebug(sql_handle);
-			return 0;
-		}
-	}
-
-	if (save_log)
-		ShowInfo("Pet saved %d - %s.\n", pet_id, p->name);
-	return 1;
+    //`pet` (`pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`)
+    char esc_name[NAME_LENGTH*2+1];// escaped pet name
+
+    Sql_EscapeStringLen(sql_handle, esc_name, p->name, strnlen(p->name, NAME_LENGTH));
+    p->hungry = cap_value(p->hungry, 0, 100);
+    p->intimate = cap_value(p->intimate, 0, 1000);
+
+    if (pet_id == -1) {
+        // New pet.
+        if (SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s` "
+                                   "(`class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`) "
+                                   "VALUES ('%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d')",
+                                   pet_db, p->class_, esc_name, p->account_id, p->char_id, p->level, p->egg_id,
+                                   p->equip, p->intimate, p->hungry, p->rename_flag, p->incuvate)) {
+            Sql_ShowDebug(sql_handle);
+            return 0;
+        }
+        p->pet_id = (int)Sql_LastInsertId(sql_handle);
+    } else {
+        // Update pet.
+        if (SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `class`='%d',`name`='%s',`account_id`='%d',`char_id`='%d',`level`='%d',`egg_id`='%d',`equip`='%d',`intimate`='%d',`hungry`='%d',`rename_flag`='%d',`incuvate`='%d' WHERE `pet_id`='%d'",
+                                   pet_db, p->class_, esc_name, p->account_id, p->char_id, p->level, p->egg_id,
+                                   p->equip, p->intimate, p->hungry, p->rename_flag, p->incuvate, p->pet_id)) {
+            Sql_ShowDebug(sql_handle);
+            return 0;
+        }
+    }
+
+    if (save_log)
+        ShowInfo("Pet saved %d - %s.\n", pet_id, p->name);
+    return 1;
 }
 
-int inter_pet_fromsql(int pet_id, struct s_pet* p)
+int inter_pet_fromsql(int pet_id, struct s_pet *p)
 {
-	char* data;
-	size_t len;
+    char *data;
+    size_t len;
 
 #ifdef NOISY
-	ShowInfo("Loading pet (%d)...\n",pet_id);
+    ShowInfo("Loading pet (%d)...\n",pet_id);
 #endif
-	memset(p, 0, sizeof(struct s_pet));
-
-	//`pet` (`pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`)
-
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate` FROM `%s` WHERE `pet_id`='%d'", pet_db, pet_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return 0;
-	}
-
-	if( SQL_SUCCESS == Sql_NextRow(sql_handle) )
-	{
-		p->pet_id = pet_id;
-		Sql_GetData(sql_handle,  1, &data, NULL); p->class_ = atoi(data);
-		Sql_GetData(sql_handle,  2, &data, &len); memcpy(p->name, data, min(len, NAME_LENGTH));
-		Sql_GetData(sql_handle,  3, &data, NULL); p->account_id = atoi(data);
-		Sql_GetData(sql_handle,  4, &data, NULL); p->char_id = atoi(data);
-		Sql_GetData(sql_handle,  5, &data, NULL); p->level = atoi(data);
-		Sql_GetData(sql_handle,  6, &data, NULL); p->egg_id = atoi(data);
-		Sql_GetData(sql_handle,  7, &data, NULL); p->equip = atoi(data);
-		Sql_GetData(sql_handle,  8, &data, NULL); p->intimate = atoi(data);
-		Sql_GetData(sql_handle,  9, &data, NULL); p->hungry = atoi(data);
-		Sql_GetData(sql_handle, 10, &data, NULL); p->rename_flag = atoi(data);
-		Sql_GetData(sql_handle, 11, &data, NULL); p->incuvate = atoi(data);
-
-		Sql_FreeResult(sql_handle);
-
-		p->hungry = cap_value(p->hungry, 0, 100);
-		p->intimate = cap_value(p->intimate, 0, 1000);
-
-		if( save_log )
-			ShowInfo("Pet loaded (%d - %s).\n", pet_id, p->name);
-	}
-	return 0;
+    memset(p, 0, sizeof(struct s_pet));
+
+    //`pet` (`pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate`)
+
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `pet_id`, `class`,`name`,`account_id`,`char_id`,`level`,`egg_id`,`equip`,`intimate`,`hungry`,`rename_flag`,`incuvate` FROM `%s` WHERE `pet_id`='%d'", pet_db, pet_id)) {
+        Sql_ShowDebug(sql_handle);
+        return 0;
+    }
+
+    if (SQL_SUCCESS == Sql_NextRow(sql_handle)) {
+        p->pet_id = pet_id;
+        Sql_GetData(sql_handle,  1, &data, NULL);
+        p->class_ = atoi(data);
+        Sql_GetData(sql_handle,  2, &data, &len);
+        memcpy(p->name, data, min(len, NAME_LENGTH));
+        Sql_GetData(sql_handle,  3, &data, NULL);
+        p->account_id = atoi(data);
+        Sql_GetData(sql_handle,  4, &data, NULL);
+        p->char_id = atoi(data);
+        Sql_GetData(sql_handle,  5, &data, NULL);
+        p->level = atoi(data);
+        Sql_GetData(sql_handle,  6, &data, NULL);
+        p->egg_id = atoi(data);
+        Sql_GetData(sql_handle,  7, &data, NULL);
+        p->equip = atoi(data);
+        Sql_GetData(sql_handle,  8, &data, NULL);
+        p->intimate = atoi(data);
+        Sql_GetData(sql_handle,  9, &data, NULL);
+        p->hungry = atoi(data);
+        Sql_GetData(sql_handle, 10, &data, NULL);
+        p->rename_flag = atoi(data);
+        Sql_GetData(sql_handle, 11, &data, NULL);
+        p->incuvate = atoi(data);
+
+        Sql_FreeResult(sql_handle);
+
+        p->hungry = cap_value(p->hungry, 0, 100);
+        p->intimate = cap_value(p->intimate, 0, 1000);
+
+        if (save_log)
+            ShowInfo("Pet loaded (%d - %s).\n", pet_id, p->name);
+    }
+    return 0;
 }
 //----------------------------------------------
 
-int inter_pet_sql_init(void){
-	//memory alloc
-	pet_pt = (struct s_pet*)aCalloc(sizeof(struct s_pet), 1);
-	return 0;
+int inter_pet_sql_init(void)
+{
+    //memory alloc
+    pet_pt = (struct s_pet *)aCalloc(sizeof(struct s_pet), 1);
+    return 0;
 }
-void inter_pet_sql_final(void){
-	if (pet_pt) aFree(pet_pt);
-	return;
+void inter_pet_sql_final(void)
+{
+    if (pet_pt) aFree(pet_pt);
+    return;
 }
 //----------------------------------
-int inter_pet_delete(int pet_id){
-	ShowInfo("delete pet request: %d...\n",pet_id);
+int inter_pet_delete(int pet_id)
+{
+    ShowInfo("delete pet request: %d...\n",pet_id);
 
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `pet_id`='%d'", pet_db, pet_id) )
-		Sql_ShowDebug(sql_handle);
-	return 0;
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `pet_id`='%d'", pet_db, pet_id))
+        Sql_ShowDebug(sql_handle);
+    return 0;
 }
 //------------------------------------------------------
 int mapif_pet_created(int fd, int account_id, struct s_pet *p)
 {
-	WFIFOHEAD(fd, 11);
-	WFIFOW(fd, 0) =0x3880;
-	WFIFOL(fd, 2) =account_id;
-	if(p!=NULL){
-		WFIFOB(fd, 6)=0;
-		WFIFOL(fd, 7) =p->pet_id;
-		ShowInfo("int_pet: created pet %d - %s\n", p->pet_id, p->name);
-	}else{
-		WFIFOB(fd, 6)=1;
-		WFIFOL(fd, 7)=0;
-	}
-	WFIFOSET(fd, 11);
-
-	return 0;
+    WFIFOHEAD(fd, 11);
+    WFIFOW(fd, 0) =0x3880;
+    WFIFOL(fd, 2) =account_id;
+    if (p!=NULL) {
+        WFIFOB(fd, 6)=0;
+        WFIFOL(fd, 7) =p->pet_id;
+        ShowInfo("int_pet: created pet %d - %s\n", p->pet_id, p->name);
+    } else {
+        WFIFOB(fd, 6)=1;
+        WFIFOL(fd, 7)=0;
+    }
+    WFIFOSET(fd, 11);
+
+    return 0;
 }
 
-int mapif_pet_info(int fd, int account_id, struct s_pet *p){
-	WFIFOHEAD(fd, sizeof(struct s_pet) + 9);
-	WFIFOW(fd, 0) =0x3881;
-	WFIFOW(fd, 2) =sizeof(struct s_pet) + 9;
-	WFIFOL(fd, 4) =account_id;
-	WFIFOB(fd, 8)=0;
-	memcpy(WFIFOP(fd, 9), p, sizeof(struct s_pet));
-	WFIFOSET(fd, WFIFOW(fd, 2));
-
-	return 0;
+int mapif_pet_info(int fd, int account_id, struct s_pet *p)
+{
+    WFIFOHEAD(fd, sizeof(struct s_pet) + 9);
+    WFIFOW(fd, 0) =0x3881;
+    WFIFOW(fd, 2) =sizeof(struct s_pet) + 9;
+    WFIFOL(fd, 4) =account_id;
+    WFIFOB(fd, 8)=0;
+    memcpy(WFIFOP(fd, 9), p, sizeof(struct s_pet));
+    WFIFOSET(fd, WFIFOW(fd, 2));
+
+    return 0;
 }
 
-int mapif_pet_noinfo(int fd, int account_id){
-	WFIFOHEAD(fd, sizeof(struct s_pet) + 9);
-	WFIFOW(fd, 0) =0x3881;
-	WFIFOW(fd, 2) =sizeof(struct s_pet) + 9;
-	WFIFOL(fd, 4) =account_id;
-	WFIFOB(fd, 8)=1;
-	memset(WFIFOP(fd, 9), 0, sizeof(struct s_pet));
-	WFIFOSET(fd, WFIFOW(fd, 2));
-
-	return 0;
+int mapif_pet_noinfo(int fd, int account_id)
+{
+    WFIFOHEAD(fd, sizeof(struct s_pet) + 9);
+    WFIFOW(fd, 0) =0x3881;
+    WFIFOW(fd, 2) =sizeof(struct s_pet) + 9;
+    WFIFOL(fd, 4) =account_id;
+    WFIFOB(fd, 8)=1;
+    memset(WFIFOP(fd, 9), 0, sizeof(struct s_pet));
+    WFIFOSET(fd, WFIFOW(fd, 2));
+
+    return 0;
 }
 
-int mapif_save_pet_ack(int fd, int account_id, int flag){
-	WFIFOHEAD(fd, 7);
-	WFIFOW(fd, 0) =0x3882;
-	WFIFOL(fd, 2) =account_id;
-	WFIFOB(fd, 6) =flag;
-	WFIFOSET(fd, 7);
+int mapif_save_pet_ack(int fd, int account_id, int flag)
+{
+    WFIFOHEAD(fd, 7);
+    WFIFOW(fd, 0) =0x3882;
+    WFIFOL(fd, 2) =account_id;
+    WFIFOB(fd, 6) =flag;
+    WFIFOSET(fd, 7);
 
-	return 0;
+    return 0;
 }
 
-int mapif_delete_pet_ack(int fd, int flag){
-	WFIFOHEAD(fd, 3);
-	WFIFOW(fd, 0) =0x3883;
-	WFIFOB(fd, 2) =flag;
-	WFIFOSET(fd, 3);
+int mapif_delete_pet_ack(int fd, int flag)
+{
+    WFIFOHEAD(fd, 3);
+    WFIFOW(fd, 0) =0x3883;
+    WFIFOB(fd, 2) =flag;
+    WFIFOSET(fd, 3);
 
-	return 0;
+    return 0;
 }
 
 int mapif_create_pet(int fd, int account_id, int char_id, short pet_class, short pet_lv, short pet_egg_id,
-	short pet_equip, short intimate, short hungry, char rename_flag, char incuvate, char *pet_name)
+                     short pet_equip, short intimate, short hungry, char rename_flag, char incuvate, char *pet_name)
 {
-	memset(pet_pt, 0, sizeof(struct s_pet));
-	strncpy(pet_pt->name, pet_name, NAME_LENGTH);
-	if(incuvate == 1)
-		pet_pt->account_id = pet_pt->char_id = 0;
-	else {
-		pet_pt->account_id = account_id;
-		pet_pt->char_id = char_id;
-	}
-	pet_pt->class_ = pet_class;
-	pet_pt->level = pet_lv;
-	pet_pt->egg_id = pet_egg_id;
-	pet_pt->equip = pet_equip;
-	pet_pt->intimate = intimate;
-	pet_pt->hungry = hungry;
-	pet_pt->rename_flag = rename_flag;
-	pet_pt->incuvate = incuvate;
-
-	if(pet_pt->hungry < 0)
-		pet_pt->hungry = 0;
-	else if(pet_pt->hungry > 100)
-		pet_pt->hungry = 100;
-	if(pet_pt->intimate < 0)
-		pet_pt->intimate = 0;
-	else if(pet_pt->intimate > 1000)
-		pet_pt->intimate = 1000;
-
-	pet_pt->pet_id = -1; //Signal NEW pet.
-	if (inter_pet_tosql(pet_pt->pet_id,pet_pt))
-		mapif_pet_created(fd, account_id, pet_pt);
-	else	//Failed...
-		mapif_pet_created(fd, account_id, NULL);
-
-	return 0;
+    memset(pet_pt, 0, sizeof(struct s_pet));
+    strncpy(pet_pt->name, pet_name, NAME_LENGTH);
+    if (incuvate == 1)
+        pet_pt->account_id = pet_pt->char_id = 0;
+    else {
+        pet_pt->account_id = account_id;
+        pet_pt->char_id = char_id;
+    }
+    pet_pt->class_ = pet_class;
+    pet_pt->level = pet_lv;
+    pet_pt->egg_id = pet_egg_id;
+    pet_pt->equip = pet_equip;
+    pet_pt->intimate = intimate;
+    pet_pt->hungry = hungry;
+    pet_pt->rename_flag = rename_flag;
+    pet_pt->incuvate = incuvate;
+
+    if (pet_pt->hungry < 0)
+        pet_pt->hungry = 0;
+    else if (pet_pt->hungry > 100)
+        pet_pt->hungry = 100;
+    if (pet_pt->intimate < 0)
+        pet_pt->intimate = 0;
+    else if (pet_pt->intimate > 1000)
+        pet_pt->intimate = 1000;
+
+    pet_pt->pet_id = -1; //Signal NEW pet.
+    if (inter_pet_tosql(pet_pt->pet_id,pet_pt))
+        mapif_pet_created(fd, account_id, pet_pt);
+    else    //Failed...
+        mapif_pet_created(fd, account_id, NULL);
+
+    return 0;
 }
 
-int mapif_load_pet(int fd, int account_id, int char_id, int pet_id){
-	memset(pet_pt, 0, sizeof(struct s_pet));
-
-	inter_pet_fromsql(pet_id, pet_pt);
-
-	if(pet_pt!=NULL) {
-		if(pet_pt->incuvate == 1) {
-			pet_pt->account_id = pet_pt->char_id = 0;
-			mapif_pet_info(fd, account_id, pet_pt);
-		}
-		else if(account_id == pet_pt->account_id && char_id == pet_pt->char_id)
-			mapif_pet_info(fd, account_id, pet_pt);
-		else
-			mapif_pet_noinfo(fd, account_id);
-	}
-	else
-		mapif_pet_noinfo(fd, account_id);
-
-	return 0;
+int mapif_load_pet(int fd, int account_id, int char_id, int pet_id)
+{
+    memset(pet_pt, 0, sizeof(struct s_pet));
+
+    inter_pet_fromsql(pet_id, pet_pt);
+
+    if (pet_pt!=NULL) {
+        if (pet_pt->incuvate == 1) {
+            pet_pt->account_id = pet_pt->char_id = 0;
+            mapif_pet_info(fd, account_id, pet_pt);
+        } else if (account_id == pet_pt->account_id && char_id == pet_pt->char_id)
+            mapif_pet_info(fd, account_id, pet_pt);
+        else
+            mapif_pet_noinfo(fd, account_id);
+    } else
+        mapif_pet_noinfo(fd, account_id);
+
+    return 0;
 }
 
-int mapif_save_pet(int fd, int account_id, struct s_pet *data) {
-	//here process pet save request.
-	int len;
-	RFIFOHEAD(fd);
-	len=RFIFOW(fd, 2);
-	if(sizeof(struct s_pet)!=len-8) {
-		ShowError("inter pet: data size error %d %d\n", sizeof(struct s_pet), len-8);
-	}
-
-	else{
-		if(data->hungry < 0)
-			data->hungry = 0;
-		else if(data->hungry > 100)
-			data->hungry = 100;
-		if(data->intimate < 0)
-			data->intimate = 0;
-		else if(data->intimate > 1000)
-			data->intimate = 1000;
-		inter_pet_tosql(data->pet_id,data);
-		mapif_save_pet_ack(fd, account_id, 0);
-	}
-
-	return 0;
+int mapif_save_pet(int fd, int account_id, struct s_pet *data)
+{
+    //here process pet save request.
+    int len;
+    RFIFOHEAD(fd);
+    len=RFIFOW(fd, 2);
+    if (sizeof(struct s_pet)!=len-8) {
+        ShowError("inter pet: data size error %d %d\n", sizeof(struct s_pet), len-8);
+    }
+
+    else {
+        if (data->hungry < 0)
+            data->hungry = 0;
+        else if (data->hungry > 100)
+            data->hungry = 100;
+        if (data->intimate < 0)
+            data->intimate = 0;
+        else if (data->intimate > 1000)
+            data->intimate = 1000;
+        inter_pet_tosql(data->pet_id,data);
+        mapif_save_pet_ack(fd, account_id, 0);
+    }
+
+    return 0;
 }
 
-int mapif_delete_pet(int fd, int pet_id){
-	mapif_delete_pet_ack(fd, inter_pet_delete(pet_id));
+int mapif_delete_pet(int fd, int pet_id)
+{
+    mapif_delete_pet_ack(fd, inter_pet_delete(pet_id));
 
-	return 0;
+    return 0;
 }
 
-int mapif_parse_CreatePet(int fd){
-	RFIFOHEAD(fd);
-	mapif_create_pet(fd, RFIFOL(fd, 2), RFIFOL(fd, 6), RFIFOW(fd, 10), RFIFOW(fd, 12), RFIFOW(fd, 14), RFIFOW(fd, 16), RFIFOW(fd, 18),
-		RFIFOW(fd, 20), RFIFOB(fd, 22), RFIFOB(fd, 23), (char*)RFIFOP(fd, 24));
-	return 0;
+int mapif_parse_CreatePet(int fd)
+{
+    RFIFOHEAD(fd);
+    mapif_create_pet(fd, RFIFOL(fd, 2), RFIFOL(fd, 6), RFIFOW(fd, 10), RFIFOW(fd, 12), RFIFOW(fd, 14), RFIFOW(fd, 16), RFIFOW(fd, 18),
+                     RFIFOW(fd, 20), RFIFOB(fd, 22), RFIFOB(fd, 23), (char *)RFIFOP(fd, 24));
+    return 0;
 }
 
-int mapif_parse_LoadPet(int fd){
-	RFIFOHEAD(fd);
-	mapif_load_pet(fd, RFIFOL(fd, 2), RFIFOL(fd, 6), RFIFOL(fd, 10));
-	return 0;
+int mapif_parse_LoadPet(int fd)
+{
+    RFIFOHEAD(fd);
+    mapif_load_pet(fd, RFIFOL(fd, 2), RFIFOL(fd, 6), RFIFOL(fd, 10));
+    return 0;
 }
 
-int mapif_parse_SavePet(int fd){
-	RFIFOHEAD(fd);
-	mapif_save_pet(fd, RFIFOL(fd, 4), (struct s_pet *) RFIFOP(fd, 8));
-	return 0;
+int mapif_parse_SavePet(int fd)
+{
+    RFIFOHEAD(fd);
+    mapif_save_pet(fd, RFIFOL(fd, 4), (struct s_pet *) RFIFOP(fd, 8));
+    return 0;
 }
 
-int mapif_parse_DeletePet(int fd){
-	RFIFOHEAD(fd);
-	mapif_delete_pet(fd, RFIFOL(fd, 2));
-	return 0;
+int mapif_parse_DeletePet(int fd)
+{
+    RFIFOHEAD(fd);
+    mapif_delete_pet(fd, RFIFOL(fd, 2));
+    return 0;
 }
 
-int inter_pet_parse_frommap(int fd){
-	RFIFOHEAD(fd);
-	switch(RFIFOW(fd, 0)){
-	case 0x3080: mapif_parse_CreatePet(fd); break;
-	case 0x3081: mapif_parse_LoadPet(fd); break;
-	case 0x3082: mapif_parse_SavePet(fd); break;
-	case 0x3083: mapif_parse_DeletePet(fd); break;
-	default:
-		return 0;
-	}
-	return 1;
+int inter_pet_parse_frommap(int fd)
+{
+    RFIFOHEAD(fd);
+    switch (RFIFOW(fd, 0)) {
+        case 0x3080:
+            mapif_parse_CreatePet(fd);
+            break;
+        case 0x3081:
+            mapif_parse_LoadPet(fd);
+            break;
+        case 0x3082:
+            mapif_parse_SavePet(fd);
+            break;
+        case 0x3083:
+            mapif_parse_DeletePet(fd);
+            break;
+        default:
+            return 0;
+    }
+    return 1;
 }

+ 122 - 128
src/char/int_quest.c

@@ -21,164 +21,158 @@
 //Load entire questlog for a character
 int mapif_quests_fromsql(int char_id, struct quest questlog[])
 {
-	int i;
-	struct quest tmp_quest;
-	SqlStmt * stmt;
-
-	stmt = SqlStmt_Malloc(sql_handle);
-	if( stmt == NULL )
-	{
-		SqlStmt_ShowDebug(stmt);
-		return 0;
-	}
-
-	memset(&tmp_quest, 0, sizeof(struct quest));
-
-	if( SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT `quest_id`, `state`, `time`, `count1`, `count2`, `count3` FROM `%s` WHERE `char_id`=? LIMIT %d", quest_db, MAX_QUEST_DB)
-	||	SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0)
-	||	SQL_ERROR == SqlStmt_Execute(stmt)
-	||	SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT,    &tmp_quest.quest_id, 0, NULL, NULL)
-	||	SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_INT,    &tmp_quest.state, 0, NULL, NULL)
-	||	SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_UINT,   &tmp_quest.time, 0, NULL, NULL)
-	||	SQL_ERROR == SqlStmt_BindColumn(stmt, 3, SQLDT_INT,    &tmp_quest.count[0], 0, NULL, NULL)
-	||	SQL_ERROR == SqlStmt_BindColumn(stmt, 4, SQLDT_INT,    &tmp_quest.count[1], 0, NULL, NULL)
-	||	SQL_ERROR == SqlStmt_BindColumn(stmt, 5, SQLDT_INT,    &tmp_quest.count[2], 0, NULL, NULL) )
-		SqlStmt_ShowDebug(stmt);
-
-	for( i = 0; i < MAX_QUEST_DB && SQL_SUCCESS == SqlStmt_NextRow(stmt); ++i )
-		memcpy(&questlog[i], &tmp_quest, sizeof(tmp_quest));
-
-	SqlStmt_Free(stmt);
-	return i;
+    int i;
+    struct quest tmp_quest;
+    SqlStmt *stmt;
+
+    stmt = SqlStmt_Malloc(sql_handle);
+    if (stmt == NULL) {
+        SqlStmt_ShowDebug(stmt);
+        return 0;
+    }
+
+    memset(&tmp_quest, 0, sizeof(struct quest));
+
+    if (SQL_ERROR == SqlStmt_Prepare(stmt, "SELECT `quest_id`, `state`, `time`, `count1`, `count2`, `count3` FROM `%s` WHERE `char_id`=? LIMIT %d", quest_db, MAX_QUEST_DB)
+        ||  SQL_ERROR == SqlStmt_BindParam(stmt, 0, SQLDT_INT, &char_id, 0)
+        ||  SQL_ERROR == SqlStmt_Execute(stmt)
+        ||  SQL_ERROR == SqlStmt_BindColumn(stmt, 0, SQLDT_INT,    &tmp_quest.quest_id, 0, NULL, NULL)
+        ||  SQL_ERROR == SqlStmt_BindColumn(stmt, 1, SQLDT_INT,    &tmp_quest.state, 0, NULL, NULL)
+        ||  SQL_ERROR == SqlStmt_BindColumn(stmt, 2, SQLDT_UINT,   &tmp_quest.time, 0, NULL, NULL)
+        ||  SQL_ERROR == SqlStmt_BindColumn(stmt, 3, SQLDT_INT,    &tmp_quest.count[0], 0, NULL, NULL)
+        ||  SQL_ERROR == SqlStmt_BindColumn(stmt, 4, SQLDT_INT,    &tmp_quest.count[1], 0, NULL, NULL)
+        ||  SQL_ERROR == SqlStmt_BindColumn(stmt, 5, SQLDT_INT,    &tmp_quest.count[2], 0, NULL, NULL))
+        SqlStmt_ShowDebug(stmt);
+
+    for (i = 0; i < MAX_QUEST_DB && SQL_SUCCESS == SqlStmt_NextRow(stmt); ++i)
+        memcpy(&questlog[i], &tmp_quest, sizeof(tmp_quest));
+
+    SqlStmt_Free(stmt);
+    return i;
 }
 
 //Delete a quest
 bool mapif_quest_delete(int char_id, int quest_id)
 {
-	if ( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `quest_id` = '%d' AND `char_id` = '%d'", quest_db, quest_id, char_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `quest_id` = '%d' AND `char_id` = '%d'", quest_db, quest_id, char_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
 
-	return true;
+    return true;
 }
 
 //Add a quest to a questlog
 bool mapif_quest_add(int char_id, struct quest qd)
 {
-	if ( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s`(`quest_id`, `char_id`, `state`, `time`, `count1`, `count2`, `count3`) VALUES ('%d', '%d', '%d','%d', '%d', '%d', '%d')", quest_db, qd.quest_id, char_id, qd.state, qd.time, qd.count[0], qd.count[1], qd.count[2]) ) 
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
+    if (SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s`(`quest_id`, `char_id`, `state`, `time`, `count1`, `count2`, `count3`) VALUES ('%d', '%d', '%d','%d', '%d', '%d', '%d')", quest_db, qd.quest_id, char_id, qd.state, qd.time, qd.count[0], qd.count[1], qd.count[2])) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
 
-	return true;
+    return true;
 }
 
 //Update a questlog
 bool mapif_quest_update(int char_id, struct quest qd)
 {
-	if ( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `state`='%d', `count1`='%d', `count2`='%d', `count3`='%d' WHERE `quest_id` = '%d' AND `char_id` = '%d'", quest_db, qd.state, qd.count[0], qd.count[1], qd.count[2], qd.quest_id, char_id) ) 
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
+    if (SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `state`='%d', `count1`='%d', `count2`='%d', `count3`='%d' WHERE `quest_id` = '%d' AND `char_id` = '%d'", quest_db, qd.state, qd.count[0], qd.count[1], qd.count[2], qd.quest_id, char_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
 
-	return true;
+    return true;
 }
 
 //Save quests
 int mapif_parse_quest_save(int fd)
 {
-	int i, j, k, num2, num1 = (RFIFOW(fd,2)-8)/sizeof(struct quest);
-	int char_id = RFIFOL(fd,4);
-	struct quest qd1[MAX_QUEST_DB],qd2[MAX_QUEST_DB];
-	bool success = true;
-
-	memset(qd1, 0, sizeof(qd1));
-	memset(qd2, 0, sizeof(qd2));
-	if( num1 ) memcpy(&qd1, RFIFOP(fd,8), RFIFOW(fd,2)-8);
-	num2 = mapif_quests_fromsql(char_id, qd2);
-
-	for( i = 0; i < num1; i++ )
-	{
-		ARR_FIND( 0, num2, j, qd1[i].quest_id == qd2[j].quest_id );
-		if( j < num2 ) // Update existed quests
-		{	// Only states and counts are changable.
-			ARR_FIND( 0, MAX_QUEST_OBJECTIVES, k, qd1[i].count[k] != qd2[j].count[k] );
-			if( k != MAX_QUEST_OBJECTIVES || qd1[i].state != qd2[j].state )
-				success &= mapif_quest_update(char_id, qd1[i]);
-
-			if( j < (--num2) )
-			{
-				memmove(&qd2[j],&qd2[j+1],sizeof(struct quest)*(num2-j));
-				memset(&qd2[num2], 0, sizeof(struct quest));
-			}
-
-		}
-		else // Add new quests
-			success &= mapif_quest_add(char_id, qd1[i]);
-	}
-
-	for( i = 0; i < num2; i++ ) // Quests not in qd1 but in qd2 are to be erased.
-		success &= mapif_quest_delete(char_id, qd2[i].quest_id);
-
-	WFIFOHEAD(fd,7);
-	WFIFOW(fd,0) = 0x3861;
-	WFIFOL(fd,2) = char_id;
-	WFIFOB(fd,6) = success?1:0;
-	WFIFOSET(fd,7);
-
-	return 0;
+    int i, j, k, num2, num1 = (RFIFOW(fd,2)-8)/sizeof(struct quest);
+    int char_id = RFIFOL(fd,4);
+    struct quest qd1[MAX_QUEST_DB],qd2[MAX_QUEST_DB];
+    bool success = true;
+
+    memset(qd1, 0, sizeof(qd1));
+    memset(qd2, 0, sizeof(qd2));
+    if (num1) memcpy(&qd1, RFIFOP(fd,8), RFIFOW(fd,2)-8);
+    num2 = mapif_quests_fromsql(char_id, qd2);
+
+    for (i = 0; i < num1; i++) {
+        ARR_FIND(0, num2, j, qd1[i].quest_id == qd2[j].quest_id);
+        if (j < num2) { // Update existed quests
+            // Only states and counts are changable.
+            ARR_FIND(0, MAX_QUEST_OBJECTIVES, k, qd1[i].count[k] != qd2[j].count[k]);
+            if (k != MAX_QUEST_OBJECTIVES || qd1[i].state != qd2[j].state)
+                success &= mapif_quest_update(char_id, qd1[i]);
+
+            if (j < (--num2)) {
+                memmove(&qd2[j],&qd2[j+1],sizeof(struct quest)*(num2-j));
+                memset(&qd2[num2], 0, sizeof(struct quest));
+            }
+
+        } else // Add new quests
+            success &= mapif_quest_add(char_id, qd1[i]);
+    }
+
+    for (i = 0; i < num2; i++)  // Quests not in qd1 but in qd2 are to be erased.
+        success &= mapif_quest_delete(char_id, qd2[i].quest_id);
+
+    WFIFOHEAD(fd,7);
+    WFIFOW(fd,0) = 0x3861;
+    WFIFOL(fd,2) = char_id;
+    WFIFOB(fd,6) = success?1:0;
+    WFIFOSET(fd,7);
+
+    return 0;
 }
 
 //Send questlog to map server
 int mapif_parse_quest_load(int fd)
 {
-	int char_id = RFIFOL(fd,2);
-	struct quest tmp_questlog[MAX_QUEST_DB];
-	int num_quests, i, num_complete = 0;
-	int complete[MAX_QUEST_DB];
-
-	memset(tmp_questlog, 0, sizeof(tmp_questlog));
-	memset(complete, 0, sizeof(complete));
-
-	num_quests = mapif_quests_fromsql(char_id, tmp_questlog);
-
-	WFIFOHEAD(fd,num_quests*sizeof(struct quest)+8);
-	WFIFOW(fd,0) = 0x3860;
-	WFIFOW(fd,2) = num_quests*sizeof(struct quest)+8;
-	WFIFOL(fd,4) = char_id;
-
-	//Active and inactive quests
-	for( i = 0; i < num_quests; i++ )
-	{
-		if( tmp_questlog[i].state == Q_COMPLETE )
-		{
-			complete[num_complete++] = i;
-			continue;
-		}
-		memcpy(WFIFOP(fd,(i-num_complete)*sizeof(struct quest)+8), &tmp_questlog[i], sizeof(struct quest));
-	}
-
-	// Completed quests
-	for( i = num_quests - num_complete; i < num_quests; i++ )
-		memcpy(WFIFOP(fd,i*sizeof(struct quest)+8), &tmp_questlog[complete[i-num_quests+num_complete]], sizeof(struct quest));
-
-	WFIFOSET(fd,num_quests*sizeof(struct quest)+8);
-
-	return 0;
+    int char_id = RFIFOL(fd,2);
+    struct quest tmp_questlog[MAX_QUEST_DB];
+    int num_quests, i, num_complete = 0;
+    int complete[MAX_QUEST_DB];
+
+    memset(tmp_questlog, 0, sizeof(tmp_questlog));
+    memset(complete, 0, sizeof(complete));
+
+    num_quests = mapif_quests_fromsql(char_id, tmp_questlog);
+
+    WFIFOHEAD(fd,num_quests*sizeof(struct quest)+8);
+    WFIFOW(fd,0) = 0x3860;
+    WFIFOW(fd,2) = num_quests*sizeof(struct quest)+8;
+    WFIFOL(fd,4) = char_id;
+
+    //Active and inactive quests
+    for (i = 0; i < num_quests; i++) {
+        if (tmp_questlog[i].state == Q_COMPLETE) {
+            complete[num_complete++] = i;
+            continue;
+        }
+        memcpy(WFIFOP(fd,(i-num_complete)*sizeof(struct quest)+8), &tmp_questlog[i], sizeof(struct quest));
+    }
+
+    // Completed quests
+    for (i = num_quests - num_complete; i < num_quests; i++)
+        memcpy(WFIFOP(fd,i*sizeof(struct quest)+8), &tmp_questlog[complete[i-num_quests+num_complete]], sizeof(struct quest));
+
+    WFIFOSET(fd,num_quests*sizeof(struct quest)+8);
+
+    return 0;
 }
 
 int inter_quest_parse_frommap(int fd)
 {
-	switch(RFIFOW(fd,0))
-	{
-		case 0x3060: mapif_parse_quest_load(fd); break;
-		case 0x3061: mapif_parse_quest_save(fd); break;
-		default:
-			return 0;
-	}
-	return 1;
+    switch (RFIFOW(fd,0)) {
+        case 0x3060:
+            mapif_parse_quest_load(fd);
+            break;
+        case 0x3061:
+            mapif_parse_quest_save(fd);
+            break;
+        default:
+            return 0;
+    }
+    return 1;
 }

+ 183 - 169
src/char/int_storage.c

@@ -15,142 +15,155 @@
 #include <stdlib.h>
 
 
-#define STORAGE_MEMINC	16
+#define STORAGE_MEMINC  16
 
 /// Save storage data to sql
-int storage_tosql(int account_id, struct storage_data* p)
+int storage_tosql(int account_id, struct storage_data *p)
 {
-	memitemdata_to_sql(p->items, MAX_STORAGE, account_id, TABLE_STORAGE);
-	return 0;
+    memitemdata_to_sql(p->items, MAX_STORAGE, account_id, TABLE_STORAGE);
+    return 0;
 }
 
 /// Load storage data to mem
-int storage_fromsql(int account_id, struct storage_data* p)
+int storage_fromsql(int account_id, struct storage_data *p)
 {
-	StringBuf buf;
-	struct item* item;
-	char* data;
-	int i;
-	int j;
-
-	memset(p, 0, sizeof(struct storage_data)); //clean up memory
-	p->storage_amount = 0;
-
-	// storage {`account_id`/`id`/`nameid`/`amount`/`equip`/`identify`/`refine`/`attribute`/`card0`/`card1`/`card2`/`card3`}
-	StringBuf_Init(&buf);
-	StringBuf_AppendStr(&buf, "SELECT `id`,`nameid`,`amount`,`equip`,`identify`,`refine`,`attribute`,`expire_time`");
-	for( j = 0; j < MAX_SLOTS; ++j )
-		StringBuf_Printf(&buf, ",`card%d`", j);
-	StringBuf_Printf(&buf, " FROM `%s` WHERE `account_id`='%d' ORDER BY `nameid`", storage_db, account_id);
-
-	if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) )
-		Sql_ShowDebug(sql_handle);
-
-	StringBuf_Destroy(&buf);
-
-	for( i = 0; i < MAX_STORAGE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i )
-	{
-		item = &p->items[i];
-		Sql_GetData(sql_handle, 0, &data, NULL); item->id = atoi(data);
-		Sql_GetData(sql_handle, 1, &data, NULL); item->nameid = atoi(data);
-		Sql_GetData(sql_handle, 2, &data, NULL); item->amount = atoi(data);
-		Sql_GetData(sql_handle, 3, &data, NULL); item->equip = atoi(data);
-		Sql_GetData(sql_handle, 4, &data, NULL); item->identify = atoi(data);
-		Sql_GetData(sql_handle, 5, &data, NULL); item->refine = atoi(data);
-		Sql_GetData(sql_handle, 6, &data, NULL); item->attribute = atoi(data);
-		Sql_GetData(sql_handle, 7, &data, NULL); item->expire_time = (unsigned int)atoi(data);
-		for( j = 0; j < MAX_SLOTS; ++j )
-		{
-			Sql_GetData(sql_handle, 8+j, &data, NULL); item->card[j] = atoi(data);
-		}
-	}
-	p->storage_amount = i;
-	Sql_FreeResult(sql_handle);
-
-	ShowInfo("storage load complete from DB - id: %d (total: %d)\n", account_id, p->storage_amount);
-	return 1;
+    StringBuf buf;
+    struct item *item;
+    char *data;
+    int i;
+    int j;
+
+    memset(p, 0, sizeof(struct storage_data)); //clean up memory
+    p->storage_amount = 0;
+
+    // storage {`account_id`/`id`/`nameid`/`amount`/`equip`/`identify`/`refine`/`attribute`/`card0`/`card1`/`card2`/`card3`}
+    StringBuf_Init(&buf);
+    StringBuf_AppendStr(&buf, "SELECT `id`,`nameid`,`amount`,`equip`,`identify`,`refine`,`attribute`,`expire_time`");
+    for (j = 0; j < MAX_SLOTS; ++j)
+        StringBuf_Printf(&buf, ",`card%d`", j);
+    StringBuf_Printf(&buf, " FROM `%s` WHERE `account_id`='%d' ORDER BY `nameid`", storage_db, account_id);
+
+    if (SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)))
+        Sql_ShowDebug(sql_handle);
+
+    StringBuf_Destroy(&buf);
+
+    for (i = 0; i < MAX_STORAGE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i) {
+        item = &p->items[i];
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        item->id = atoi(data);
+        Sql_GetData(sql_handle, 1, &data, NULL);
+        item->nameid = atoi(data);
+        Sql_GetData(sql_handle, 2, &data, NULL);
+        item->amount = atoi(data);
+        Sql_GetData(sql_handle, 3, &data, NULL);
+        item->equip = atoi(data);
+        Sql_GetData(sql_handle, 4, &data, NULL);
+        item->identify = atoi(data);
+        Sql_GetData(sql_handle, 5, &data, NULL);
+        item->refine = atoi(data);
+        Sql_GetData(sql_handle, 6, &data, NULL);
+        item->attribute = atoi(data);
+        Sql_GetData(sql_handle, 7, &data, NULL);
+        item->expire_time = (unsigned int)atoi(data);
+        for (j = 0; j < MAX_SLOTS; ++j) {
+            Sql_GetData(sql_handle, 8+j, &data, NULL);
+            item->card[j] = atoi(data);
+        }
+    }
+    p->storage_amount = i;
+    Sql_FreeResult(sql_handle);
+
+    ShowInfo("storage load complete from DB - id: %d (total: %d)\n", account_id, p->storage_amount);
+    return 1;
 }
 
 /// Save guild_storage data to sql
-int guild_storage_tosql(int guild_id, struct guild_storage* p)
+int guild_storage_tosql(int guild_id, struct guild_storage *p)
 {
-	memitemdata_to_sql(p->items, MAX_GUILD_STORAGE, guild_id, TABLE_GUILD_STORAGE);
-	ShowInfo ("guild storage save to DB - guild: %d\n", guild_id);
-	return 0;
+    memitemdata_to_sql(p->items, MAX_GUILD_STORAGE, guild_id, TABLE_GUILD_STORAGE);
+    ShowInfo("guild storage save to DB - guild: %d\n", guild_id);
+    return 0;
 }
 
 /// Load guild_storage data to mem
-int guild_storage_fromsql(int guild_id, struct guild_storage* p)
+int guild_storage_fromsql(int guild_id, struct guild_storage *p)
 {
-	StringBuf buf;
-	struct item* item;
-	char* data;
-	int i;
-	int j;
-
-	memset(p, 0, sizeof(struct guild_storage)); //clean up memory
-	p->storage_amount = 0;
-	p->guild_id = guild_id;
-
-	// storage {`guild_id`/`id`/`nameid`/`amount`/`equip`/`identify`/`refine`/`attribute`/`card0`/`card1`/`card2`/`card3`}
-	StringBuf_Init(&buf);
-	StringBuf_AppendStr(&buf, "SELECT `id`,`nameid`,`amount`,`equip`,`identify`,`refine`,`attribute`");
-	for( j = 0; j < MAX_SLOTS; ++j )
-		StringBuf_Printf(&buf, ",`card%d`", j);
-	StringBuf_Printf(&buf, " FROM `%s` WHERE `guild_id`='%d' ORDER BY `nameid`", guild_storage_db, guild_id);
-
-	if( SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)) )
-		Sql_ShowDebug(sql_handle);
-
-	StringBuf_Destroy(&buf);
-
-	for( i = 0; i < MAX_GUILD_STORAGE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i )
-	{
-		item = &p->items[i];
-		Sql_GetData(sql_handle, 0, &data, NULL); item->id = atoi(data);
-		Sql_GetData(sql_handle, 1, &data, NULL); item->nameid = atoi(data);
-		Sql_GetData(sql_handle, 2, &data, NULL); item->amount = atoi(data);
-		Sql_GetData(sql_handle, 3, &data, NULL); item->equip = atoi(data);
-		Sql_GetData(sql_handle, 4, &data, NULL); item->identify = atoi(data);
-		Sql_GetData(sql_handle, 5, &data, NULL); item->refine = atoi(data);
-		Sql_GetData(sql_handle, 6, &data, NULL); item->attribute = atoi(data);
-		item->expire_time = 0;
-		for( j = 0; j < MAX_SLOTS; ++j )
-		{
-			Sql_GetData(sql_handle, 7+j, &data, NULL); item->card[j] = atoi(data);
-		}
-	}
-	p->storage_amount = i;
-	Sql_FreeResult(sql_handle);
-
-	ShowInfo("guild storage load complete from DB - id: %d (total: %d)\n", guild_id, p->storage_amount);
-	return 0;
+    StringBuf buf;
+    struct item *item;
+    char *data;
+    int i;
+    int j;
+
+    memset(p, 0, sizeof(struct guild_storage)); //clean up memory
+    p->storage_amount = 0;
+    p->guild_id = guild_id;
+
+    // storage {`guild_id`/`id`/`nameid`/`amount`/`equip`/`identify`/`refine`/`attribute`/`card0`/`card1`/`card2`/`card3`}
+    StringBuf_Init(&buf);
+    StringBuf_AppendStr(&buf, "SELECT `id`,`nameid`,`amount`,`equip`,`identify`,`refine`,`attribute`");
+    for (j = 0; j < MAX_SLOTS; ++j)
+        StringBuf_Printf(&buf, ",`card%d`", j);
+    StringBuf_Printf(&buf, " FROM `%s` WHERE `guild_id`='%d' ORDER BY `nameid`", guild_storage_db, guild_id);
+
+    if (SQL_ERROR == Sql_Query(sql_handle, StringBuf_Value(&buf)))
+        Sql_ShowDebug(sql_handle);
+
+    StringBuf_Destroy(&buf);
+
+    for (i = 0; i < MAX_GUILD_STORAGE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i) {
+        item = &p->items[i];
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        item->id = atoi(data);
+        Sql_GetData(sql_handle, 1, &data, NULL);
+        item->nameid = atoi(data);
+        Sql_GetData(sql_handle, 2, &data, NULL);
+        item->amount = atoi(data);
+        Sql_GetData(sql_handle, 3, &data, NULL);
+        item->equip = atoi(data);
+        Sql_GetData(sql_handle, 4, &data, NULL);
+        item->identify = atoi(data);
+        Sql_GetData(sql_handle, 5, &data, NULL);
+        item->refine = atoi(data);
+        Sql_GetData(sql_handle, 6, &data, NULL);
+        item->attribute = atoi(data);
+        item->expire_time = 0;
+        for (j = 0; j < MAX_SLOTS; ++j) {
+            Sql_GetData(sql_handle, 7+j, &data, NULL);
+            item->card[j] = atoi(data);
+        }
+    }
+    p->storage_amount = i;
+    Sql_FreeResult(sql_handle);
+
+    ShowInfo("guild storage load complete from DB - id: %d (total: %d)\n", guild_id, p->storage_amount);
+    return 0;
 }
 
 //---------------------------------------------------------
 // storage data initialize
 int inter_storage_sql_init(void)
 {
-	return 1;
+    return 1;
 }
 // storage data finalize
 void inter_storage_sql_final(void)
 {
-	return;
+    return;
 }
 
 // q?f[^?
 int inter_storage_delete(int account_id)
 {
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id`='%d'", storage_db, account_id) )
-		Sql_ShowDebug(sql_handle);
-	return 0;
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id`='%d'", storage_db, account_id))
+        Sql_ShowDebug(sql_handle);
+    return 0;
 }
 int inter_guild_storage_delete(int guild_id)
 {
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id`='%d'", guild_storage_db, guild_id) )
-		Sql_ShowDebug(sql_handle);
-	return 0;
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `guild_id`='%d'", guild_storage_db, guild_id))
+        Sql_ShowDebug(sql_handle);
+    return 0;
 }
 
 //---------------------------------------------------------
@@ -158,38 +171,38 @@ int inter_guild_storage_delete(int guild_id)
 
 int mapif_load_guild_storage(int fd,int account_id,int guild_id)
 {
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `guild_id` FROM `%s` WHERE `guild_id`='%d'", guild_db, guild_id) )
-		Sql_ShowDebug(sql_handle);
-	else if( Sql_NumRows(sql_handle) > 0 )
-	{// guild exists
-		WFIFOHEAD(fd, sizeof(struct guild_storage)+12);
-		WFIFOW(fd,0) = 0x3818;
-		WFIFOW(fd,2) = sizeof(struct guild_storage)+12;
-		WFIFOL(fd,4) = account_id;
-		WFIFOL(fd,8) = guild_id;
-		guild_storage_fromsql(guild_id, (struct guild_storage*)WFIFOP(fd,12));
-		WFIFOSET(fd, WFIFOW(fd,2));
-		return 0;
-	}
-	// guild does not exist
-	Sql_FreeResult(sql_handle);
-	WFIFOHEAD(fd, 12);
-	WFIFOW(fd,0) = 0x3818;
-	WFIFOW(fd,2) = 12;
-	WFIFOL(fd,4) = account_id;
-	WFIFOL(fd,8) = 0;
-	WFIFOSET(fd, 12);
-	return 0;
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `guild_id` FROM `%s` WHERE `guild_id`='%d'", guild_db, guild_id))
+        Sql_ShowDebug(sql_handle);
+    else if (Sql_NumRows(sql_handle) > 0) {
+        // guild exists
+        WFIFOHEAD(fd, sizeof(struct guild_storage)+12);
+        WFIFOW(fd,0) = 0x3818;
+        WFIFOW(fd,2) = sizeof(struct guild_storage)+12;
+        WFIFOL(fd,4) = account_id;
+        WFIFOL(fd,8) = guild_id;
+        guild_storage_fromsql(guild_id, (struct guild_storage *)WFIFOP(fd,12));
+        WFIFOSET(fd, WFIFOW(fd,2));
+        return 0;
+    }
+    // guild does not exist
+    Sql_FreeResult(sql_handle);
+    WFIFOHEAD(fd, 12);
+    WFIFOW(fd,0) = 0x3818;
+    WFIFOW(fd,2) = 12;
+    WFIFOL(fd,4) = account_id;
+    WFIFOL(fd,8) = 0;
+    WFIFOSET(fd, 12);
+    return 0;
 }
 int mapif_save_guild_storage_ack(int fd,int account_id,int guild_id,int fail)
 {
-	WFIFOHEAD(fd,11);
-	WFIFOW(fd,0)=0x3819;
-	WFIFOL(fd,2)=account_id;
-	WFIFOL(fd,6)=guild_id;
-	WFIFOB(fd,10)=fail;
-	WFIFOSET(fd,11);
-	return 0;
+    WFIFOHEAD(fd,11);
+    WFIFOW(fd,0)=0x3819;
+    WFIFOL(fd,2)=account_id;
+    WFIFOL(fd,6)=guild_id;
+    WFIFOB(fd,10)=fail;
+    WFIFOSET(fd,11);
+    return 0;
 }
 
 //---------------------------------------------------------
@@ -197,50 +210,51 @@ int mapif_save_guild_storage_ack(int fd,int account_id,int guild_id,int fail)
 
 int mapif_parse_LoadGuildStorage(int fd)
 {
-	RFIFOHEAD(fd);
-	mapif_load_guild_storage(fd,RFIFOL(fd,2),RFIFOL(fd,6));
-	return 0;
+    RFIFOHEAD(fd);
+    mapif_load_guild_storage(fd,RFIFOL(fd,2),RFIFOL(fd,6));
+    return 0;
 }
 
 int mapif_parse_SaveGuildStorage(int fd)
 {
-	int guild_id;
-	int len;
-
-	RFIFOHEAD(fd);
-	guild_id = RFIFOL(fd,8);
-	len = RFIFOW(fd,2);
-
-	if( sizeof(struct guild_storage) != len - 12 )
-	{
-		ShowError("inter storage: data size error %d != %d\n", sizeof(struct guild_storage), len - 12);
-	}
-	else
-	{
-		if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `guild_id` FROM `%s` WHERE `guild_id`='%d'", guild_db, guild_id) )
-			Sql_ShowDebug(sql_handle);
-		else if( Sql_NumRows(sql_handle) > 0 )
-		{// guild exists
-			Sql_FreeResult(sql_handle);
-			guild_storage_tosql(guild_id, (struct guild_storage*)RFIFOP(fd,12));
-			mapif_save_guild_storage_ack(fd, RFIFOL(fd,4), guild_id, 0);
-			return 0;
-		}
-		Sql_FreeResult(sql_handle);
-	}
-	mapif_save_guild_storage_ack(fd, RFIFOL(fd,4), guild_id, 1);
-	return 0;
+    int guild_id;
+    int len;
+
+    RFIFOHEAD(fd);
+    guild_id = RFIFOL(fd,8);
+    len = RFIFOW(fd,2);
+
+    if (sizeof(struct guild_storage) != len - 12) {
+        ShowError("inter storage: data size error %d != %d\n", sizeof(struct guild_storage), len - 12);
+    } else {
+        if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `guild_id` FROM `%s` WHERE `guild_id`='%d'", guild_db, guild_id))
+            Sql_ShowDebug(sql_handle);
+        else if (Sql_NumRows(sql_handle) > 0) {
+            // guild exists
+            Sql_FreeResult(sql_handle);
+            guild_storage_tosql(guild_id, (struct guild_storage *)RFIFOP(fd,12));
+            mapif_save_guild_storage_ack(fd, RFIFOL(fd,4), guild_id, 0);
+            return 0;
+        }
+        Sql_FreeResult(sql_handle);
+    }
+    mapif_save_guild_storage_ack(fd, RFIFOL(fd,4), guild_id, 1);
+    return 0;
 }
 
 
 int inter_storage_parse_frommap(int fd)
 {
-	RFIFOHEAD(fd);
-	switch(RFIFOW(fd,0)){
-	case 0x3018: mapif_parse_LoadGuildStorage(fd); break;
-	case 0x3019: mapif_parse_SaveGuildStorage(fd); break;
-	default:
-		return 0;
-	}
-	return 1;
+    RFIFOHEAD(fd);
+    switch (RFIFOW(fd,0)) {
+        case 0x3018:
+            mapif_parse_LoadGuildStorage(fd);
+            break;
+        case 0x3019:
+            mapif_parse_SaveGuildStorage(fd);
+            break;
+        default:
+            return 0;
+    }
+    return 1;
 }

+ 1 - 1
src/char/int_storage.h

@@ -15,7 +15,7 @@ int inter_guild_storage_delete(int guild_id);
 int inter_storage_parse_frommap(int fd);
 
 //Exported for use in the TXT-SQL converter.
-int storage_fromsql(int account_id, struct storage_data* p);
+int storage_fromsql(int account_id, struct storage_data *p);
 int storage_tosql(int account_id,struct storage_data *p);
 int guild_storage_tosql(int guild_id, struct guild_storage *p);
 

File diff suppressed because it is too large
+ 715 - 693
src/char/inter.c


+ 2 - 2
src/char/inter.h

@@ -20,8 +20,8 @@ int inter_log(char *fmt,...);
 
 extern unsigned int party_share_level;
 
-extern Sql* sql_handle;
-extern Sql* lsql_handle;
+extern Sql *sql_handle;
+extern Sql *lsql_handle;
 
 extern char main_chat_nick[16];
 

+ 77 - 62
src/common/atomic.h

@@ -4,16 +4,16 @@
 #ifndef _rA_ATOMIC_H_
 #define _rA_ATOMIC_H_
 
-// Atomic Operations 
+// Atomic Operations
 // (Interlocked CompareExchange, Add .. and so on ..)
-// 
+//
 // Implementation varies / depends on:
-//	- Architecture
-//	- Compiler
-//	- Operating System
+//  - Architecture
+//  - Compiler
+//  - Operating System
 //
 // our Abstraction is fully API-Compatible to Microsofts implementation @ NT5.0+
-// 
+//
 #include "../common/cbasetypes.h"
 
 #if defined(_MSC_VER)
@@ -22,60 +22,65 @@
 #if !defined(_M_X64)
 // When compiling for windows 32bit, the 8byte interlocked operations are not provided by microsoft
 // (because they need at least i586 so its not generic enough.. ... )
-forceinline int64 InterlockedCompareExchange64(volatile int64 *dest, int64 exch, int64 _cmp){
-	_asm{
-		lea esi,_cmp;
-		lea edi,exch;
-        
-		mov eax,[esi];
-		mov edx,4[esi];
-		mov ebx,[edi];
-		mov ecx,4[edi];
-		mov esi,dest;
-		
-		lock CMPXCHG8B [esi];					
-	}
+forceinline int64 InterlockedCompareExchange64(volatile int64 *dest, int64 exch, int64 _cmp)
+{
+    _asm {
+        lea esi,_cmp;
+        lea edi,exch;
+
+        mov eax,[esi];
+        mov edx,4[esi];
+        mov ebx,[edi];
+        mov ecx,4[edi];
+        mov esi,dest;
+
+        lock CMPXCHG8B [esi];
+    }
 }
 
 
-forceinline volatile int64 InterlockedIncrement64(volatile int64 *addend){
-	__int64 old;
-	do{
-		old = *addend;
-	}while(InterlockedCompareExchange64(addend, (old+1), old) != old);
+forceinline volatile int64 InterlockedIncrement64(volatile int64 *addend)
+{
+    __int64 old;
+    do {
+        old = *addend;
+    } while (InterlockedCompareExchange64(addend, (old+1), old) != old);
 
-	return (old + 1);
+    return (old + 1);
 }
 
 
 
-forceinline volatile int64 InterlockedDecrement64(volatile int64 *addend){
-	__int64 old;
+forceinline volatile int64 InterlockedDecrement64(volatile int64 *addend)
+{
+    __int64 old;
 
-	do{
-		old = *addend;
-	}while(InterlockedCompareExchange64(addend, (old-1), old) != old);
+    do {
+        old = *addend;
+    } while (InterlockedCompareExchange64(addend, (old-1), old) != old);
 
-	return (old - 1);
+    return (old - 1);
 }
 
-forceinline volatile int64 InterlockedExchangeAdd64(volatile int64 *addend, int64 increment){
-	__int64 old;
+forceinline volatile int64 InterlockedExchangeAdd64(volatile int64 *addend, int64 increment)
+{
+    __int64 old;
 
-	do{
-		old = *addend;
-	}while(InterlockedCompareExchange64(addend, (old + increment), old) != old);
+    do {
+        old = *addend;
+    } while (InterlockedCompareExchange64(addend, (old + increment), old) != old);
 
-	return old;
+    return old;
 }
 
-forceinline volatile int64 InterlockedExchange64(volatile int64 *target, int64 val){
-	__int64 old;
-	do{
-		old = *target;
-	}while(InterlockedCompareExchange64(target, val, old) != old);
+forceinline volatile int64 InterlockedExchange64(volatile int64 *target, int64 val)
+{
+    __int64 old;
+    do {
+        old = *target;
+    } while (InterlockedCompareExchange64(target, val, old) != old);
 
-	return old;
+    return old;
 }
 
 #endif //endif 32bit windows
@@ -86,52 +91,62 @@ forceinline volatile int64 InterlockedExchange64(volatile int64 *target, int64 v
 #error Your Target Platfrom is not supported
 #endif
 
-static forceinline int64 InterlockedExchangeAdd64(volatile int64 *addend, int64 increment){
-	return __sync_fetch_and_add(addend, increment);
+static forceinline int64 InterlockedExchangeAdd64(volatile int64 *addend, int64 increment)
+{
+    return __sync_fetch_and_add(addend, increment);
 }//end: InterlockedExchangeAdd64()
 
 
-static forceinline int32 InterlockedExchangeAdd(volatile int32 *addend, int32 increment){
-	return __sync_fetch_and_add(addend, increment);
+static forceinline int32 InterlockedExchangeAdd(volatile int32 *addend, int32 increment)
+{
+    return __sync_fetch_and_add(addend, increment);
 }//end: InterlockedExchangeAdd()
 
 
-static forceinline int64 InterlockedIncrement64(volatile int64 *addend){
-	return __sync_add_and_fetch(addend, 1);
+static forceinline int64 InterlockedIncrement64(volatile int64 *addend)
+{
+    return __sync_add_and_fetch(addend, 1);
 }//end: InterlockedIncrement64()
 
 
-static forceinline int32 InterlockedIncrement(volatile int32 *addend){
-        return __sync_add_and_fetch(addend, 1);
+static forceinline int32 InterlockedIncrement(volatile int32 *addend)
+{
+    return __sync_add_and_fetch(addend, 1);
 }//end: InterlockedIncrement()
 
 
-static forceinline int64 InterlockedDecrement64(volatile int64 *addend){
-	return __sync_sub_and_fetch(addend, 1);
+static forceinline int64 InterlockedDecrement64(volatile int64 *addend)
+{
+    return __sync_sub_and_fetch(addend, 1);
 }//end: InterlockedDecrement64()
 
 
-static forceinline int32 InterlockedDecrement(volatile int32 *addend){
-	return __sync_sub_and_fetch(addend, 1);
+static forceinline int32 InterlockedDecrement(volatile int32 *addend)
+{
+    return __sync_sub_and_fetch(addend, 1);
 }//end: InterlockedDecrement()
 
 
-static forceinline int64 InterlockedCompareExchange64(volatile int64 *dest, int64 exch, int64 cmp){
-	return __sync_val_compare_and_swap(dest, cmp, exch);
+static forceinline int64 InterlockedCompareExchange64(volatile int64 *dest, int64 exch, int64 cmp)
+{
+    return __sync_val_compare_and_swap(dest, cmp, exch);
 }//end: InterlockedCompareExchange64()
 
 
-static forceinline int32 InterlockedCompareExchange(volatile int32 *dest, int32 exch, int32 cmp){
-	return __sync_val_compare_and_swap(dest, cmp, exch);
+static forceinline int32 InterlockedCompareExchange(volatile int32 *dest, int32 exch, int32 cmp)
+{
+    return __sync_val_compare_and_swap(dest, cmp, exch);
 }//end: InterlockedCompareExchnage()
 
 
-static forceinline int64 InterlockedExchange64(volatile int64 *target, int64 val){
-	return __sync_lock_test_and_set(target, val);
+static forceinline int64 InterlockedExchange64(volatile int64 *target, int64 val)
+{
+    return __sync_lock_test_and_set(target, val);
 }//end: InterlockedExchange64()
 
 
-static forceinline int32 InterlockedExchange(volatile int32 *target, int32 val){
+static forceinline int32 InterlockedExchange(volatile int32 *target, int32 val)
+{
     return __sync_lock_test_and_set(target, val);
 }//end: InterlockedExchange()
 

+ 75 - 72
src/common/cbasetypes.h

@@ -59,11 +59,11 @@
 // debug function name
 #ifndef __NETBSD__
 #if __STDC_VERSION__ < 199901L
-#	if __GNUC__ >= 2
-#		define __func__ __FUNCTION__
-#	else
-#		define __func__ ""
-#	endif
+#   if __GNUC__ >= 2
+#       define __func__ __FUNCTION__
+#   else
+#       define __func__ ""
+#   endif
 #endif
 #endif
 
@@ -106,56 +106,56 @@
 // Integers with guaranteed _exact_ size.
 //////////////////////////////////////////////////////////////////////////
 
-typedef int8_t		int8;
-typedef int16_t		int16;
-typedef int32_t		int32;
-typedef int64_t		int64;
+typedef int8_t      int8;
+typedef int16_t     int16;
+typedef int32_t     int32;
+typedef int64_t     int64;
 
-typedef int8_t		sint8;
-typedef int16_t		sint16;
-typedef int32_t		sint32;
-typedef int64_t		sint64;
+typedef int8_t      sint8;
+typedef int16_t     sint16;
+typedef int32_t     sint32;
+typedef int64_t     sint64;
 
-typedef uint8_t		uint8;
-typedef uint16_t	uint16;
-typedef uint32_t	uint32;
-typedef uint64_t	uint64;
+typedef uint8_t     uint8;
+typedef uint16_t    uint16;
+typedef uint32_t    uint32;
+typedef uint64_t    uint64;
 
 #undef UINT8_MIN
 #undef UINT16_MIN
 #undef UINT32_MIN
 #undef UINT64_MIN
-#define UINT8_MIN	((uint8) UINT8_C(0x00))
-#define UINT16_MIN	((uint16)UINT16_C(0x0000))
-#define UINT32_MIN	((uint32)UINT32_C(0x00000000))
-#define UINT64_MIN	((uint64)UINT64_C(0x0000000000000000))
+#define UINT8_MIN   ((uint8) UINT8_C(0x00))
+#define UINT16_MIN  ((uint16)UINT16_C(0x0000))
+#define UINT32_MIN  ((uint32)UINT32_C(0x00000000))
+#define UINT64_MIN  ((uint64)UINT64_C(0x0000000000000000))
 
 #undef UINT8_MAX
 #undef UINT16_MAX
 #undef UINT32_MAX
 #undef UINT64_MAX
-#define UINT8_MAX	((uint8) UINT8_C(0xFF))
-#define UINT16_MAX	((uint16)UINT16_C(0xFFFF))
-#define UINT32_MAX	((uint32)UINT32_C(0xFFFFFFFF))
-#define UINT64_MAX	((uint64)UINT64_C(0xFFFFFFFFFFFFFFFF))
+#define UINT8_MAX   ((uint8) UINT8_C(0xFF))
+#define UINT16_MAX  ((uint16)UINT16_C(0xFFFF))
+#define UINT32_MAX  ((uint32)UINT32_C(0xFFFFFFFF))
+#define UINT64_MAX  ((uint64)UINT64_C(0xFFFFFFFFFFFFFFFF))
 
 #undef SINT8_MIN
 #undef SINT16_MIN
 #undef SINT32_MIN
 #undef SINT64_MIN
-#define SINT8_MIN	((sint8) INT8_C(0x80))
-#define SINT16_MIN	((sint16)INT16_C(0x8000))
-#define SINT32_MIN	((sint32)INT32_C(0x80000000))
-#define SINT64_MIN	((sint32)INT64_C(0x8000000000000000))
+#define SINT8_MIN   ((sint8) INT8_C(0x80))
+#define SINT16_MIN  ((sint16)INT16_C(0x8000))
+#define SINT32_MIN  ((sint32)INT32_C(0x80000000))
+#define SINT64_MIN  ((sint32)INT64_C(0x8000000000000000))
 
 #undef SINT8_MAX
 #undef SINT16_MAX
 #undef SINT32_MAX
 #undef SINT64_MAX
-#define SINT8_MAX	((sint8) INT8_C(0x7F))
-#define SINT16_MAX	((sint16)INT16_C(0x7FFF))
-#define SINT32_MAX	((sint32)INT32_C(0x7FFFFFFF))
-#define SINT64_MAX	((sint64)INT64_C(0x7FFFFFFFFFFFFFFF))
+#define SINT8_MAX   ((sint8) INT8_C(0x7F))
+#define SINT16_MAX  ((sint16)INT16_C(0x7FFF))
+#define SINT32_MAX  ((sint32)INT32_C(0x7FFFFFFF))
+#define SINT64_MAX  ((sint64)INT64_C(0x7FFFFFFFFFFFFFFF))
 
 //////////////////////////////////////////////////////////////////////////
 // Integers with guaranteed _minimum_ size.
@@ -180,10 +180,10 @@ typedef unsigned long int   ppuint32;
 
 #if defined(WIN32) && !defined(MINGW) // does not have a signed size_t
 //////////////////////////////
-#if defined(_WIN64)	// naive 64bit windows platform
-typedef __int64			ssize_t;
+#if defined(_WIN64) // naive 64bit windows platform
+typedef __int64         ssize_t;
 #else
-typedef int				ssize_t;
+typedef int             ssize_t;
 #endif
 //////////////////////////////
 #endif
@@ -201,23 +201,23 @@ typedef uintptr_t uintptr;
 // Add a 'sysint' Type which has the width of the platform we're compiled for.
 //////////////////////////////////////////////////////////////////////////
 #if defined(__GNUC__)
-	#if defined(__x86_64__)
-		typedef int64 sysint;
-		typedef uint64 usysint;
-	#else
-		typedef int32 sysint;
-		typedef uint32 usysint;
-	#endif
+#if defined(__x86_64__)
+typedef int64 sysint;
+typedef uint64 usysint;
+#else
+typedef int32 sysint;
+typedef uint32 usysint;
+#endif
 #elif defined(_MSC_VER)
-	#if defined(_M_X64)
-		typedef int64 sysint;
-		typedef uint64 usysint;
-	#else
-		typedef int32 sysint;
-		typedef uint32 usysint;
-	#endif
+#if defined(_M_X64)
+typedef int64 sysint;
+typedef uint64 usysint;
+#else
+typedef int32 sysint;
+typedef uint32 usysint;
+#endif
 #else
-	#error Compiler / Platform is unsupported.
+#error Compiler / Platform is unsupported.
 #endif
 
 
@@ -225,21 +225,21 @@ typedef uintptr_t uintptr;
 // some redefine of function redefines for some Compilers
 //////////////////////////////////////////////////////////////////////////
 #if defined(_MSC_VER) || defined(__BORLANDC__)
-#define strcasecmp			stricmp
-#define strncasecmp			strnicmp
-#define strncmpi			strnicmp
-#define snprintf			_snprintf
+#define strcasecmp          stricmp
+#define strncasecmp         strnicmp
+#define strncmpi            strnicmp
+#define snprintf            _snprintf
 #if defined(_MSC_VER) && _MSC_VER < 1400
-#define vsnprintf			_vsnprintf
+#define vsnprintf           _vsnprintf
 #endif
 #else
-#define strcmpi				strcasecmp
-#define stricmp				strcasecmp
-#define strncmpi			strncasecmp
-#define strnicmp			strncasecmp
+#define strcmpi             strcasecmp
+#define stricmp             strcasecmp
+#define strncmpi            strncasecmp
+#define strnicmp            strncasecmp
 #endif
 #if defined(_MSC_VER) && _MSC_VER > 1200
-#define strtoull			_strtoui64
+#define strtoull            _strtoui64
 #endif
 
 // keyword replacement
@@ -262,8 +262,8 @@ typedef uintptr_t uintptr;
 
 // boolean types for C
 typedef char bool;
-#define false	(1==0)
-#define true	(1==1)
+#define false   (1==0)
+#define true    (1==1)
 
 //////////////////////////////
 #endif // not __cplusplus
@@ -276,7 +276,7 @@ typedef char bool;
 #undef swap
 #endif
 // hmm only ints?
-//#define swap(a,b) { int temp=a; a=b; b=temp;} 
+//#define swap(a,b) { int temp=a; a=b; b=temp;}
 // if using macros then something that is type independent
 //#define swap(a,b) ((a == b) || ((a ^= b), (b ^= a), (a ^= b)))
 // Avoid "value computed is not used" warning and generates the same assembly code
@@ -299,7 +299,7 @@ typedef char bool;
 //////////////////////////////////////////////////////////////////////////
 // number of bits in a byte
 #ifndef NBBY
-#define	NBBY 8
+#define NBBY 8
 #endif
 
 //////////////////////////////////////////////////////////////////////////
@@ -383,17 +383,20 @@ typedef char bool;
 // Set a pointer variable to a pointer value.
 #ifdef __cplusplus
 template <typename T1, typename T2>
-void SET_POINTER(T1*&var, T2* p)
+void SET_POINTER(T1 *&var, T2 *p)
 {
-	var = static_cast<T1*>(p);
+    var = static_cast<T1 *>(p);
 }
 template <typename T1, typename T2>
-void SET_FUNCPOINTER(T1& var, T2 p)
+void SET_FUNCPOINTER(T1 &var, T2 p)
 {
-	char ASSERT_POINTERSIZE[sizeof(T1) == sizeof(void*) && sizeof(T2) == sizeof(void*)?1:-1];// 1 if true, -1 if false
-	union{ T1 out; T2 in; } tmp;// /!\ WARNING casting a pointer to a function pointer is against the C++ standard
-	tmp.in = p;
-	var = tmp.out;
+    char ASSERT_POINTERSIZE[sizeof(T1) == sizeof(void *) && sizeof(T2) == sizeof(void *)?1:-1]; // 1 if true, -1 if false
+    union {
+        T1 out;
+        T2 in;
+    } tmp;// /!\ WARNING casting a pointer to a function pointer is against the C++ standard
+    tmp.in = p;
+    var = tmp.out;
 }
 #else
 #define SET_POINTER(var,p) (var) = (p)

+ 73 - 74
src/common/conf.c

@@ -8,14 +8,14 @@
 
 int conf_read_file(config_t *config, const char *config_filename)
 {
-	config_init(config);
-	if (!config_read_file(config, config_filename)) {
-		ShowError("%s:%d - %s\n", config_error_file(config),
-		          config_error_line(config), config_error_text(config));
-		config_destroy(config);
-		return 1;
-	}
-	return 0;
+    config_init(config);
+    if (!config_read_file(config, config_filename)) {
+        ShowError("%s:%d - %s\n", config_error_file(config),
+                  config_error_line(config), config_error_text(config));
+        config_destroy(config);
+        return 1;
+    }
+    return 0;
 }
 
 //
@@ -28,82 +28,81 @@ int config_setting_copy(config_setting_t *parent, const config_setting_t *src);
 
 void config_setting_copy_simple(config_setting_t *parent, const config_setting_t *src)
 {
-	if (config_setting_is_aggregate(src)) {
-		config_setting_copy_aggregate(parent, src);
-	}
-	else {
-		config_setting_t *set = config_setting_add(parent, config_setting_name(src), config_setting_type(src));
-
-		if (set == NULL)
-			return;
-
-		if (CONFIG_TYPE_INT == config_setting_type(src)) {
-			config_setting_set_int(set, config_setting_get_int(src));
-			config_setting_set_format(set, src->format);
-		} else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
-			config_setting_set_int64(set, config_setting_get_int64(src));
-			config_setting_set_format(set, src->format);
-		} else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
-			config_setting_set_float(set, config_setting_get_float(src));
-		} else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
-			config_setting_set_string(set, config_setting_get_string(src));
-		} else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
-			config_setting_set_bool(set, config_setting_get_bool(src));
-		}
-	}
+    if (config_setting_is_aggregate(src)) {
+        config_setting_copy_aggregate(parent, src);
+    } else {
+        config_setting_t *set = config_setting_add(parent, config_setting_name(src), config_setting_type(src));
+
+        if (set == NULL)
+            return;
+
+        if (CONFIG_TYPE_INT == config_setting_type(src)) {
+            config_setting_set_int(set, config_setting_get_int(src));
+            config_setting_set_format(set, src->format);
+        } else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
+            config_setting_set_int64(set, config_setting_get_int64(src));
+            config_setting_set_format(set, src->format);
+        } else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
+            config_setting_set_float(set, config_setting_get_float(src));
+        } else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
+            config_setting_set_string(set, config_setting_get_string(src));
+        } else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
+            config_setting_set_bool(set, config_setting_get_bool(src));
+        }
+    }
 }
 
 void config_setting_copy_elem(config_setting_t *parent, const config_setting_t *src)
 {
-	config_setting_t *set = NULL;
-
-	if (config_setting_is_aggregate(src))
-		config_setting_copy_aggregate(parent, src);
-	else if (CONFIG_TYPE_INT == config_setting_type(src)) {
-		set = config_setting_set_int_elem(parent, -1, config_setting_get_int(src));
-		config_setting_set_format(set, src->format);
-	} else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
-		set = config_setting_set_int64_elem(parent, -1, config_setting_get_int64(src));
-		config_setting_set_format(set, src->format);   
-	} else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
-		config_setting_set_float_elem(parent, -1, config_setting_get_float(src));
-	} else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
-		config_setting_set_string_elem(parent, -1, config_setting_get_string(src));
-	} else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
-		config_setting_set_bool_elem(parent, -1, config_setting_get_bool(src));
-	}
+    config_setting_t *set = NULL;
+
+    if (config_setting_is_aggregate(src))
+        config_setting_copy_aggregate(parent, src);
+    else if (CONFIG_TYPE_INT == config_setting_type(src)) {
+        set = config_setting_set_int_elem(parent, -1, config_setting_get_int(src));
+        config_setting_set_format(set, src->format);
+    } else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
+        set = config_setting_set_int64_elem(parent, -1, config_setting_get_int64(src));
+        config_setting_set_format(set, src->format);
+    } else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
+        config_setting_set_float_elem(parent, -1, config_setting_get_float(src));
+    } else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
+        config_setting_set_string_elem(parent, -1, config_setting_get_string(src));
+    } else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
+        config_setting_set_bool_elem(parent, -1, config_setting_get_bool(src));
+    }
 }
 
 void config_setting_copy_aggregate(config_setting_t *parent, const config_setting_t *src)
 {
-	config_setting_t *newAgg;
-	int i, n;
-
-	newAgg = config_setting_add(parent, config_setting_name(src), config_setting_type(src));
-
-	if (newAgg == NULL)
-		return;
-
-	n = config_setting_length(src);
-	
-	for (i = 0; i < n; i++) {
-		if (config_setting_is_group(src)) {
-			config_setting_copy_simple(newAgg, config_setting_get_elem(src, i));            
-		} else {
-			config_setting_copy_elem(newAgg, config_setting_get_elem(src, i));
-		}
-	}
+    config_setting_t *newAgg;
+    int i, n;
+
+    newAgg = config_setting_add(parent, config_setting_name(src), config_setting_type(src));
+
+    if (newAgg == NULL)
+        return;
+
+    n = config_setting_length(src);
+
+    for (i = 0; i < n; i++) {
+        if (config_setting_is_group(src)) {
+            config_setting_copy_simple(newAgg, config_setting_get_elem(src, i));
+        } else {
+            config_setting_copy_elem(newAgg, config_setting_get_elem(src, i));
+        }
+    }
 }
 
 int config_setting_copy(config_setting_t *parent, const config_setting_t *src)
 {
-	if (!config_setting_is_group(parent) && !config_setting_is_list(parent))
-		return CONFIG_FALSE;
-
-	if (config_setting_is_aggregate(src)) {
-		config_setting_copy_aggregate(parent, src);
-	} else {
-		config_setting_copy_simple(parent, src);
-	}
-	return CONFIG_TRUE;
+    if (!config_setting_is_group(parent) && !config_setting_is_list(parent))
+        return CONFIG_FALSE;
+
+    if (config_setting_is_aggregate(src)) {
+        config_setting_copy_aggregate(parent, src);
+    } else {
+        config_setting_copy_simple(parent, src);
+    }
+    return CONFIG_TRUE;
 }

+ 222 - 225
src/common/core.c

@@ -28,7 +28,7 @@
 void (*shutdown_callback)(void) = NULL;
 
 #if defined(BUILDBOT)
-	int buildbotflag = 0;
+int buildbotflag = 0;
 #endif
 
 int runflag = CORE_ST_RUN;
@@ -38,14 +38,14 @@ char **arg_v = NULL;
 char *SERVER_NAME = NULL;
 char SERVER_TYPE = ATHENA_SERVER_NONE;
 
-#ifndef MINICORE	// minimalist Core
+#ifndef MINICORE    // minimalist Core
 // Added by Gabuzomeu
 //
 // This is an implementation of signal() using sigaction() for portability.
 // (sigaction() is POSIX; signal() is not.)  Taken from Stevens' _Advanced
 // Programming in the UNIX Environment_.
 //
-#ifdef WIN32	// windows don't have SIGPIPE
+#ifdef WIN32    // windows don't have SIGPIPE
 #define SIGPIPE SIGINT
 #endif
 
@@ -54,229 +54,225 @@ char SERVER_TYPE = ATHENA_SERVER_NONE;
 #else
 sigfunc *compat_signal(int signo, sigfunc *func)
 {
-	struct sigaction sact, oact;
+    struct sigaction sact, oact;
 
-	sact.sa_handler = func;
-	sigemptyset(&sact.sa_mask);
-	sact.sa_flags = 0;
+    sact.sa_handler = func;
+    sigemptyset(&sact.sa_mask);
+    sact.sa_flags = 0;
 #ifdef SA_INTERRUPT
-	sact.sa_flags |= SA_INTERRUPT;	/* SunOS */
+    sact.sa_flags |= SA_INTERRUPT;  /* SunOS */
 #endif
 
-	if (sigaction(signo, &sact, &oact) < 0)
-		return (SIG_ERR);
+    if (sigaction(signo, &sact, &oact) < 0)
+        return (SIG_ERR);
 
-	return (oact.sa_handler);
+    return (oact.sa_handler);
 }
 #endif
 
 /*======================================
- *	CORE : Console events for Windows
+ *  CORE : Console events for Windows
  *--------------------------------------*/
 #ifdef _WIN32
 static BOOL WINAPI console_handler(DWORD c_event)
 {
-    switch(c_event)
-    {
-    case CTRL_CLOSE_EVENT:
-    case CTRL_LOGOFF_EVENT:
-    case CTRL_SHUTDOWN_EVENT:
-		if( shutdown_callback != NULL )
-			shutdown_callback();
-		else
-			runflag = CORE_ST_STOP;// auto-shutdown
-        break;
-	default:
-		return FALSE;
+    switch (c_event) {
+        case CTRL_CLOSE_EVENT:
+        case CTRL_LOGOFF_EVENT:
+        case CTRL_SHUTDOWN_EVENT:
+            if (shutdown_callback != NULL)
+                shutdown_callback();
+            else
+                runflag = CORE_ST_STOP;// auto-shutdown
+            break;
+        default:
+            return FALSE;
     }
     return TRUE;
 }
 
 static void cevents_init()
 {
-	if (SetConsoleCtrlHandler(console_handler,TRUE)==FALSE)
-		ShowWarning ("Unable to install the console handler!\n");
+    if (SetConsoleCtrlHandler(console_handler,TRUE)==FALSE)
+        ShowWarning("Unable to install the console handler!\n");
 }
 #endif
 
 /*======================================
- *	CORE : Signal Sub Function
+ *  CORE : Signal Sub Function
  *--------------------------------------*/
 static void sig_proc(int sn)
 {
-	static int is_called = 0;
-
-	switch (sn) {
-	case SIGINT:
-	case SIGTERM:
-		if (++is_called > 3)
-			exit(EXIT_SUCCESS);
-		if( shutdown_callback != NULL )
-			shutdown_callback();
-		else
-			runflag = CORE_ST_STOP;// auto-shutdown
-		break;
-	case SIGSEGV:
-	case SIGFPE:
-		do_abort();
-		// Pass the signal to the system's default handler
-		compat_signal(sn, SIG_DFL);
-		raise(sn);
-		break;
+    static int is_called = 0;
+
+    switch (sn) {
+        case SIGINT:
+        case SIGTERM:
+            if (++is_called > 3)
+                exit(EXIT_SUCCESS);
+            if (shutdown_callback != NULL)
+                shutdown_callback();
+            else
+                runflag = CORE_ST_STOP;// auto-shutdown
+            break;
+        case SIGSEGV:
+        case SIGFPE:
+            do_abort();
+            // Pass the signal to the system's default handler
+            compat_signal(sn, SIG_DFL);
+            raise(sn);
+            break;
 #ifndef _WIN32
-	case SIGXFSZ:
-		// ignore and allow it to set errno to EFBIG
-		ShowWarning ("Max file size reached!\n");
-		//run_flag = 0;	// should we quit?
-		break;
-	case SIGPIPE:
-		//ShowInfo ("Broken pipe found... closing socket\n");	// set to eof in socket.c
-		break;	// does nothing here
+        case SIGXFSZ:
+            // ignore and allow it to set errno to EFBIG
+            ShowWarning("Max file size reached!\n");
+            //run_flag = 0; // should we quit?
+            break;
+        case SIGPIPE:
+            //ShowInfo ("Broken pipe found... closing socket\n");   // set to eof in socket.c
+            break;  // does nothing here
 #endif
-	}
+    }
 }
 
-void signals_init (void)
+void signals_init(void)
 {
-	compat_signal(SIGTERM, sig_proc);
-	compat_signal(SIGINT, sig_proc);
+    compat_signal(SIGTERM, sig_proc);
+    compat_signal(SIGINT, sig_proc);
 #ifndef _DEBUG // need unhandled exceptions to debug on Windows
-	compat_signal(SIGSEGV, sig_proc);
-	compat_signal(SIGFPE, sig_proc);
+    compat_signal(SIGSEGV, sig_proc);
+    compat_signal(SIGFPE, sig_proc);
 #endif
 #ifndef _WIN32
-	compat_signal(SIGILL, SIG_DFL);
-	compat_signal(SIGXFSZ, sig_proc);
-	compat_signal(SIGPIPE, sig_proc);
-	compat_signal(SIGBUS, SIG_DFL);
-	compat_signal(SIGTRAP, SIG_DFL);
+    compat_signal(SIGILL, SIG_DFL);
+    compat_signal(SIGXFSZ, sig_proc);
+    compat_signal(SIGPIPE, sig_proc);
+    compat_signal(SIGBUS, SIG_DFL);
+    compat_signal(SIGTRAP, SIG_DFL);
 #endif
 }
 #endif
 
 #ifdef SVNVERSION
-	const char *get_svn_revision(void)
-	{
-		return EXPAND_AND_QUOTE(SVNVERSION);
-	}
+const char *get_svn_revision(void)
+{
+    return EXPAND_AND_QUOTE(SVNVERSION);
+}
 #else// not SVNVERSION
-const char* get_svn_revision(void)
+const char *get_svn_revision(void)
 {
-	static char svn_version_buffer[16] = "";
-	FILE *fp;
-
-	if( svn_version_buffer[0] != '\0' )
-		return svn_version_buffer;
-
-	// subversion 1.7 uses a sqlite3 database
-	// FIXME this is hackish at best...
-	// - ignores database file structure
-	// - assumes the data in NODES.dav_cache column ends with "!svn/ver/<revision>/<path>)"
-	// - since it's a cache column, the data might not even exist
-	if( (fp = fopen(".svn"PATHSEP_STR"wc.db", "rb")) != NULL || (fp = fopen(".."PATHSEP_STR".svn"PATHSEP_STR"wc.db", "rb")) != NULL )
-	{
-	#ifndef SVNNODEPATH
-		//not sure how to handle branches, so i'll leave this overridable define until a better solution comes up
-		#define SVNNODEPATH trunk
-	#endif
-		const char* prefix = "!svn/ver/";
-		const char* postfix = "/"EXPAND_AND_QUOTE(SVNNODEPATH)")"; // there should exist only 1 entry like this
-		size_t prefix_len = strlen(prefix);
-		size_t postfix_len = strlen(postfix);
-		size_t i,j,len;
-		char* buffer;
-
-		// read file to buffer
-		fseek(fp, 0, SEEK_END);
-		len = ftell(fp);
-		buffer = (char*)aMalloc(len + 1);
-		fseek(fp, 0, SEEK_SET);
-		len = fread(buffer, 1, len, fp);
-		buffer[len] = '\0';
-		fclose(fp);
-
-		// parse buffer
-		for( i = prefix_len + 1; i + postfix_len <= len; ++i )
-		{
-			if( buffer[i] != postfix[0] || memcmp(buffer + i, postfix, postfix_len) != 0 )
-				continue; // postfix missmatch
-			for( j = i; j > 0; --j )
-			{// skip digits
-				if( !ISDIGIT(buffer[j - 1]) )
-					break;
-			}
-			if( memcmp(buffer + j - prefix_len, prefix, prefix_len) != 0 )
-				continue; // prefix missmatch
-			// done
-			snprintf(svn_version_buffer, sizeof(svn_version_buffer), "%d", atoi(buffer + j));
-			break;
-		}
-		aFree(buffer);
-
-		if( svn_version_buffer[0] != '\0' )
-			return svn_version_buffer;
-	}
-
-	// subversion 1.6 and older?
-	if ((fp = fopen(".svn/entries", "r")) != NULL)
-	{
-		char line[1024];
-		int rev;
-		// Check the version
-		if (fgets(line, sizeof(line), fp))
-		{
-			if(!ISDIGIT(line[0]))
-			{
-				// XML File format
-				while (fgets(line,sizeof(line),fp))
-					if (strstr(line,"revision=")) break;
-				if (sscanf(line," %*[^\"]\"%d%*[^\n]", &rev) == 1) {
-					snprintf(svn_version_buffer, sizeof(svn_version_buffer), "%d", rev);
-				}
-			}
-			else
-			{
-				// Bin File format
-				if ( fgets(line, sizeof(line), fp) == NULL ) { printf("Can't get bin name\n"); } // Get the name
-				if ( fgets(line, sizeof(line), fp) == NULL ) { printf("Can't get entries kind\n"); } // Get the entries kind
-				if(fgets(line, sizeof(line), fp)) // Get the rev numver
-				{
-					snprintf(svn_version_buffer, sizeof(svn_version_buffer), "%d", atoi(line));
-				}
-			}
-		}
-		fclose(fp);
-
-		if( svn_version_buffer[0] != '\0' )
-			return svn_version_buffer;
-	}
-
-	// fallback
-	snprintf(svn_version_buffer, sizeof(svn_version_buffer), "Unknown");
-	return svn_version_buffer;
+    static char svn_version_buffer[16] = "";
+    FILE *fp;
+
+    if (svn_version_buffer[0] != '\0')
+        return svn_version_buffer;
+
+    // subversion 1.7 uses a sqlite3 database
+    // FIXME this is hackish at best...
+    // - ignores database file structure
+    // - assumes the data in NODES.dav_cache column ends with "!svn/ver/<revision>/<path>)"
+    // - since it's a cache column, the data might not even exist
+    if ((fp = fopen(".svn"PATHSEP_STR"wc.db", "rb")) != NULL || (fp = fopen(".."PATHSEP_STR".svn"PATHSEP_STR"wc.db", "rb")) != NULL) {
+#ifndef SVNNODEPATH
+        //not sure how to handle branches, so i'll leave this overridable define until a better solution comes up
+#define SVNNODEPATH trunk
+#endif
+        const char *prefix = "!svn/ver/";
+        const char *postfix = "/"EXPAND_AND_QUOTE(SVNNODEPATH)")"; // there should exist only 1 entry like this
+        size_t prefix_len = strlen(prefix);
+        size_t postfix_len = strlen(postfix);
+        size_t i,j,len;
+        char *buffer;
+
+        // read file to buffer
+        fseek(fp, 0, SEEK_END);
+        len = ftell(fp);
+        buffer = (char *)aMalloc(len + 1);
+        fseek(fp, 0, SEEK_SET);
+        len = fread(buffer, 1, len, fp);
+        buffer[len] = '\0';
+        fclose(fp);
+
+        // parse buffer
+        for (i = prefix_len + 1; i + postfix_len <= len; ++i) {
+            if (buffer[i] != postfix[0] || memcmp(buffer + i, postfix, postfix_len) != 0)
+                continue; // postfix missmatch
+            for (j = i; j > 0; --j) {
+                // skip digits
+                if (!ISDIGIT(buffer[j - 1]))
+                    break;
+            }
+            if (memcmp(buffer + j - prefix_len, prefix, prefix_len) != 0)
+                continue; // prefix missmatch
+            // done
+            snprintf(svn_version_buffer, sizeof(svn_version_buffer), "%d", atoi(buffer + j));
+            break;
+        }
+        aFree(buffer);
+
+        if (svn_version_buffer[0] != '\0')
+            return svn_version_buffer;
+    }
+
+    // subversion 1.6 and older?
+    if ((fp = fopen(".svn/entries", "r")) != NULL) {
+        char line[1024];
+        int rev;
+        // Check the version
+        if (fgets(line, sizeof(line), fp)) {
+            if (!ISDIGIT(line[0])) {
+                // XML File format
+                while (fgets(line,sizeof(line),fp))
+                    if (strstr(line,"revision=")) break;
+                if (sscanf(line," %*[^\"]\"%d%*[^\n]", &rev) == 1) {
+                    snprintf(svn_version_buffer, sizeof(svn_version_buffer), "%d", rev);
+                }
+            } else {
+                // Bin File format
+                if (fgets(line, sizeof(line), fp) == NULL) {
+                    printf("Can't get bin name\n");    // Get the name
+                }
+                if (fgets(line, sizeof(line), fp) == NULL) {
+                    printf("Can't get entries kind\n");    // Get the entries kind
+                }
+                if (fgets(line, sizeof(line), fp)) { // Get the rev numver
+                    snprintf(svn_version_buffer, sizeof(svn_version_buffer), "%d", atoi(line));
+                }
+            }
+        }
+        fclose(fp);
+
+        if (svn_version_buffer[0] != '\0')
+            return svn_version_buffer;
+    }
+
+    // fallback
+    snprintf(svn_version_buffer, sizeof(svn_version_buffer), "Unknown");
+    return svn_version_buffer;
 }
 #endif
 
 /*======================================
- *	CORE : Display title
+ *  CORE : Display title
  *  ASCII By CalciumKid 1/12/2011
  *--------------------------------------*/
-static void display_title(void) {
-	//ClearScreen(); // clear screen and go up/left (0, 0 position in text)
-
-	ShowMessage("\n");
-	ShowMessage(""CL_PASS"     "CL_BOLD"                                                                 "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"       "CL_BT_WHITE"            rAthena Development Team presents                  "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"     "CL_BOLD"                 ___   __  __                                    "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"     "CL_BOLD"           _____/   | / /_/ /_  ___  ____  ____ _                "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"     "CL_BOLD"          / ___/ /| |/ __/ __ \\/ _ \\/ __ \\/ __ `/                "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"     "CL_BOLD"         / /  / ___ / /_/ / / /  __/ / / / /_/ /                 "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"     "CL_BOLD"        /_/  /_/  |_\\__/_/ /_/\\___/_/ /_/\\__,_/                  "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"     "CL_BOLD"                                                                 "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"       "CL_GREEN"              http://rathena.org/board/                        "CL_PASS""CL_CLL""CL_NORMAL"\n");
-	ShowMessage(""CL_PASS"     "CL_BOLD"                                                                 "CL_PASS""CL_CLL""CL_NORMAL"\n");
-
-	ShowInfo("SVN Revision: '"CL_WHITE"%s"CL_RESET"'.\n", get_svn_revision());
+static void display_title(void)
+{
+    //ClearScreen(); // clear screen and go up/left (0, 0 position in text)
+
+    ShowMessage("\n");
+    ShowMessage(""CL_PASS"     "CL_BOLD"                                                                 "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"       "CL_BT_WHITE"            rAthena Development Team presents                  "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"     "CL_BOLD"                 ___   __  __                                    "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"     "CL_BOLD"           _____/   | / /_/ /_  ___  ____  ____ _                "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"     "CL_BOLD"          / ___/ /| |/ __/ __ \\/ _ \\/ __ \\/ __ `/                "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"     "CL_BOLD"         / /  / ___ / /_/ / / /  __/ / / / /_/ /                 "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"     "CL_BOLD"        /_/  /_/  |_\\__/_/ /_/\\___/_/ /_/\\__,_/                  "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"     "CL_BOLD"                                                                 "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"       "CL_GREEN"              http://rathena.org/board/                        "CL_PASS""CL_CLL""CL_NORMAL"\n");
+    ShowMessage(""CL_PASS"     "CL_BOLD"                                                                 "CL_PASS""CL_CLL""CL_NORMAL"\n");
+
+    ShowInfo("SVN Revision: '"CL_WHITE"%s"CL_RESET"'.\n", get_svn_revision());
 }
 
 // Warning if executed as superuser (root)
@@ -284,72 +280,73 @@ void usercheck(void)
 {
 #ifndef _WIN32
     if (geteuid() == 0) {
-		ShowWarning ("You are running rAthena with root privileges, it is not necessary.\n");
+        ShowWarning("You are running rAthena with root privileges, it is not necessary.\n");
     }
 #endif
 }
 
 /*======================================
- *	CORE : MAINROUTINE
+ *  CORE : MAINROUTINE
  *--------------------------------------*/
-int main (int argc, char **argv)
+int main(int argc, char **argv)
 {
-	{// initialize program arguments
-		char *p1 = SERVER_NAME = argv[0];
-		char *p2 = p1;
-		while ((p1 = strchr(p2, '/')) != NULL || (p1 = strchr(p2, '\\')) != NULL)
-		{
-			SERVER_NAME = ++p1;
-			p2 = p1;
-		}
-		arg_c = argc;
-		arg_v = argv;
-	}
-
-	malloc_init();// needed for Show* in display_title() [FlavioJS]
+    {
+        // initialize program arguments
+        char *p1 = SERVER_NAME = argv[0];
+        char *p2 = p1;
+        while ((p1 = strchr(p2, '/')) != NULL || (p1 = strchr(p2, '\\')) != NULL) {
+            SERVER_NAME = ++p1;
+            p2 = p1;
+        }
+        arg_c = argc;
+        arg_v = argv;
+    }
+
+    malloc_init();// needed for Show* in display_title() [FlavioJS]
 
 #ifdef MINICORE // minimalist Core
-	display_title();
-	usercheck();
-	do_init(argc,argv);
-	do_final();
+    display_title();
+    usercheck();
+    do_init(argc,argv);
+    do_final();
 #else// not MINICORE
-	set_server_type();
-	display_title();
-	usercheck();
+    set_server_type();
+    display_title();
+    usercheck();
 
-	rathread_init();
-	mempool_init();
-	db_init();
-	signals_init();
+    rathread_init();
+    mempool_init();
+    db_init();
+    signals_init();
 
 #ifdef _WIN32
-	cevents_init();
+    cevents_init();
 #endif
 
-	timer_init();
-	socket_init();
+    timer_init();
+    socket_init();
 
-	do_init(argc,argv);
+    do_init(argc,argv);
 
-	{// Main runtime cycle
-		int next;
-		while (runflag != CORE_ST_STOP) {
-			next = do_timer(gettick_nocache());
-			do_sockets(next);
-		}
-	}
+    {
+        // Main runtime cycle
+        int next;
+        while (runflag != CORE_ST_STOP) {
+            next = do_timer(gettick_nocache());
+            do_sockets(next);
+        }
+    }
 
-	do_final();
+    do_final();
 
-	timer_final();
-	socket_final();
-	db_final();
-	mempool_final();
-	rathread_final();
+    timer_final();
+    socket_final();
+    db_final();
+    mempool_final();
+    rathread_final();
 #endif
 
-	malloc_final();
+    malloc_final();
 
-	return 0;
+    return 0;
 }

+ 14 - 15
src/common/core.h

@@ -1,14 +1,14 @@
 // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
 // For more information, see LICENCE in the main folder
 
-#ifndef	_CORE_H_
-#define	_CORE_H_
+#ifndef _CORE_H_
+#define _CORE_H_
 
 extern int arg_c;
 extern char **arg_v;
 
 #if defined(BUILDBOT)
-	extern int buildbotflag;
+extern int buildbotflag;
 #endif
 
 /// @see E_CORE_ST
@@ -16,28 +16,27 @@ extern int runflag;
 extern char *SERVER_NAME;
 
 enum {
-	ATHENA_SERVER_NONE = 0,	// not defined
-	ATHENA_SERVER_LOGIN	= 1,	// login server
-	ATHENA_SERVER_CHAR = 2,	// char server
-	ATHENA_SERVER_INTER	= 4,	// inter server
-	ATHENA_SERVER_MAP = 8,	// map server
+    ATHENA_SERVER_NONE = 0, // not defined
+    ATHENA_SERVER_LOGIN = 1,    // login server
+    ATHENA_SERVER_CHAR = 2, // char server
+    ATHENA_SERVER_INTER = 4,    // inter server
+    ATHENA_SERVER_MAP = 8,  // map server
 };
 
 extern char SERVER_TYPE;
 
-extern int parse_console(const char* buf);
+extern int parse_console(const char *buf);
 extern const char *get_svn_revision(void);
-extern int do_init(int,char**);
+extern int do_init(int,char **);
 extern void set_server_type(void);
 extern void do_abort(void);
 extern void do_final(void);
 
 /// The main loop continues until runflag is CORE_ST_STOP
-enum E_CORE_ST
-{
-	CORE_ST_STOP = 0,
-	CORE_ST_RUN,
-	CORE_ST_LAST
+enum E_CORE_ST {
+    CORE_ST_STOP = 0,
+    CORE_ST_RUN,
+    CORE_ST_LAST
 };
 
 /// Called when a terminate signal is received. (Ctrl+C pressed)

File diff suppressed because it is too large
+ 453 - 453
src/common/db.c


File diff suppressed because it is too large
+ 400 - 401
src/common/db.h


+ 155 - 161
src/common/des.c

@@ -12,207 +12,201 @@
 
 /// Bitmask for accessing individual bits of a byte.
 static const uint8_t mask[8] = {
-	0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01
+    0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01
 };
 
 
 /// Initial permutation (IP).
-static void IP(BIT64* src)
+static void IP(BIT64 *src)
 {
-	BIT64 tmp = {{0}};
-
-	static const uint8_t ip_table[64] = {
-		58, 50, 42, 34, 26, 18, 10,  2,
-		60, 52, 44, 36, 28, 20, 12,  4,
-		62, 54, 46, 38, 30, 22, 14,  6,
-		64, 56, 48, 40, 32, 24, 16,  8,
-		57, 49, 41, 33, 25, 17,  9,  1,
-		59, 51, 43, 35, 27, 19, 11,  3,
-		61, 53, 45, 37, 29, 21, 13,  5,
-		63, 55, 47, 39, 31, 23, 15,  7,
-	};
-
-	size_t i;
-	for( i = 0; i < ARRAYLENGTH(ip_table); ++i )
-	{
-		uint8_t j = ip_table[i] - 1;
-		if( src->b[(j >> 3) & 7] &  mask[j & 7] )
-			tmp .b[(i >> 3) & 7] |= mask[i & 7];
-	}
-
-	*src = tmp;
+    BIT64 tmp = {{0}};
+
+    static const uint8_t ip_table[64] = {
+        58, 50, 42, 34, 26, 18, 10,  2,
+        60, 52, 44, 36, 28, 20, 12,  4,
+        62, 54, 46, 38, 30, 22, 14,  6,
+        64, 56, 48, 40, 32, 24, 16,  8,
+        57, 49, 41, 33, 25, 17,  9,  1,
+        59, 51, 43, 35, 27, 19, 11,  3,
+        61, 53, 45, 37, 29, 21, 13,  5,
+        63, 55, 47, 39, 31, 23, 15,  7,
+    };
+
+    size_t i;
+    for (i = 0; i < ARRAYLENGTH(ip_table); ++i) {
+        uint8_t j = ip_table[i] - 1;
+        if (src->b[(j >> 3) & 7] &  mask[j & 7])
+            tmp .b[(i >> 3) & 7] |= mask[i & 7];
+    }
+
+    *src = tmp;
 }
 
 
 /// Final permutation (IP^-1).
-static void FP(BIT64* src)
+static void FP(BIT64 *src)
 {
-	BIT64 tmp = {{0}};
-
-	static const uint8_t fp_table[64] = {
-		40,  8, 48, 16, 56, 24, 64, 32,
-		39,  7, 47, 15, 55, 23, 63, 31,
-		38,  6, 46, 14, 54, 22, 62, 30,
-		37,  5, 45, 13, 53, 21, 61, 29,
-		36,  4, 44, 12, 52, 20, 60, 28,
-		35,  3, 43, 11, 51, 19, 59, 27,
-		34,  2, 42, 10, 50, 18, 58, 26,
-		33,  1, 41,  9, 49, 17, 57, 25,
-	};
-
-	size_t i;
-	for( i = 0; i < ARRAYLENGTH(fp_table); ++i )
-	{
-		uint8_t j = fp_table[i] - 1;
-		if( src->b[(j >> 3) & 7] &  mask[j & 7] )
-			tmp .b[(i >> 3) & 7] |= mask[i & 7];
-	}
-
-	*src = tmp;
+    BIT64 tmp = {{0}};
+
+    static const uint8_t fp_table[64] = {
+        40,  8, 48, 16, 56, 24, 64, 32,
+        39,  7, 47, 15, 55, 23, 63, 31,
+        38,  6, 46, 14, 54, 22, 62, 30,
+        37,  5, 45, 13, 53, 21, 61, 29,
+        36,  4, 44, 12, 52, 20, 60, 28,
+        35,  3, 43, 11, 51, 19, 59, 27,
+        34,  2, 42, 10, 50, 18, 58, 26,
+        33,  1, 41,  9, 49, 17, 57, 25,
+    };
+
+    size_t i;
+    for (i = 0; i < ARRAYLENGTH(fp_table); ++i) {
+        uint8_t j = fp_table[i] - 1;
+        if (src->b[(j >> 3) & 7] &  mask[j & 7])
+            tmp .b[(i >> 3) & 7] |= mask[i & 7];
+    }
+
+    *src = tmp;
 }
 
 
 /// Expansion (E).
 /// Expands upper four 8-bits (32b) into eight 6-bits (48b).
-static void E(BIT64* src)
+static void E(BIT64 *src)
 {
-	BIT64 tmp = {{0}};
-
-if( false )
-{// original
-	static const uint8_t expand_table[48] = {
-		32,  1,  2,  3,  4,  5,
-		 4,  5,  6,  7,  8,  9,
-		 8,  9, 10, 11, 12, 13,
-		12, 13, 14, 15, 16, 17,
-		16, 17, 18, 19, 20, 21,
-		20, 21, 22, 23, 24, 25,
-		24, 25, 26, 27, 28, 29,
-		28, 29, 30, 31, 32,  1,
-	};
-
-	size_t i;
-	for( i = 0; i < ARRAYLENGTH(expand_table); ++i )
-	{
-		uint8_t j = expand_table[i] - 1;
-		if( src->b[j / 8 + 4] &  mask[j % 8] )
-			tmp .b[i / 6 + 0] |= mask[i % 6];
-	}
-}
-else
-{// optimized
-	tmp.b[0] = ((src->b[7]<<5) | (src->b[4]>>3)) & 0x3f;	// ..0 vutsr
-	tmp.b[1] = ((src->b[4]<<1) | (src->b[5]>>7)) & 0x3f;	// ..srqpo n
-	tmp.b[2] = ((src->b[4]<<5) | (src->b[5]>>3)) & 0x3f;	// ..o nmlkj
-	tmp.b[3] = ((src->b[5]<<1) | (src->b[6]>>7)) & 0x3f;	// ..kjihg f
-	tmp.b[4] = ((src->b[5]<<5) | (src->b[6]>>3)) & 0x3f;	// ..g fedcb
-	tmp.b[5] = ((src->b[6]<<1) | (src->b[7]>>7)) & 0x3f;	// ..cba98 7
-	tmp.b[6] = ((src->b[6]<<5) | (src->b[7]>>3)) & 0x3f;	// ..8 76543
-	tmp.b[7] = ((src->b[7]<<1) | (src->b[4]>>7)) & 0x3f;	// ..43210 v
-}
-
-	*src = tmp;
+    BIT64 tmp = {{0}};
+
+    if (false) {
+        // original
+        static const uint8_t expand_table[48] = {
+            32,  1,  2,  3,  4,  5,
+            4,  5,  6,  7,  8,  9,
+            8,  9, 10, 11, 12, 13,
+            12, 13, 14, 15, 16, 17,
+            16, 17, 18, 19, 20, 21,
+            20, 21, 22, 23, 24, 25,
+            24, 25, 26, 27, 28, 29,
+            28, 29, 30, 31, 32,  1,
+        };
+
+        size_t i;
+        for (i = 0; i < ARRAYLENGTH(expand_table); ++i) {
+            uint8_t j = expand_table[i] - 1;
+            if (src->b[j / 8 + 4] &  mask[j % 8])
+                tmp .b[i / 6 + 0] |= mask[i % 6];
+        }
+    } else {
+        // optimized
+        tmp.b[0] = ((src->b[7]<<5) | (src->b[4]>>3)) & 0x3f;    // ..0 vutsr
+        tmp.b[1] = ((src->b[4]<<1) | (src->b[5]>>7)) & 0x3f;    // ..srqpo n
+        tmp.b[2] = ((src->b[4]<<5) | (src->b[5]>>3)) & 0x3f;    // ..o nmlkj
+        tmp.b[3] = ((src->b[5]<<1) | (src->b[6]>>7)) & 0x3f;    // ..kjihg f
+        tmp.b[4] = ((src->b[5]<<5) | (src->b[6]>>3)) & 0x3f;    // ..g fedcb
+        tmp.b[5] = ((src->b[6]<<1) | (src->b[7]>>7)) & 0x3f;    // ..cba98 7
+        tmp.b[6] = ((src->b[6]<<5) | (src->b[7]>>3)) & 0x3f;    // ..8 76543
+        tmp.b[7] = ((src->b[7]<<1) | (src->b[4]>>7)) & 0x3f;    // ..43210 v
+    }
+
+    *src = tmp;
 }
 
 
 /// Transposition (P-BOX).
-static void TP(BIT64* src)
+static void TP(BIT64 *src)
 {
-	BIT64 tmp = {{0}};
-
-	static const uint8_t tp_table[32] = {
-		16,  7, 20, 21,
-		29, 12, 28, 17,
-		 1, 15, 23, 26,
-		 5, 18, 31, 10,
-		 2,  8, 24, 14,
-		32, 27,  3,  9,
-		19, 13, 30,  6,
-		22, 11,  4, 25,
-	};
-
-	size_t i;
-	for( i = 0; i < ARRAYLENGTH(tp_table); ++i )
-	{
-		uint8_t j = tp_table[i] - 1;
-		if( src->b[(j >> 3) + 0] &  mask[j & 7] )
-			tmp .b[(i >> 3) + 4] |= mask[i & 7];
-	}
-
-	*src = tmp;
+    BIT64 tmp = {{0}};
+
+    static const uint8_t tp_table[32] = {
+        16,  7, 20, 21,
+        29, 12, 28, 17,
+        1, 15, 23, 26,
+        5, 18, 31, 10,
+        2,  8, 24, 14,
+        32, 27,  3,  9,
+        19, 13, 30,  6,
+        22, 11,  4, 25,
+    };
+
+    size_t i;
+    for (i = 0; i < ARRAYLENGTH(tp_table); ++i) {
+        uint8_t j = tp_table[i] - 1;
+        if (src->b[(j >> 3) + 0] &  mask[j & 7])
+            tmp .b[(i >> 3) + 4] |= mask[i & 7];
+    }
+
+    *src = tmp;
 }
 
 
 /// Substitution boxes (S-boxes).
 /// NOTE: This implementation was optimized to process two nibbles in one step (twice as fast).
-static void SBOX(BIT64* src)
+static void SBOX(BIT64 *src)
 {
-	BIT64 tmp = {{0}};
-
-	static const uint8_t s_table[4][64] = {
-		  {
-			0xef, 0x03, 0x41, 0xfd, 0xd8, 0x74, 0x1e, 0x47,  0x26, 0xef, 0xfb, 0x22, 0xb3, 0xd8, 0x84, 0x1e,
-			0x39, 0xac, 0xa7, 0x60, 0x62, 0xc1, 0xcd, 0xba,  0x5c, 0x96, 0x90, 0x59, 0x05, 0x3b, 0x7a, 0x85,
-			0x40, 0xfd, 0x1e, 0xc8, 0xe7, 0x8a, 0x8b, 0x21,  0xda, 0x43, 0x64, 0x9f, 0x2d, 0x14, 0xb1, 0x72,
-			0xf5, 0x5b, 0xc8, 0xb6, 0x9c, 0x37, 0x76, 0xec,  0x39, 0xa0, 0xa3, 0x05, 0x52, 0x6e, 0x0f, 0xd9,
-		},{
-			0xa7, 0xdd, 0x0d, 0x78, 0x9e, 0x0b, 0xe3, 0x95,  0x60, 0x36, 0x36, 0x4f, 0xf9, 0x60, 0x5a, 0xa3,
-			0x11, 0x24, 0xd2, 0x87, 0xc8, 0x52, 0x75, 0xec,  0xbb, 0xc1, 0x4c, 0xba, 0x24, 0xfe, 0x8f, 0x19,
-			0xda, 0x13, 0x66, 0xaf, 0x49, 0xd0, 0x90, 0x06,  0x8c, 0x6a, 0xfb, 0x91, 0x37, 0x8d, 0x0d, 0x78,
-			0xbf, 0x49, 0x11, 0xf4, 0x23, 0xe5, 0xce, 0x3b,  0x55, 0xbc, 0xa2, 0x57, 0xe8, 0x22, 0x74, 0xce,
-		},{
-			0x2c, 0xea, 0xc1, 0xbf, 0x4a, 0x24, 0x1f, 0xc2,  0x79, 0x47, 0xa2, 0x7c, 0xb6, 0xd9, 0x68, 0x15,
-			0x80, 0x56, 0x5d, 0x01, 0x33, 0xfd, 0xf4, 0xae,  0xde, 0x30, 0x07, 0x9b, 0xe5, 0x83, 0x9b, 0x68,
-			0x49, 0xb4, 0x2e, 0x83, 0x1f, 0xc2, 0xb5, 0x7c,  0xa2, 0x19, 0xd8, 0xe5, 0x7c, 0x2f, 0x83, 0xda,
-			0xf7, 0x6b, 0x90, 0xfe, 0xc4, 0x01, 0x5a, 0x97,  0x61, 0xa6, 0x3d, 0x40, 0x0b, 0x58, 0xe6, 0x3d,
-		},{
-			0x4d, 0xd1, 0xb2, 0x0f, 0x28, 0xbd, 0xe4, 0x78,  0xf6, 0x4a, 0x0f, 0x93, 0x8b, 0x17, 0xd1, 0xa4,
-			0x3a, 0xec, 0xc9, 0x35, 0x93, 0x56, 0x7e, 0xcb,  0x55, 0x20, 0xa0, 0xfe, 0x6c, 0x89, 0x17, 0x62,
-			0x17, 0x62, 0x4b, 0xb1, 0xb4, 0xde, 0xd1, 0x87,  0xc9, 0x14, 0x3c, 0x4a, 0x7e, 0xa8, 0xe2, 0x7d,
-			0xa0, 0x9f, 0xf6, 0x5c, 0x6a, 0x09, 0x8d, 0xf0,  0x0f, 0xe3, 0x53, 0x25, 0x95, 0x36, 0x28, 0xcb,
-		}
-	};
-
-	size_t i;
-	for( i = 0; i < ARRAYLENGTH(s_table); ++i )
-	{
-		tmp.b[i] = (s_table[i][src->b[i*2+0]] & 0xf0)
-		         | (s_table[i][src->b[i*2+1]] & 0x0f);
-	}
-
-	*src = tmp;
+    BIT64 tmp = {{0}};
+
+    static const uint8_t s_table[4][64] = {
+        {
+            0xef, 0x03, 0x41, 0xfd, 0xd8, 0x74, 0x1e, 0x47,  0x26, 0xef, 0xfb, 0x22, 0xb3, 0xd8, 0x84, 0x1e,
+            0x39, 0xac, 0xa7, 0x60, 0x62, 0xc1, 0xcd, 0xba,  0x5c, 0x96, 0x90, 0x59, 0x05, 0x3b, 0x7a, 0x85,
+            0x40, 0xfd, 0x1e, 0xc8, 0xe7, 0x8a, 0x8b, 0x21,  0xda, 0x43, 0x64, 0x9f, 0x2d, 0x14, 0xb1, 0x72,
+            0xf5, 0x5b, 0xc8, 0xb6, 0x9c, 0x37, 0x76, 0xec,  0x39, 0xa0, 0xa3, 0x05, 0x52, 0x6e, 0x0f, 0xd9,
+        },{
+            0xa7, 0xdd, 0x0d, 0x78, 0x9e, 0x0b, 0xe3, 0x95,  0x60, 0x36, 0x36, 0x4f, 0xf9, 0x60, 0x5a, 0xa3,
+            0x11, 0x24, 0xd2, 0x87, 0xc8, 0x52, 0x75, 0xec,  0xbb, 0xc1, 0x4c, 0xba, 0x24, 0xfe, 0x8f, 0x19,
+            0xda, 0x13, 0x66, 0xaf, 0x49, 0xd0, 0x90, 0x06,  0x8c, 0x6a, 0xfb, 0x91, 0x37, 0x8d, 0x0d, 0x78,
+            0xbf, 0x49, 0x11, 0xf4, 0x23, 0xe5, 0xce, 0x3b,  0x55, 0xbc, 0xa2, 0x57, 0xe8, 0x22, 0x74, 0xce,
+        },{
+            0x2c, 0xea, 0xc1, 0xbf, 0x4a, 0x24, 0x1f, 0xc2,  0x79, 0x47, 0xa2, 0x7c, 0xb6, 0xd9, 0x68, 0x15,
+            0x80, 0x56, 0x5d, 0x01, 0x33, 0xfd, 0xf4, 0xae,  0xde, 0x30, 0x07, 0x9b, 0xe5, 0x83, 0x9b, 0x68,
+            0x49, 0xb4, 0x2e, 0x83, 0x1f, 0xc2, 0xb5, 0x7c,  0xa2, 0x19, 0xd8, 0xe5, 0x7c, 0x2f, 0x83, 0xda,
+            0xf7, 0x6b, 0x90, 0xfe, 0xc4, 0x01, 0x5a, 0x97,  0x61, 0xa6, 0x3d, 0x40, 0x0b, 0x58, 0xe6, 0x3d,
+        },{
+            0x4d, 0xd1, 0xb2, 0x0f, 0x28, 0xbd, 0xe4, 0x78,  0xf6, 0x4a, 0x0f, 0x93, 0x8b, 0x17, 0xd1, 0xa4,
+            0x3a, 0xec, 0xc9, 0x35, 0x93, 0x56, 0x7e, 0xcb,  0x55, 0x20, 0xa0, 0xfe, 0x6c, 0x89, 0x17, 0x62,
+            0x17, 0x62, 0x4b, 0xb1, 0xb4, 0xde, 0xd1, 0x87,  0xc9, 0x14, 0x3c, 0x4a, 0x7e, 0xa8, 0xe2, 0x7d,
+            0xa0, 0x9f, 0xf6, 0x5c, 0x6a, 0x09, 0x8d, 0xf0,  0x0f, 0xe3, 0x53, 0x25, 0x95, 0x36, 0x28, 0xcb,
+        }
+    };
+
+    size_t i;
+    for (i = 0; i < ARRAYLENGTH(s_table); ++i) {
+        tmp.b[i] = (s_table[i][src->b[i*2+0]] & 0xf0)
+                   | (s_table[i][src->b[i*2+1]] & 0x0f);
+    }
+
+    *src = tmp;
 }
 
 
 /// DES round function.
 /// XORs src[0..3] with TP(SBOX(E(src[4..7]))).
-static void RoundFunction(BIT64* src)
+static void RoundFunction(BIT64 *src)
 {
-	BIT64 tmp = *src;
-	E(&tmp);
-	SBOX(&tmp);
-	TP(&tmp);
-
-	src->b[0] ^= tmp.b[4];
-	src->b[1] ^= tmp.b[5];
-	src->b[2] ^= tmp.b[6];
-	src->b[3] ^= tmp.b[7];
+    BIT64 tmp = *src;
+    E(&tmp);
+    SBOX(&tmp);
+    TP(&tmp);
+
+    src->b[0] ^= tmp.b[4];
+    src->b[1] ^= tmp.b[5];
+    src->b[2] ^= tmp.b[6];
+    src->b[3] ^= tmp.b[7];
 }
 
 
-void des_decrypt_block(BIT64* block)
+void des_decrypt_block(BIT64 *block)
 {
-	IP(block);
-	RoundFunction(block);
-	FP(block);
+    IP(block);
+    RoundFunction(block);
+    FP(block);
 }
 
 
-void des_decrypt(unsigned char* data, size_t size)
+void des_decrypt(unsigned char *data, size_t size)
 {
-	BIT64* p = (BIT64*)data;
-	size_t i;
+    BIT64 *p = (BIT64 *)data;
+    size_t i;
 
-	for( i = 0; i*8 < size; i += 8 )
-		des_decrypt_block(p);
+    for (i = 0; i*8 < size; i += 8)
+        des_decrypt_block(p);
 }

+ 7 - 5
src/common/des.h

@@ -1,15 +1,17 @@
 // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
 // For more information, see LICENCE in the main folder
-#ifndef	_DES_H_
-#define	_DES_H_
+#ifndef _DES_H_
+#define _DES_H_
 
 
 /// One 64-bit block.
-typedef struct BIT64 { uint8_t b[8]; } BIT64;
+typedef struct BIT64 {
+    uint8_t b[8];
+} BIT64;
 
 
-void des_decrypt_block(BIT64* block);
-void des_decrypt(unsigned char* data, size_t size);
+void des_decrypt_block(BIT64 *block);
+void des_decrypt(unsigned char *data, size_t size);
 
 
 #endif // _DES_H_

+ 149 - 167
src/common/ers.c

@@ -51,54 +51,51 @@
 #define ERS_ROOT_SIZE 256
 #define ERS_BLOCK_ENTRIES 4096
 
-struct ers_list
-{
-	struct ers_list *Next;
+struct ers_list {
+    struct ers_list *Next;
 };
 
-typedef struct ers_cache
-{
-	// Allocated object size, including ers_list size
-	unsigned int ObjectSize;
+typedef struct ers_cache {
+    // Allocated object size, including ers_list size
+    unsigned int ObjectSize;
+
+    // Number of ers_instances referencing this
+    int ReferenceCount;
 
-	// Number of ers_instances referencing this
-	int ReferenceCount;
+    // Reuse linked list
+    struct ers_list *ReuseList;
 
-	// Reuse linked list
-	struct ers_list *ReuseList;
+    // Memory blocks array
+    unsigned char **Blocks;
 
-	// Memory blocks array
-	unsigned char **Blocks;
+    // Max number of blocks
+    unsigned int Max;
 
-	// Max number of blocks 
-	unsigned int Max;
+    // Free objects count
+    unsigned int Free;
 
-	// Free objects count
-	unsigned int Free;
-	
-	// Used objects count
-	unsigned int Used;
+    // Used objects count
+    unsigned int Used;
 
-	// Linked list
-	struct ers_cache *Next, *Prev;
+    // Linked list
+    struct ers_cache *Next, *Prev;
 } ers_cache_t;
 
-typedef struct
-{
-	// Interface to ERS
-	struct eri VTable;
-	
-	// Name, used for debbuging purpouses
-	char *Name;
+typedef struct {
+    // Interface to ERS
+    struct eri VTable;
+
+    // Name, used for debbuging purpouses
+    char *Name;
 
-	// Misc options
-	enum ERSOptions Options;
+    // Misc options
+    enum ERSOptions Options;
 
-	// Our cache
-	ers_cache_t *Cache;
+    // Our cache
+    ers_cache_t *Cache;
 
-	// Count of objects in use, used for detecting memory leaks
-	unsigned int Count;
+    // Count of objects in use, used for detecting memory leaks
+    unsigned int Count;
 } ers_instance_t;
 
 
@@ -107,186 +104,171 @@ static ers_cache_t *CacheList;
 
 static ers_cache_t *ers_find_cache(unsigned int size)
 {
-	ers_cache_t *cache;
-
-	for (cache = CacheList; cache; cache = cache->Next)
-		if (cache->ObjectSize == size)
-			return cache;
-
-	CREATE(cache, ers_cache_t, 1);
-	cache->ObjectSize = size;
-	cache->ReferenceCount = 0;
-	cache->ReuseList = NULL;
-	cache->Blocks = NULL;
-	cache->Free = 0;
-	cache->Used = 0;
-	cache->Max = 0;
-	
-	if (CacheList == NULL)
-	{
-		CacheList = cache;
-	}
-	else
-	{
-		cache->Next = CacheList;
-		cache->Next->Prev = cache;
-		CacheList = cache;
-		CacheList->Prev = NULL;
-	}
-
-	return cache;
+    ers_cache_t *cache;
+
+    for (cache = CacheList; cache; cache = cache->Next)
+        if (cache->ObjectSize == size)
+            return cache;
+
+    CREATE(cache, ers_cache_t, 1);
+    cache->ObjectSize = size;
+    cache->ReferenceCount = 0;
+    cache->ReuseList = NULL;
+    cache->Blocks = NULL;
+    cache->Free = 0;
+    cache->Used = 0;
+    cache->Max = 0;
+
+    if (CacheList == NULL) {
+        CacheList = cache;
+    } else {
+        cache->Next = CacheList;
+        cache->Next->Prev = cache;
+        CacheList = cache;
+        CacheList->Prev = NULL;
+    }
+
+    return cache;
 }
 
 static void ers_free_cache(ers_cache_t *cache, bool remove)
 {
-	unsigned int i;
+    unsigned int i;
 
-	for (i = 0; i < cache->Used; i++)
-		aFree(cache->Blocks[i]);
+    for (i = 0; i < cache->Used; i++)
+        aFree(cache->Blocks[i]);
 
-	if (cache->Next)
-		cache->Next->Prev = cache->Prev;
+    if (cache->Next)
+        cache->Next->Prev = cache->Prev;
 
-	if (cache->Prev)
-		cache->Prev->Next = cache->Next;
-	else
-		CacheList = cache->Next;
+    if (cache->Prev)
+        cache->Prev->Next = cache->Next;
+    else
+        CacheList = cache->Next;
 
-	aFree(cache->Blocks);
-	aFree(cache);
+    aFree(cache->Blocks);
+    aFree(cache);
 }
 
 static void *ers_obj_alloc_entry(ERS self)
 {
-	ers_instance_t *instance = (ers_instance_t *)self;
-	void *ret;
-
-	if (instance == NULL) 
-	{
-		ShowError("ers_obj_alloc_entry: NULL object, aborting entry freeing.\n");
-		return NULL;
-	}
-
-	if (instance->Cache->ReuseList != NULL)
-	{
-		ret = (void *)((unsigned char *)instance->Cache->ReuseList + sizeof(struct ers_list));
-		instance->Cache->ReuseList = instance->Cache->ReuseList->Next;
-	} 
-	else if (instance->Cache->Free > 0) 
-	{
-		instance->Cache->Free--;
-		ret = &instance->Cache->Blocks[instance->Cache->Used - 1][instance->Cache->Free * instance->Cache->ObjectSize + sizeof(struct ers_list)];
-	} 
-	else 
-	{
-		if (instance->Cache->Used == instance->Cache->Max) 
-		{
-			instance->Cache->Max = (instance->Cache->Max * 4) + 3;
-			RECREATE(instance->Cache->Blocks, unsigned char *, instance->Cache->Max);
-		}
-
-		CREATE(instance->Cache->Blocks[instance->Cache->Used], unsigned char, instance->Cache->ObjectSize * ERS_BLOCK_ENTRIES);
-		instance->Cache->Used++;
-
-		instance->Cache->Free = ERS_BLOCK_ENTRIES -1;
-		ret = &instance->Cache->Blocks[instance->Cache->Used - 1][instance->Cache->Free * instance->Cache->ObjectSize + sizeof(struct ers_list)];
-	}
-
-	instance->Count++;
-
-	return ret;
+    ers_instance_t *instance = (ers_instance_t *)self;
+    void *ret;
+
+    if (instance == NULL) {
+        ShowError("ers_obj_alloc_entry: NULL object, aborting entry freeing.\n");
+        return NULL;
+    }
+
+    if (instance->Cache->ReuseList != NULL) {
+        ret = (void *)((unsigned char *)instance->Cache->ReuseList + sizeof(struct ers_list));
+        instance->Cache->ReuseList = instance->Cache->ReuseList->Next;
+    } else if (instance->Cache->Free > 0) {
+        instance->Cache->Free--;
+        ret = &instance->Cache->Blocks[instance->Cache->Used - 1][instance->Cache->Free * instance->Cache->ObjectSize + sizeof(struct ers_list)];
+    } else {
+        if (instance->Cache->Used == instance->Cache->Max) {
+            instance->Cache->Max = (instance->Cache->Max * 4) + 3;
+            RECREATE(instance->Cache->Blocks, unsigned char *, instance->Cache->Max);
+        }
+
+        CREATE(instance->Cache->Blocks[instance->Cache->Used], unsigned char, instance->Cache->ObjectSize * ERS_BLOCK_ENTRIES);
+        instance->Cache->Used++;
+
+        instance->Cache->Free = ERS_BLOCK_ENTRIES -1;
+        ret = &instance->Cache->Blocks[instance->Cache->Used - 1][instance->Cache->Free * instance->Cache->ObjectSize + sizeof(struct ers_list)];
+    }
+
+    instance->Count++;
+
+    return ret;
 }
 
 static void ers_obj_free_entry(ERS self, void *entry)
 {
-	ers_instance_t *instance = (ers_instance_t *)self;
-	struct ers_list *reuse = (struct ers_list *)((unsigned char *)entry - sizeof(struct ers_list));
-
-	if (instance == NULL) 
-	{
-		ShowError("ers_obj_free_entry: NULL object, aborting entry freeing.\n");
-		return;
-	} 
-	else if (entry == NULL) 
-	{
-		ShowError("ers_obj_free_entry: NULL entry, nothing to free.\n");
-		return;
-	}
-
-	reuse->Next = instance->Cache->ReuseList;
-	instance->Cache->ReuseList = reuse;
-	instance->Count--;
+    ers_instance_t *instance = (ers_instance_t *)self;
+    struct ers_list *reuse = (struct ers_list *)((unsigned char *)entry - sizeof(struct ers_list));
+
+    if (instance == NULL) {
+        ShowError("ers_obj_free_entry: NULL object, aborting entry freeing.\n");
+        return;
+    } else if (entry == NULL) {
+        ShowError("ers_obj_free_entry: NULL entry, nothing to free.\n");
+        return;
+    }
+
+    reuse->Next = instance->Cache->ReuseList;
+    instance->Cache->ReuseList = reuse;
+    instance->Count--;
 }
 
 static size_t ers_obj_entry_size(ERS self)
 {
-	ers_instance_t *instance = (ers_instance_t *)self;
+    ers_instance_t *instance = (ers_instance_t *)self;
 
-	if (instance == NULL) 
-	{
-		ShowError("ers_obj_entry_size: NULL object, aborting entry freeing.\n");
-		return 0;
-	} 
+    if (instance == NULL) {
+        ShowError("ers_obj_entry_size: NULL object, aborting entry freeing.\n");
+        return 0;
+    }
 
-	return instance->Cache->ObjectSize;
+    return instance->Cache->ObjectSize;
 }
 
 static void ers_obj_destroy(ERS self)
 {
-	ers_instance_t *instance = (ers_instance_t *)self;
+    ers_instance_t *instance = (ers_instance_t *)self;
 
-	if (instance == NULL) 
-	{
-		ShowError("ers_obj_destroy: NULL object, aborting entry freeing.\n");
-		return;
-	}
+    if (instance == NULL) {
+        ShowError("ers_obj_destroy: NULL object, aborting entry freeing.\n");
+        return;
+    }
 
-	if (instance->Count > 0)
-		if (!(instance->Options & ERS_OPT_CLEAR))
-			ShowWarning("Memory leak detected at ERS '%s', %d objects not freed.\n", instance->Name, instance->Count);
+    if (instance->Count > 0)
+        if (!(instance->Options & ERS_OPT_CLEAR))
+            ShowWarning("Memory leak detected at ERS '%s', %d objects not freed.\n", instance->Name, instance->Count);
 
-	if (--instance->Cache->ReferenceCount <= 0)
-		ers_free_cache(instance->Cache, true);
+    if (--instance->Cache->ReferenceCount <= 0)
+        ers_free_cache(instance->Cache, true);
 
-	aFree(instance);
+    aFree(instance);
 }
 
 ERS ers_new(uint32 size, char *name, enum ERSOptions options)
 {
-	ers_instance_t *instance;
-	CREATE(instance, ers_instance_t, 1);
+    ers_instance_t *instance;
+    CREATE(instance, ers_instance_t, 1);
 
-	size += sizeof(struct ers_list);
-	if (size % ERS_ALIGNED)
-		size += ERS_ALIGNED - size % ERS_ALIGNED;
+    size += sizeof(struct ers_list);
+    if (size % ERS_ALIGNED)
+        size += ERS_ALIGNED - size % ERS_ALIGNED;
 
-	instance->VTable.alloc = ers_obj_alloc_entry;
-	instance->VTable.free = ers_obj_free_entry;
-	instance->VTable.entry_size = ers_obj_entry_size;
-	instance->VTable.destroy = ers_obj_destroy;
+    instance->VTable.alloc = ers_obj_alloc_entry;
+    instance->VTable.free = ers_obj_free_entry;
+    instance->VTable.entry_size = ers_obj_entry_size;
+    instance->VTable.destroy = ers_obj_destroy;
 
-	instance->Name = name;
-	instance->Options = options;
+    instance->Name = name;
+    instance->Options = options;
 
-	instance->Cache = ers_find_cache(size);
-	instance->Cache->ReferenceCount++;
+    instance->Cache = ers_find_cache(size);
+    instance->Cache->ReferenceCount++;
 
-	instance->Count = 0;
+    instance->Count = 0;
 
-	return &instance->VTable;
+    return &instance->VTable;
 }
 
 void ers_report(void)
 {
-	// FIXME: Someone use this? Is it really needed?
+    // FIXME: Someone use this? Is it really needed?
 }
 
 void ers_force_destroy_all(void)
 {
-	ers_cache_t *cache;
-	
-	for (cache = CacheList; cache; cache = cache->Next)
-			ers_free_cache(cache, false);
+    ers_cache_t *cache;
+
+    for (cache = CacheList; cache; cache = cache->Next)
+        ers_free_cache(cache, false);
 }
 
 #endif

+ 53 - 53
src/common/ers.h

@@ -55,7 +55,7 @@
 /**
  * Define this to disable the Entry Reusage System.
  * All code except the typedef of ERInterface will be disabled.
- * To allow a smooth transition, 
+ * To allow a smooth transition,
  */
 //#define DISABLE_ERS
 
@@ -63,16 +63,16 @@
  * Entries are aligned to ERS_ALIGNED bytes in the blocks of entries.
  * By default it aligns to one byte, using the "natural order" of the entries.
  * This should NEVER be set to zero or less.
- * If greater than one, some memory can be wasted. This should never be needed 
+ * If greater than one, some memory can be wasted. This should never be needed
  * but is here just in case some aligment issues arise.
  */
 #ifndef ERS_ALIGNED
-#	define ERS_ALIGNED 1
+#   define ERS_ALIGNED 1
 #endif /* not ERS_ALIGN_ENTRY */
 
 enum ERSOptions {
-	ERS_OPT_NONE           = 0,
-	ERS_OPT_CLEAR          = 1,/* silently clears any entries left in the manager upon destruction */
+    ERS_OPT_NONE           = 0,
+    ERS_OPT_CLEAR          = 1,/* silently clears any entries left in the manager upon destruction */
 };
 
 /**
@@ -84,65 +84,65 @@ enum ERSOptions {
  */
 typedef struct eri {
 
-	/**
-	 * Allocate an entry from this entry manager.
-	 * If there are reusable entries available, it reuses one instead.
-	 * @param self Interface of the entry manager
-	 * @return An entry
-	 */
-	void *(*alloc)(struct eri *self);
-
-	/**
-	 * Free an entry allocated from this manager.
-	 * WARNING: Does not check if the entry was allocated by this manager.
-	 * Freeing such an entry can lead to unexpected behaviour.
-	 * @param self Interface of the entry manager
-	 * @param entry Entry to be freed
-	 */
-	void (*free)(struct eri *self, void *entry);
-
-	/**
-	 * Return the size of the entries allocated from this manager.
-	 * @param self Interface of the entry manager
-	 * @return Size of the entries of this manager in bytes
-	 */
-	size_t (*entry_size)(struct eri *self);
-
-	/**
-	 * Destroy this instance of the manager.
-	 * The manager is actually only destroyed when all the instances are destroyed.
-	 * When destroying the manager a warning is shown if the manager has 
-	 * missing/extra entries.
-	 * @param self Interface of the entry manager
-	 */
-	void (*destroy)(struct eri *self);
+    /**
+     * Allocate an entry from this entry manager.
+     * If there are reusable entries available, it reuses one instead.
+     * @param self Interface of the entry manager
+     * @return An entry
+     */
+    void *(*alloc)(struct eri *self);
+
+    /**
+     * Free an entry allocated from this manager.
+     * WARNING: Does not check if the entry was allocated by this manager.
+     * Freeing such an entry can lead to unexpected behaviour.
+     * @param self Interface of the entry manager
+     * @param entry Entry to be freed
+     */
+    void (*free)(struct eri *self, void *entry);
+
+    /**
+     * Return the size of the entries allocated from this manager.
+     * @param self Interface of the entry manager
+     * @return Size of the entries of this manager in bytes
+     */
+    size_t (*entry_size)(struct eri *self);
+
+    /**
+     * Destroy this instance of the manager.
+     * The manager is actually only destroyed when all the instances are destroyed.
+     * When destroying the manager a warning is shown if the manager has
+     * missing/extra entries.
+     * @param self Interface of the entry manager
+     */
+    void (*destroy)(struct eri *self);
 
 } *ERS;
 
 #ifdef DISABLE_ERS
 // Use memory manager to allocate/free and disable other interface functions
-#	define ers_alloc(obj,type) (type *)aMalloc(sizeof(type))
-#	define ers_free(obj,entry) aFree(entry)
-#	define ers_entry_size(obj) (size_t)0
-#	define ers_destroy(obj)
+#   define ers_alloc(obj,type) (type *)aMalloc(sizeof(type))
+#   define ers_free(obj,entry) aFree(entry)
+#   define ers_entry_size(obj) (size_t)0
+#   define ers_destroy(obj)
 // Disable the public functions
-#	define ers_new(size,name,options) NULL
-#	define ers_report()
-#	define ers_force_destroy_all()
+#   define ers_new(size,name,options) NULL
+#   define ers_report()
+#   define ers_force_destroy_all()
 #else /* not DISABLE_ERS */
-// These defines should be used to allow the code to keep working whenever 
+// These defines should be used to allow the code to keep working whenever
 // the system is disabled
-#	define ers_alloc(obj,type) (type *)(obj)->alloc(obj)
-#	define ers_free(obj,entry) (obj)->free((obj),(entry))
-#	define ers_entry_size(obj) (obj)->entry_size(obj)
-#	define ers_destroy(obj)    (obj)->destroy(obj)
+#   define ers_alloc(obj,type) (type *)(obj)->alloc(obj)
+#   define ers_free(obj,entry) (obj)->free((obj),(entry))
+#   define ers_entry_size(obj) (obj)->entry_size(obj)
+#   define ers_destroy(obj)    (obj)->destroy(obj)
 
 /**
  * Get a new instance of the manager that handles the specified entry size.
  * Size has to greater than 0.
- * If the specified size is smaller than a pointer, the size of a pointer is 
+ * If the specified size is smaller than a pointer, the size of a pointer is
  * used instead.
- * It's also aligned to ERS_ALIGNED bytes, so the smallest multiple of 
+ * It's also aligned to ERS_ALIGNED bytes, so the smallest multiple of
  * ERS_ALIGNED that is greater or equal to size is what's actually used.
  * @param The requested size of the entry in bytes
  * @return Interface of the object
@@ -152,7 +152,7 @@ ERS ers_new(uint32 size, char *name, enum ERSOptions options);
 /**
  * Print a report about the current state of the Entry Reusage System.
  * Shows information about the global system and each entry manager.
- * The number of entries are checked and a warning is shown if extra reusable 
+ * The number of entries are checked and a warning is shown if extra reusable
  * entries are found.
  * The extra entries are included in the count of reusable entries.
  */
@@ -163,7 +163,7 @@ void ers_report(void);
  * The system is left as if no instances or entries had ever been allocated.
  * All previous entries and instances of the managers become invalid.
  * The use of this is NOT recommended.
- * It should only be used in extreme situations to make shure all the memory 
+ * It should only be used in extreme situations to make shure all the memory
  * allocated by this system is released.
  */
 void ers_force_destroy_all(void);

+ 65 - 65
src/common/evdp.h

@@ -8,27 +8,27 @@ typedef struct EVDP_DATA EVDP_DATA;
 
 //#idef EVDP_EPOLL
 #include <sys/epoll.h>
-struct EVDP_DATA{
-	struct epoll_event ev_data;
-	bool ev_added;
+struct EVDP_DATA {
+    struct epoll_event ev_data;
+    bool ev_added;
 };
 //#endif
 
 
-enum EVDP_EVENTFLAGS{
-	EVDP_EVENT_IN = 1,	// Incomming data  
-	EVDP_EVENT_OUT = 2,	// Connection accepts writing.
-	EVDP_EVENT_HUP = 4	// Connection Closed.
+enum EVDP_EVENTFLAGS {
+    EVDP_EVENT_IN = 1,  // Incomming data
+    EVDP_EVENT_OUT = 2, // Connection accepts writing.
+    EVDP_EVENT_HUP = 4  // Connection Closed.
 };
 
-typedef struct EVDP_EVENT{
-	int32	events;	// due to performance reasons, this should be the first member.
-	int32	fd;	// Connection Identifier
+typedef struct EVDP_EVENT {
+    int32   events; // due to performance reasons, this should be the first member.
+    int32   fd; // Connection Identifier
 } EVDP_EVENT;
 
 
 
-/** 
+/**
  * Network Event Dispatcher Initialization / Finalization routines
  */
 void evdp_init();
@@ -38,56 +38,56 @@ void evdp_final();
 /**
  * Will Wait for events.
  *
- * @param *out_ev 		pointer to array in size at least of max_events.
- * @param max_events	max no of events to report with this call (coalesc)
- * @param timeout_ticks	max time to wait in ticks (milliseconds) 
+ * @param *out_ev       pointer to array in size at least of max_events.
+ * @param max_events    max no of events to report with this call (coalesc)
+ * @param timeout_ticks max time to wait in ticks (milliseconds)
  *
  * @Note:
- * 	The function will block until an event has occured on one of the monitored connections
- *	or the timeout of timeout_ticks has passed by.
- *	Upon successfull call (changed connections) this function will write the connection
- *	Identifier & event  to the out_fds array. 
+ *  The function will block until an event has occured on one of the monitored connections
+ *  or the timeout of timeout_ticks has passed by.
+ *  Upon successfull call (changed connections) this function will write the connection
+ *  Identifier & event  to the out_fds array.
  *
- * @return 	0 -> Timeout, 	> 0 no of changed connections.
+ * @return  0 -> Timeout,   > 0 no of changed connections.
  */
-int32 evdp_wait(EVDP_EVENT *out_fds,	int32 max_events, 	int32 timeout_ticks);
+int32 evdp_wait(EVDP_EVENT *out_fds,    int32 max_events,   int32 timeout_ticks);
 
 
-/** 
+/**
  * Applys the given mask on the given connection.
- * 
- * @param fd	connection identifier
- * @param *ep	event data pointer for the connection
- * @param mask	new event mask we're monitoring for.
+ *
+ * @param fd    connection identifier
+ * @param *ep   event data pointer for the connection
+ * @param mask  new event mask we're monitoring for.
  */
-//void evdp_apply(int32 fd,  EVDP_DATA *ep,	int32 mask);
+//void evdp_apply(int32 fd,  EVDP_DATA *ep, int32 mask);
 
 
-/** 
+/**
  * Adds a connection (listner) to the event notification system.
  *
- * @param fd 	connection identifier
- * @param *ep	event data pointer for the connection 
+ * @param fd    connection identifier
+ * @param *ep   event data pointer for the connection
  *
- * @note: 
- *	Listener type sockets are edge triggered, (see epoll manual for more information)
+ * @note:
+ *  Listener type sockets are edge triggered, (see epoll manual for more information)
  *  - This basicaly means that youll receive one event, adn you have to accept until accept returns an error (nothing to accept)
  *
  * MONITORS by default:   IN
- * 
+ *
  * @return success indicator.
- */ 
+ */
 bool evdp_addlistener(int32 fd, EVDP_DATA *ep);
 
 /**
  * Adds a connection (client connectioN) to the event notification system
  *
- * @param fd	connection identifier
- * @param *ep	event data pointr for the connection
- * 
+ * @param fd    connection identifier
+ * @param *ep   event data pointr for the connection
+ *
  * @note:
- * 
- * MONITORS by default:	IN, HUP
+ *
+ * MONITORS by default: IN, HUP
  *
  * @return success indicator.
  */
@@ -96,17 +96,17 @@ bool evdp_addclient(int32 fd, EVDP_DATA *ep);
 /**
  * Adds a connection (pending / outgoing connection!) to the event notification system.
  *
- * @param fd	connection identifier
- * @param *ep	event data pointer for the conneciton.
+ * @param fd    connection identifier
+ * @param *ep   event data pointer for the conneciton.
  *
  * @note:
- *	Outgoing connection type sockets are getting monitored for connection established
- *	successfull
- *	- if the connection has been established - we're generitng a writable notification .. (send) 
- * 		this is typical for BSD / posix conform network stacks.
- *	- Additinionally its edge triggered.
+ *  Outgoing connection type sockets are getting monitored for connection established
+ *  successfull
+ *  - if the connection has been established - we're generitng a writable notification .. (send)
+ *      this is typical for BSD / posix conform network stacks.
+ *  - Additinionally its edge triggered.
  *
- * @see evdp_outgoingconnection_established  
+ * @see evdp_outgoingconnection_established
  *
  *
  * @return success indicator
@@ -114,14 +114,14 @@ bool evdp_addclient(int32 fd, EVDP_DATA *ep);
 bool evdp_addconnecting(int32 fd, EVDP_DATA *ep);
 
 /**
- * Adds an outgoing connection to the normal event notification system after it has been successfully established. 
- *
- * @param fd	connection identifier
- * @param *ep	event data pointer for the conneciton.
- 
- * @note 
- * 	after this call, its handled like a normal "client" connection (incomming)
- * 
+ * Adds an outgoing connection to the normal event notification system after it has been successfully established.
+ *
+ * @param fd    connection identifier
+ * @param *ep   event data pointer for the conneciton.
+
+ * @note
+ *  after this call, its handled like a normal "client" connection (incomming)
+ *
  * @rturn success indicator
  */
 bool evdp_outgoingconnection_established(int32 fd, EVDP_DATA *ep);
@@ -129,24 +129,24 @@ bool evdp_outgoingconnection_established(int32 fd, EVDP_DATA *ep);
 /**
  * Marks a connection to be monitored for writable.
  *
- * @param fd	connection identifier
- * @param *ep	event data pointer for the connection
+ * @param fd    connection identifier
+ * @param *ep   event data pointer for the connection
  *
  * @note:
- *	the connection must be already added (as client or listener)
- * 
+ *  the connection must be already added (as client or listener)
+ *
  *
  * @return sucess indicator
  */
 bool evdp_writable_add(int32 fd, EVDP_DATA *ep);
 
-/** 
+/**
  * Removes the connection from writable notification monitoring
  *
- * @param fd	connection identifier
- * @param *ep	event data pointr for the connection
+ * @param fd    connection identifier
+ * @param *ep   event data pointr for the connection
  *
- */ 
+ */
 void evdp_writable_remove(int32 fd, EVDP_DATA *ep);
 
 /**
@@ -157,11 +157,11 @@ void evdp_writable_remove(int32 fd, EVDP_DATA *ep);
  *
  *
  * @note:
- * 	this will also clear the given EVENT_DATA block 
- *	so the connection slot is in an "initial" blank status / ready to get reused.
+ *  this will also clear the given EVENT_DATA block
+ *  so the connection slot is in an "initial" blank status / ready to get reused.
  *
  */
-void evdp_remove(int32 fd, 	EVDP_DATA *ep);
+void evdp_remove(int32 fd,  EVDP_DATA *ep);
 
 
 

+ 183 - 173
src/common/evdp_epoll.c

@@ -1,5 +1,5 @@
 //
-// Event Dispatcher Abstraction for EPOLL 
+// Event Dispatcher Abstraction for EPOLL
 //
 // Author: Florian Wilkemeyer <fw@f-ws.de>
 //
@@ -23,210 +23,220 @@
 #include "../common/evdp.h"
 
 
-#define EPOLL_MAX_PER_CYCLE 10	// Max Events to coalesc. per cycle. 
+#define EPOLL_MAX_PER_CYCLE 10  // Max Events to coalesc. per cycle. 
 
 
 static int epoll_fd = -1;
 
 
-void evdp_init(){
-		
-	epoll_fd = epoll_create( EPOLL_MAX_PER_CYCLE );
-	if(epoll_fd == -1){
-		ShowFatalError("evdp [EPOLL]: Cannot create event dispatcher (errno: %u / %s)\n", errno, strerror(errno) ); 
-		exit(1);
-	}
-		
+void evdp_init()
+{
+
+    epoll_fd = epoll_create(EPOLL_MAX_PER_CYCLE);
+    if (epoll_fd == -1) {
+        ShowFatalError("evdp [EPOLL]: Cannot create event dispatcher (errno: %u / %s)\n", errno, strerror(errno));
+        exit(1);
+    }
+
 }//end: evdp_init()
 
 
-void evdp_final(){
-	
-	if(epoll_fd != -1){
-		close(epoll_fd);
-		epoll_fd = -1;
-	}
-	
+void evdp_final()
+{
+
+    if (epoll_fd != -1) {
+        close(epoll_fd);
+        epoll_fd = -1;
+    }
+
 }//end: evdp_final()
 
 
-int32 evdp_wait(EVDP_EVENT *out_fds, int32 max_events, int32 timeout_ticks){
-	struct epoll_event l_events[EPOLL_MAX_PER_CYCLE];
-	register struct epoll_event *ev;
-	register int nfds, n;
-	
-	if(max_events > EPOLL_MAX_PER_CYCLE)
-		max_events = EPOLL_MAX_PER_CYCLE;
-	
-	nfds = epoll_wait( epoll_fd,  l_events,		max_events,		timeout_ticks);
-	if(nfds == -1){
-		// @TODO: check if core is in shutdown mode.  if - ignroe error.
-		
-		ShowFatalError("evdp [EPOLL]: epoll_wait returned bad / unexpected status (errno: %u / %s)\n", errno, strerror(errno));
-		exit(1); //..
-	}
-	
-	// Loop thru all events and copy it to the local ra evdp_event.. struct.
-	for(n = 0; n < nfds; n++){
-		ev = &l_events[n];
-		
-		out_fds->fd = ev->data.fd;
-		out_fds->events = 0; // clear
-		
-		if(ev->events & EPOLLHUP)
-			out_fds->events |= EVDP_EVENT_HUP;
-		
-		if(ev->events & EPOLLIN)
-			out_fds->events |= EVDP_EVENT_IN;
-		
-		if(ev->events & EPOLLOUT)
-			out_fds->events |= EVDP_EVENT_OUT;
-			
-		out_fds++;		
-	}
-
-	return nfds; // 0 on timeout or > 0  .. 
+int32 evdp_wait(EVDP_EVENT *out_fds, int32 max_events, int32 timeout_ticks)
+{
+    struct epoll_event l_events[EPOLL_MAX_PER_CYCLE];
+    register struct epoll_event *ev;
+    register int nfds, n;
+
+    if (max_events > EPOLL_MAX_PER_CYCLE)
+        max_events = EPOLL_MAX_PER_CYCLE;
+
+    nfds = epoll_wait(epoll_fd,  l_events,      max_events,     timeout_ticks);
+    if (nfds == -1) {
+        // @TODO: check if core is in shutdown mode.  if - ignroe error.
+
+        ShowFatalError("evdp [EPOLL]: epoll_wait returned bad / unexpected status (errno: %u / %s)\n", errno, strerror(errno));
+        exit(1); //..
+    }
+
+    // Loop thru all events and copy it to the local ra evdp_event.. struct.
+    for (n = 0; n < nfds; n++) {
+        ev = &l_events[n];
+
+        out_fds->fd = ev->data.fd;
+        out_fds->events = 0; // clear
+
+        if (ev->events & EPOLLHUP)
+            out_fds->events |= EVDP_EVENT_HUP;
+
+        if (ev->events & EPOLLIN)
+            out_fds->events |= EVDP_EVENT_IN;
+
+        if (ev->events & EPOLLOUT)
+            out_fds->events |= EVDP_EVENT_OUT;
+
+        out_fds++;
+    }
+
+    return nfds; // 0 on timeout or > 0  ..
 }//end: evdp_wait()
 
 
-void evdp_remove(int32 fd,  EVDP_DATA *ep){
-	
-	if(ep->ev_added == true){
-		
-		if( epoll_ctl(epoll_fd,  EPOLL_CTL_DEL,  fd,  &ep->ev_data)  != 0){
-			ShowError("evdp [EPOLL]: evdp_remove - epoll_ctl (EPOLL_CTL_DEL) failed! fd #%u (errno %u / %s)\n", fd,  errno, strerror(errno));		
-		}
-		
-		ep->ev_data.events = 0; // clear struct.
-		ep->ev_data.data.fd = -1; // .. clear struct .. 
+void evdp_remove(int32 fd,  EVDP_DATA *ep)
+{
+
+    if (ep->ev_added == true) {
+
+        if (epoll_ctl(epoll_fd,  EPOLL_CTL_DEL,  fd,  &ep->ev_data)  != 0) {
+            ShowError("evdp [EPOLL]: evdp_remove - epoll_ctl (EPOLL_CTL_DEL) failed! fd #%u (errno %u / %s)\n", fd,  errno, strerror(errno));
+        }
+
+        ep->ev_data.events = 0; // clear struct.
+        ep->ev_data.data.fd = -1; // .. clear struct ..
+
+        ep->ev_added = false; // not added!
+    }
 
-		ep->ev_added = false; // not added! 
-	}
-	
 
 }//end: evdp_remove()
 
 
-bool evdp_addlistener(int32 fd, EVDP_DATA *ep){
-	
-	ep->ev_data.events = EPOLLET|EPOLLIN;
-	ep->ev_data.data.fd = fd;
-	
-	// No check here for 'added ?'
-	// listeners cannot be added twice.
-	//
-	if( epoll_ctl(epoll_fd,  EPOLL_CTL_ADD,  fd,  &ep->ev_data) != 0 ){
-		ShowError("evdp [EPOLL]: evdp_addlistener - epoll_ctl (EPOLL_CTL_ADD) faield! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
-		ep->ev_data.events = 0;
-		ep->ev_data.data.fd = -1;
-		return false;
-	}	
-	
-	ep->ev_added = true;
-	
-	return true;
+bool evdp_addlistener(int32 fd, EVDP_DATA *ep)
+{
+
+    ep->ev_data.events = EPOLLET|EPOLLIN;
+    ep->ev_data.data.fd = fd;
+
+    // No check here for 'added ?'
+    // listeners cannot be added twice.
+    //
+    if (epoll_ctl(epoll_fd,  EPOLL_CTL_ADD,  fd,  &ep->ev_data) != 0) {
+        ShowError("evdp [EPOLL]: evdp_addlistener - epoll_ctl (EPOLL_CTL_ADD) faield! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
+        ep->ev_data.events = 0;
+        ep->ev_data.data.fd = -1;
+        return false;
+    }
+
+    ep->ev_added = true;
+
+    return true;
 }//end: evdp_addlistener()
 
 
-bool evdp_addclient(int32 fd, EVDP_DATA *ep){
-	
-	ep->ev_data.events = EPOLLIN | EPOLLHUP;
-	ep->ev_data.data.fd = fd;
-	
-	// No check for "added?" here,
-	// this function only gets called upon accpept.
-	//
-	
-	if( epoll_ctl(epoll_fd,  EPOLL_CTL_ADD,  fd, &ep->ev_data) != 0){
-		ShowError("evdp [EPOLL]: evdp_addclient - epoll_ctl (EPOLL_CTL_ADD) failed! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
-		ep->ev_data.events = 0;
-		ep->ev_data.data.fd = -1;
-		return false;
-	}
-	
-	ep->ev_added = true;
-	
-	return true;
+bool evdp_addclient(int32 fd, EVDP_DATA *ep)
+{
+
+    ep->ev_data.events = EPOLLIN | EPOLLHUP;
+    ep->ev_data.data.fd = fd;
+
+    // No check for "added?" here,
+    // this function only gets called upon accpept.
+    //
+
+    if (epoll_ctl(epoll_fd,  EPOLL_CTL_ADD,  fd, &ep->ev_data) != 0) {
+        ShowError("evdp [EPOLL]: evdp_addclient - epoll_ctl (EPOLL_CTL_ADD) failed! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
+        ep->ev_data.events = 0;
+        ep->ev_data.data.fd = -1;
+        return false;
+    }
+
+    ep->ev_added = true;
+
+    return true;
 }//end: evdp_addclient()
 
 
-bool evdp_addconnecting(int32 fd, EVDP_DATA *ep){
-	
-	ep->ev_data.events = EPOLLET | EPOLLOUT | EPOLLHUP;
-	ep->ev_data.data.fd = fd;
-	
-	if( epoll_ctl(epoll_fd,  EPOLL_CTL_ADD,  fd, &ep->ev_data) != 0){
-		ShowError("evdp [EPOLL]: evdp_addconnecting - epoll_ctl (EPOLL_CTL_ADD) failed! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
-		ep->ev_data.events = 0;
-		ep->ev_data.data.fd = -1; 	
-	}
-		
-	ep->ev_added = true;
-
-	return true;
+bool evdp_addconnecting(int32 fd, EVDP_DATA *ep)
+{
+
+    ep->ev_data.events = EPOLLET | EPOLLOUT | EPOLLHUP;
+    ep->ev_data.data.fd = fd;
+
+    if (epoll_ctl(epoll_fd,  EPOLL_CTL_ADD,  fd, &ep->ev_data) != 0) {
+        ShowError("evdp [EPOLL]: evdp_addconnecting - epoll_ctl (EPOLL_CTL_ADD) failed! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
+        ep->ev_data.events = 0;
+        ep->ev_data.data.fd = -1;
+    }
+
+    ep->ev_added = true;
+
+    return true;
 }//end: evdp_addconnecting()
 
 
-bool evdp_outgoingconnection_established(int32 fd, EVDP_DATA *ep){
-	int32 saved_mask;
-	
-	if(ep->ev_added != true){
-		// ! 
-		ShowError("evdp [EPOLL]: evdp_outgoingconnection_established fd #%u is not added to event dispatcher! invalid call.\n", fd);
-		return false;
-	}
-	
-	saved_mask = ep->ev_data.events;
-	
-	ep->ev_data.events = EPOLLIN | EPOLLHUP;
-	
-	if( epoll_ctl(epoll_fd,  EPOLL_CTL_MOD,  fd, &ep->ev_data) != 0){
-		ep->ev_data.events = saved_mask; // restore old mask.
-		ShowError("evdp [EPOLL]: evdp_outgoingconnection_established - epoll_ctl (EPOLL_CTL_MOD) failed! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
-		return false;		
-	}
-	
-	return true;
+bool evdp_outgoingconnection_established(int32 fd, EVDP_DATA *ep)
+{
+    int32 saved_mask;
+
+    if (ep->ev_added != true) {
+        // !
+        ShowError("evdp [EPOLL]: evdp_outgoingconnection_established fd #%u is not added to event dispatcher! invalid call.\n", fd);
+        return false;
+    }
+
+    saved_mask = ep->ev_data.events;
+
+    ep->ev_data.events = EPOLLIN | EPOLLHUP;
+
+    if (epoll_ctl(epoll_fd,  EPOLL_CTL_MOD,  fd, &ep->ev_data) != 0) {
+        ep->ev_data.events = saved_mask; // restore old mask.
+        ShowError("evdp [EPOLL]: evdp_outgoingconnection_established - epoll_ctl (EPOLL_CTL_MOD) failed! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
+        return false;
+    }
+
+    return true;
 }//end: evdp_outgoingconnection_established()
 
 
-bool evdp_writable_add(int32 fd, EVDP_DATA *ep){
-	
-	if(ep->ev_added != true){
-		ShowError("evdp [EPOLL]: evdp_writable_add - tried to add not added fd #%u\n",fd);
-		return false;
-	}
-	
-	if(! (ep->ev_data.events  & EPOLLOUT) ){ // 
-	
-		ep->ev_data.events |= EPOLLOUT;
-		if( epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ep->ev_data) != 0 ){
-			ShowError("evdp [EPOLL]: evdp_writable_add - epoll_ctl (EPOLL_CTL_MOD) failed! fd #%u (errno: %u / %s)\n", fd, errno, strerror(errno));
-			ep->ev_data.events &= ~EPOLLOUT; // remove from local flagmask due to failed syscall.
-			return false;
-		}
-	}
-	
-	return true;	
+bool evdp_writable_add(int32 fd, EVDP_DATA *ep)
+{
+
+    if (ep->ev_added != true) {
+        ShowError("evdp [EPOLL]: evdp_writable_add - tried to add not added fd #%u\n",fd);
+        return false;
+    }
+
+    if (!(ep->ev_data.events  & EPOLLOUT)) { //
+
+        ep->ev_data.events |= EPOLLOUT;
+        if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ep->ev_data) != 0) {
+            ShowError("evdp [EPOLL]: evdp_writable_add - epoll_ctl (EPOLL_CTL_MOD) failed! fd #%u (errno: %u / %s)\n", fd, errno, strerror(errno));
+            ep->ev_data.events &= ~EPOLLOUT; // remove from local flagmask due to failed syscall.
+            return false;
+        }
+    }
+
+    return true;
 }//end: evdp_writable_add()
 
 
-void evdp_writable_remove(int32 fd, EVDP_DATA *ep){
-	
-	if(ep->ev_added != true){
-		ShowError("evdp [EPOLL]: evdp_writable_remove - tried to remove not added fd #%u\n", fd);
-		return;
-	}
-	
-	if( ep->ev_data.events & EPOLLOUT ){
-		
-		ep->ev_data.events &= ~EPOLLOUT;
-		if( epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ep->ev_data) != 0){
-			ShowError("evdp [EPOLL]: evdp_writable_remove - epoll_ctl (EPOLL_CTL_MOD) failed! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
-			ep->ev_data.events |= EPOLLOUT; // add back to local flagmask because of failed syscall.
-			return;
-		}		
-	}
-	
-	return;	
+void evdp_writable_remove(int32 fd, EVDP_DATA *ep)
+{
+
+    if (ep->ev_added != true) {
+        ShowError("evdp [EPOLL]: evdp_writable_remove - tried to remove not added fd #%u\n", fd);
+        return;
+    }
+
+    if (ep->ev_data.events & EPOLLOUT) {
+
+        ep->ev_data.events &= ~EPOLLOUT;
+        if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ep->ev_data) != 0) {
+            ShowError("evdp [EPOLL]: evdp_writable_remove - epoll_ctl (EPOLL_CTL_MOD) failed! fd #%u (errno %u / %s)\n", fd, errno, strerror(errno));
+            ep->ev_data.events |= EPOLLOUT; // add back to local flagmask because of failed syscall.
+            return;
+        }
+    }
+
+    return;
 }//end: evdp_writable_remove()

+ 610 - 595
src/common/grfio.c

@@ -16,18 +16,18 @@
 #include <zlib.h>
 
 //----------------------------
-//	file entry table struct
+//  file entry table struct
 //----------------------------
 typedef struct _FILELIST {
-	int		srclen;				// compressed size
-	int		srclen_aligned;
-	int		declen;				// original size
-	int		srcpos;				// position of entry in grf
-	int		next;				// index of next filelist entry with same hash (-1: end of entry chain)
-	char	type;
-	char	fn[128-4*5];		// file name
-	char*	fnd;				// if the file was cloned, contains name of original file
-	char	gentry;				// read grf file select
+    int     srclen;             // compressed size
+    int     srclen_aligned;
+    int     declen;             // original size
+    int     srcpos;             // position of entry in grf
+    int     next;               // index of next filelist entry with same hash (-1: end of entry chain)
+    char    type;
+    char    fn[128-4*5];        // file name
+    char   *fnd;                // if the file was cloned, contains name of original file
+    char    gentry;             // read grf file select
 } FILELIST;
 
 #define FILELIST_TYPE_FILE           0x01 // entry is a file
@@ -45,34 +45,33 @@ typedef struct _FILELIST {
 
 
 // stores info about every loaded file
-FILELIST* filelist		= NULL;
-int filelist_entrys		= 0;
-int filelist_maxentry	= 0;
+FILELIST *filelist      = NULL;
+int filelist_entrys     = 0;
+int filelist_maxentry   = 0;
 
 // stores grf file names
-char** gentry_table		= NULL;
-int gentry_entrys		= 0;
-int gentry_maxentry		= 0;
+char **gentry_table     = NULL;
+int gentry_entrys       = 0;
+int gentry_maxentry     = 0;
 
 // the path to the data directory
 char data_dir[1024] = "";
 
 
 // little endian char array to uint conversion
-static unsigned int getlong(unsigned char* p)
+static unsigned int getlong(unsigned char *p)
 {
-	return (p[0] << 0 | p[1] << 8 | p[2] << 16 | p[3] << 24);
+    return (p[0] << 0 | p[1] << 8 | p[2] << 16 | p[3] << 24);
 }
 
 
-static void NibbleSwap(unsigned char* src, int len)
+static void NibbleSwap(unsigned char *src, int len)
 {
-	while( len > 0 )
-	{
-		*src = (*src >> 4) | (*src << 4);
-		++src;
-		--len;
-	}
+    while (len > 0) {
+        *src = (*src >> 4) | (*src << 4);
+        ++src;
+        --len;
+    }
 }
 
 
@@ -80,114 +79,142 @@ static void NibbleSwap(unsigned char* src, int len)
 /// NOTE: Operation is symmetric (calling it twice gives back the original input).
 static uint8_t grf_substitution(uint8_t in)
 {
-	uint8_t out;
-
-	switch( in )
-	{
-	case 0x00: out = 0x2B; break;
-	case 0x2B: out = 0x00; break;
-	case 0x6C: out = 0x80; break;
-	case 0x01: out = 0x68; break;
-	case 0x68: out = 0x01; break;
-	case 0x48: out = 0x77; break;
-	case 0x60: out = 0xFF; break;
-	case 0x77: out = 0x48; break;
-	case 0xB9: out = 0xC0; break;
-	case 0xC0: out = 0xB9; break;
-	case 0xFE: out = 0xEB; break;
-	case 0xEB: out = 0xFE; break;
-	case 0x80: out = 0x6C; break;
-	case 0xFF: out = 0x60; break;
-	default:   out = in;   break;
-	}
-
-	return out;
+    uint8_t out;
+
+    switch (in) {
+        case 0x00:
+            out = 0x2B;
+            break;
+        case 0x2B:
+            out = 0x00;
+            break;
+        case 0x6C:
+            out = 0x80;
+            break;
+        case 0x01:
+            out = 0x68;
+            break;
+        case 0x68:
+            out = 0x01;
+            break;
+        case 0x48:
+            out = 0x77;
+            break;
+        case 0x60:
+            out = 0xFF;
+            break;
+        case 0x77:
+            out = 0x48;
+            break;
+        case 0xB9:
+            out = 0xC0;
+            break;
+        case 0xC0:
+            out = 0xB9;
+            break;
+        case 0xFE:
+            out = 0xEB;
+            break;
+        case 0xEB:
+            out = 0xFE;
+            break;
+        case 0x80:
+            out = 0x6C;
+            break;
+        case 0xFF:
+            out = 0x60;
+            break;
+        default:
+            out = in;
+            break;
+    }
+
+    return out;
 }
 
 /* this is not used anywhere, is it ok to delete?  */
 //static void grf_shuffle_enc(BIT64* src) {
-//	BIT64 out;
+//  BIT64 out;
 //
-//	out.b[0] = src->b[3];
-//	out.b[1] = src->b[4];
-//	out.b[2] = src->b[5];
-//	out.b[3] = src->b[0];
-//	out.b[4] = src->b[1];
-//	out.b[5] = src->b[6];
-//	out.b[6] = src->b[2];
-//	out.b[7] = grf_substitution(src->b[7]);
+//  out.b[0] = src->b[3];
+//  out.b[1] = src->b[4];
+//  out.b[2] = src->b[5];
+//  out.b[3] = src->b[0];
+//  out.b[4] = src->b[1];
+//  out.b[5] = src->b[6];
+//  out.b[6] = src->b[2];
+//  out.b[7] = grf_substitution(src->b[7]);
 //
-//	*src = out;
+//  *src = out;
 //}
 
 
-static void grf_shuffle_dec(BIT64* src)
+static void grf_shuffle_dec(BIT64 *src)
 {
-	BIT64 out;
-
-	out.b[0] = src->b[3];
-	out.b[1] = src->b[4];
-	out.b[2] = src->b[6];
-	out.b[3] = src->b[0];
-	out.b[4] = src->b[1];
-	out.b[5] = src->b[2];
-	out.b[6] = src->b[5];
-	out.b[7] = grf_substitution(src->b[7]);
-
-	*src = out;
+    BIT64 out;
+
+    out.b[0] = src->b[3];
+    out.b[1] = src->b[4];
+    out.b[2] = src->b[6];
+    out.b[3] = src->b[0];
+    out.b[4] = src->b[1];
+    out.b[5] = src->b[2];
+    out.b[6] = src->b[5];
+    out.b[7] = grf_substitution(src->b[7]);
+
+    *src = out;
 }
 
 
-static void grf_decode_header(unsigned char* buf, size_t len)
+static void grf_decode_header(unsigned char *buf, size_t len)
 {
-	BIT64* p = (BIT64*)buf;
-	size_t nblocks = len / sizeof(BIT64);
-	size_t i;
+    BIT64 *p = (BIT64 *)buf;
+    size_t nblocks = len / sizeof(BIT64);
+    size_t i;
 
-	// first 20 blocks are all des-encrypted
-	for( i = 0; i < 20 && i < nblocks; ++i )
-		des_decrypt_block(&p[i]);
+    // first 20 blocks are all des-encrypted
+    for (i = 0; i < 20 && i < nblocks; ++i)
+        des_decrypt_block(&p[i]);
 
-	// the rest is plaintext, done.
+    // the rest is plaintext, done.
 }
 
 
-static void grf_decode_full(unsigned char* buf, size_t len, int cycle)
+static void grf_decode_full(unsigned char *buf, size_t len, int cycle)
 {
-	BIT64* p = (BIT64*)buf;
-	size_t nblocks = len / sizeof(BIT64);
-	int dcycle, scycle;
-	size_t i, j;
-
-	// first 20 blocks are all des-encrypted
-	for( i = 0; i < 20 && i < nblocks; ++i )
-		des_decrypt_block(&p[i]);
-
-	// after that only one of every 'dcycle' blocks is des-encrypted
-	dcycle = cycle;
-
-	// and one of every 'scycle' plaintext blocks is shuffled (starting from the 0th but skipping the 0th)
-	scycle = 7;
-
-	// so decrypt/de-shuffle periodically
-	j = -1; // 0, adjusted to fit the ++j step
-	for( i = 20; i < nblocks; ++i )
-	{
-		if( i % dcycle == 0 )
-		{// decrypt block
-			des_decrypt_block(&p[i]);
-			continue;
-		}
-
-		++j;
-		if( j % scycle == 0 && j != 0 )
-		{// de-shuffle block
-			grf_shuffle_dec(&p[i]);
-			continue;
-		}
-
-		// plaintext, do nothing.
-	}
+    BIT64 *p = (BIT64 *)buf;
+    size_t nblocks = len / sizeof(BIT64);
+    int dcycle, scycle;
+    size_t i, j;
+
+    // first 20 blocks are all des-encrypted
+    for (i = 0; i < 20 && i < nblocks; ++i)
+        des_decrypt_block(&p[i]);
+
+    // after that only one of every 'dcycle' blocks is des-encrypted
+    dcycle = cycle;
+
+    // and one of every 'scycle' plaintext blocks is shuffled (starting from the 0th but skipping the 0th)
+    scycle = 7;
+
+    // so decrypt/de-shuffle periodically
+    j = -1; // 0, adjusted to fit the ++j step
+    for (i = 20; i < nblocks; ++i) {
+        if (i % dcycle == 0) {
+            // decrypt block
+            des_decrypt_block(&p[i]);
+            continue;
+        }
+
+        ++j;
+        if (j % scycle == 0 && j != 0) {
+            // de-shuffle block
+            grf_shuffle_dec(&p[i]);
+            continue;
+        }
+
+        // plaintext, do nothing.
+    }
 }
 
 
@@ -196,38 +223,35 @@ static void grf_decode_full(unsigned char* buf, size_t len, int cycle)
 /// @param len length of the data
 /// @param entry_type flags associated with the data
 /// @param entry_len true (unaligned) length of the data
-static void grf_decode(unsigned char* buf, size_t len, char entry_type, int entry_len)
+static void grf_decode(unsigned char *buf, size_t len, char entry_type, int entry_len)
 {
-	if( entry_type & FILELIST_TYPE_ENCRYPT_MIXED )
-	{// fully encrypted
-		int digits;
-		int cycle;
-		int i;
-
-		// compute number of digits of the entry length
-		digits = 1;
-		for( i = 10; i <= entry_len; i *= 10 )
-			++digits;
-
-		// choose size of gap between two encrypted blocks
-		// digits:  0  1  2  3  4  5  6  7  8  9 ...
-		//  cycle:  1  1  1  4  5 14 15 22 23 24 ...
-		cycle = ( digits < 3 ) ? 1
-		      : ( digits < 5 ) ? digits + 1
-		      : ( digits < 7 ) ? digits + 9
-		      :                  digits + 15;
-
-		grf_decode_full(buf, len, cycle);
-	}
-	else
-	if( entry_type & FILELIST_TYPE_ENCRYPT_HEADER )
-	{// header encrypted
-		grf_decode_header(buf, len);
-	}
-	else
-	{// plaintext
-		;
-	}
+    if (entry_type & FILELIST_TYPE_ENCRYPT_MIXED) {
+        // fully encrypted
+        int digits;
+        int cycle;
+        int i;
+
+        // compute number of digits of the entry length
+        digits = 1;
+        for (i = 10; i <= entry_len; i *= 10)
+            ++digits;
+
+        // choose size of gap between two encrypted blocks
+        // digits:  0  1  2  3  4  5  6  7  8  9 ...
+        //  cycle:  1  1  1  4  5 14 15 22 23 24 ...
+        cycle = (digits < 3) ? 1
+                : (digits < 5) ? digits + 1
+                : (digits < 7) ? digits + 9
+                :                  digits + 15;
+
+        grf_decode_full(buf, len, cycle);
+    } else if (entry_type & FILELIST_TYPE_ENCRYPT_HEADER) {
+        // header encrypted
+        grf_decode_header(buf, len);
+    } else {
+        // plaintext
+        ;
+    }
 }
 
 
@@ -236,23 +260,23 @@ static void grf_decode(unsigned char* buf, size_t len, char entry_type, int entr
  ******************************************************/
 
 /// zlib crc32
-unsigned long grfio_crc32(const unsigned char* buf, unsigned int len)
+unsigned long grfio_crc32(const unsigned char *buf, unsigned int len)
 {
-	return crc32(crc32(0L, Z_NULL, 0), buf, len);
+    return crc32(crc32(0L, Z_NULL, 0), buf, len);
 }
 
 
 /// zlib uncompress
-int decode_zip(void* dest, unsigned long* destLen, const void* source, unsigned long sourceLen)
+int decode_zip(void *dest, unsigned long *destLen, const void *source, unsigned long sourceLen)
 {
-	return uncompress((Bytef*)dest, destLen, (const Bytef*)source, sourceLen);
+    return uncompress((Bytef *)dest, destLen, (const Bytef *)source, sourceLen);
 }
 
 
 /// zlib compress
-int encode_zip(void* dest, unsigned long* destLen, const void* source, unsigned long sourceLen)
+int encode_zip(void *dest, unsigned long *destLen, const void *source, unsigned long sourceLen)
 {
-	return compress((Bytef*)dest, destLen, (const Bytef*)source, sourceLen);
+    return compress((Bytef *)dest, destLen, (const Bytef *)source, sourceLen);
 }
 
 
@@ -265,94 +289,94 @@ int filelist_hash[256];
 // initializes the table that holds the first elements of all hash chains
 static void hashinit(void)
 {
-	int i;
-	for (i = 0; i < 256; i++)
-		filelist_hash[i] = -1;
+    int i;
+    for (i = 0; i < 256; i++)
+        filelist_hash[i] = -1;
 }
 
 // hashes a filename string into a number from {0..255}
-static int filehash(const char* fname)
+static int filehash(const char *fname)
 {
-	unsigned int hash = 0;
-	while(*fname) {
-		hash = (hash<<1) + (hash>>7)*9 + TOLOWER(*fname);
-		fname++;
-	}
-	return hash & 255;
+    unsigned int hash = 0;
+    while (*fname) {
+        hash = (hash<<1) + (hash>>7)*9 + TOLOWER(*fname);
+        fname++;
+    }
+    return hash & 255;
 }
 
 // finds a FILELIST entry with the specified file name
-static FILELIST* filelist_find(const char* fname)
+static FILELIST *filelist_find(const char *fname)
 {
-	int hash, index;
+    int hash, index;
 
-	if (!filelist)
-		return NULL;
+    if (!filelist)
+        return NULL;
 
-	hash = filelist_hash[filehash(fname)];
-	for (index = hash; index != -1; index = filelist[index].next)
-		if(!strcmpi(filelist[index].fn, fname))
-			break;
+    hash = filelist_hash[filehash(fname)];
+    for (index = hash; index != -1; index = filelist[index].next)
+        if (!strcmpi(filelist[index].fn, fname))
+            break;
 
-	return (index >= 0) ? &filelist[index] : NULL;
+    return (index >= 0) ? &filelist[index] : NULL;
 }
 
 // returns the original file name
-char* grfio_find_file(const char* fname)
+char *grfio_find_file(const char *fname)
 {
-	FILELIST *filelist = filelist_find(fname);
-	if (!filelist) return NULL;
-	return (!filelist->fnd ? filelist->fn : filelist->fnd);
+    FILELIST *filelist = filelist_find(fname);
+    if (!filelist) return NULL;
+    return (!filelist->fnd ? filelist->fn : filelist->fnd);
 }
 
 // adds a FILELIST entry into the list of loaded files
-static FILELIST* filelist_add(FILELIST* entry)
+static FILELIST *filelist_add(FILELIST *entry)
 {
-	int hash;
+    int hash;
 
-	#define	FILELIST_ADDS	1024	// number increment of file lists `
+#define FILELIST_ADDS   1024    // number increment of file lists `
 
-	if (filelist_entrys >= filelist_maxentry) {
-		filelist = (FILELIST *)aRealloc(filelist, (filelist_maxentry + FILELIST_ADDS) * sizeof(FILELIST));
-		memset(filelist + filelist_maxentry, '\0', FILELIST_ADDS * sizeof(FILELIST));
-		filelist_maxentry += FILELIST_ADDS;
-	}
+    if (filelist_entrys >= filelist_maxentry) {
+        filelist = (FILELIST *)aRealloc(filelist, (filelist_maxentry + FILELIST_ADDS) * sizeof(FILELIST));
+        memset(filelist + filelist_maxentry, '\0', FILELIST_ADDS * sizeof(FILELIST));
+        filelist_maxentry += FILELIST_ADDS;
+    }
 
-	memcpy (&filelist[filelist_entrys], entry, sizeof(FILELIST));
+    memcpy(&filelist[filelist_entrys], entry, sizeof(FILELIST));
 
-	hash = filehash(entry->fn);
-	filelist[filelist_entrys].next = filelist_hash[hash];
-	filelist_hash[hash] = filelist_entrys;
+    hash = filehash(entry->fn);
+    filelist[filelist_entrys].next = filelist_hash[hash];
+    filelist_hash[hash] = filelist_entrys;
 
-	filelist_entrys++;
+    filelist_entrys++;
 
-	return &filelist[filelist_entrys - 1];
+    return &filelist[filelist_entrys - 1];
 }
 
 // adds a new FILELIST entry or overwrites an existing one
-static FILELIST* filelist_modify(FILELIST* entry)
+static FILELIST *filelist_modify(FILELIST *entry)
 {
-	FILELIST* fentry = filelist_find(entry->fn);
-	if (fentry != NULL) {
-		int tmp = fentry->next;
-		memcpy(fentry, entry, sizeof(FILELIST));
-		fentry->next = tmp;
-	} else {
-		fentry = filelist_add(entry);
-	}
-	return fentry;
+    FILELIST *fentry = filelist_find(entry->fn);
+    if (fentry != NULL) {
+        int tmp = fentry->next;
+        memcpy(fentry, entry, sizeof(FILELIST));
+        fentry->next = tmp;
+    } else {
+        fentry = filelist_add(entry);
+    }
+    return fentry;
 }
 
 // shrinks the file list array if too long
 static void filelist_compact(void)
 {
-	if (filelist == NULL)
-		return;
+    if (filelist == NULL)
+        return;
 
-	if (filelist_entrys < filelist_maxentry) {
-		filelist = (FILELIST *)aRealloc(filelist, filelist_entrys * sizeof(FILELIST));
-		filelist_maxentry = filelist_entrys;
-	}
+    if (filelist_entrys < filelist_maxentry) {
+        filelist = (FILELIST *)aRealloc(filelist, filelist_entrys * sizeof(FILELIST));
+        filelist_maxentry = filelist_entrys;
+    }
 }
 
 
@@ -362,457 +386,448 @@ static void filelist_compact(void)
 
 
 /// Combines are resource path with the data folder location to create local resource path.
-static void grfio_localpath_create(char* buffer, size_t size, const char* filename)
+static void grfio_localpath_create(char *buffer, size_t size, const char *filename)
 {
-	unsigned int i;
-	size_t len;
-
-	len = strlen(data_dir);
-
-	if( data_dir[0] == '\0' || data_dir[len-1] == '/' || data_dir[len-1] == '\\' )
-	{
-		safesnprintf(buffer, size, "%s%s", data_dir, filename);
-	}
-	else
-	{
-		safesnprintf(buffer, size, "%s/%s", data_dir, filename);
-	}
-
-	// normalize path
-	for( i = 0; buffer[i] != '\0'; ++i )
-		if( buffer[i] == '\\' )
-			buffer[i] = '/';
+    unsigned int i;
+    size_t len;
+
+    len = strlen(data_dir);
+
+    if (data_dir[0] == '\0' || data_dir[len-1] == '/' || data_dir[len-1] == '\\') {
+        safesnprintf(buffer, size, "%s%s", data_dir, filename);
+    } else {
+        safesnprintf(buffer, size, "%s/%s", data_dir, filename);
+    }
+
+    // normalize path
+    for (i = 0; buffer[i] != '\0'; ++i)
+        if (buffer[i] == '\\')
+            buffer[i] = '/';
 }
 
 
 /// Reads a file into a newly allocated buffer (from grf or data directory).
-void* grfio_reads(const char* fname, int* size)
+void *grfio_reads(const char *fname, int *size)
 {
-	unsigned char* buf2 = NULL;
-
-	FILELIST* entry = filelist_find(fname);
-	if( entry == NULL || entry->gentry <= 0 ) {// LocalFileCheck
-		char lfname[256];
-		int declen;
-		FILE* in;
-		grfio_localpath_create(lfname, sizeof(lfname), ( entry && entry->fnd ) ? entry->fnd : fname);
-
-		in = fopen(lfname, "rb");
-		if( in != NULL ) {
-			fseek(in,0,SEEK_END);
-			declen = ftell(in);
-			fseek(in,0,SEEK_SET);
-			buf2 = (unsigned char *)aMalloc(declen+1);  // +1 for resnametable zero-termination
-			if(fread(buf2, 1, declen, in) != declen) ShowError("An error occured in fread grfio_reads, fname=%s \n",fname);
-			fclose(in);
-
-			if( size )
-				*size = declen;
-		} else {
-			if (entry != NULL && entry->gentry < 0) {
-				entry->gentry = -entry->gentry;	// local file checked
-			} else {
-				ShowError("grfio_reads: %s not found (local file: %s)\n", fname, lfname);
-				return NULL;
-			}
-		}
-	}
-
-	if( entry != NULL && entry->gentry > 0 ) {// Archive[GRF] File Read
-		char* grfname = gentry_table[entry->gentry - 1];
-		FILE* in = fopen(grfname, "rb");
-		if( in != NULL ) {
-			int fsize = entry->srclen_aligned;
-			unsigned char *buf = (unsigned char *)aMalloc(fsize);
-			fseek(in, entry->srcpos, 0);
-			if(fread(buf, 1, fsize, in) != fsize) ShowError("An error occured in fread in grfio_reads, grfname=%s\n",grfname);
-			fclose(in);
-
-			buf2 = (unsigned char *)aMalloc(entry->declen+1);  // +1 for resnametable zero-termination
-			if( entry->type & FILELIST_TYPE_FILE )
-			{// file
-				uLongf len;
-				grf_decode(buf, fsize, entry->type, entry->srclen);
-				len = entry->declen;
-				decode_zip(buf2, &len, buf, entry->srclen);
-				if (len != (uLong)entry->declen) {
-					ShowError("decode_zip size mismatch err: %d != %d\n", (int)len, entry->declen);
-					aFree(buf);
-					aFree(buf2);
-					return NULL;
-				}
-			} else {// directory?
-				memcpy(buf2, buf, entry->declen);
-			}
-
-			if( size )
-				*size = entry->declen;
-
-			aFree(buf);
-		} else {
-			ShowError("grfio_reads: %s not found (GRF file: %s)\n", fname, grfname);
-			return NULL;
-		}
-	}
-
-	return buf2;
+    unsigned char *buf2 = NULL;
+
+    FILELIST *entry = filelist_find(fname);
+    if (entry == NULL || entry->gentry <= 0) { // LocalFileCheck
+        char lfname[256];
+        int declen;
+        FILE *in;
+        grfio_localpath_create(lfname, sizeof(lfname), (entry && entry->fnd) ? entry->fnd : fname);
+
+        in = fopen(lfname, "rb");
+        if (in != NULL) {
+            fseek(in,0,SEEK_END);
+            declen = ftell(in);
+            fseek(in,0,SEEK_SET);
+            buf2 = (unsigned char *)aMalloc(declen+1);  // +1 for resnametable zero-termination
+            if (fread(buf2, 1, declen, in) != declen) ShowError("An error occured in fread grfio_reads, fname=%s \n",fname);
+            fclose(in);
+
+            if (size)
+                *size = declen;
+        } else {
+            if (entry != NULL && entry->gentry < 0) {
+                entry->gentry = -entry->gentry; // local file checked
+            } else {
+                ShowError("grfio_reads: %s not found (local file: %s)\n", fname, lfname);
+                return NULL;
+            }
+        }
+    }
+
+    if (entry != NULL && entry->gentry > 0) { // Archive[GRF] File Read
+        char *grfname = gentry_table[entry->gentry - 1];
+        FILE *in = fopen(grfname, "rb");
+        if (in != NULL) {
+            int fsize = entry->srclen_aligned;
+            unsigned char *buf = (unsigned char *)aMalloc(fsize);
+            fseek(in, entry->srcpos, 0);
+            if (fread(buf, 1, fsize, in) != fsize) ShowError("An error occured in fread in grfio_reads, grfname=%s\n",grfname);
+            fclose(in);
+
+            buf2 = (unsigned char *)aMalloc(entry->declen+1);  // +1 for resnametable zero-termination
+            if (entry->type & FILELIST_TYPE_FILE) {
+                // file
+                uLongf len;
+                grf_decode(buf, fsize, entry->type, entry->srclen);
+                len = entry->declen;
+                decode_zip(buf2, &len, buf, entry->srclen);
+                if (len != (uLong)entry->declen) {
+                    ShowError("decode_zip size mismatch err: %d != %d\n", (int)len, entry->declen);
+                    aFree(buf);
+                    aFree(buf2);
+                    return NULL;
+                }
+            } else {// directory?
+                memcpy(buf2, buf, entry->declen);
+            }
+
+            if (size)
+                *size = entry->declen;
+
+            aFree(buf);
+        } else {
+            ShowError("grfio_reads: %s not found (GRF file: %s)\n", fname, grfname);
+            return NULL;
+        }
+    }
+
+    return buf2;
 }
 
 
 /// Decodes encrypted filename from a version 01xx grf index.
-static char* decode_filename(unsigned char* buf, int len)
+static char *decode_filename(unsigned char *buf, int len)
 {
-	int lop;
-	for(lop=0;lop<len;lop+=8) {
-		NibbleSwap(&buf[lop],8);
-		des_decrypt(&buf[lop],8);
-	}
-	return (char*)buf;
+    int lop;
+    for (lop=0; lop<len; lop+=8) {
+        NibbleSwap(&buf[lop],8);
+        des_decrypt(&buf[lop],8);
+    }
+    return (char *)buf;
 }
 
 
 /// Compares file extension against known large file types.
 /// @return true if the file should undergo full mode 0 decryption, and true otherwise.
-static bool isFullEncrypt(const char* fname)
+static bool isFullEncrypt(const char *fname)
 {
-	static const char extensions[4][5] = { ".gnd", ".gat", ".act", ".str" };
-	size_t i;
+    static const char extensions[4][5] = { ".gnd", ".gat", ".act", ".str" };
+    size_t i;
 
-	const char* ext = strrchr(fname, '.');
-	if( ext != NULL )
-		for( i = 0; i < ARRAYLENGTH(extensions); ++i )
-			if( strcmpi(ext, extensions[i]) == 0 )
-				return false;
+    const char *ext = strrchr(fname, '.');
+    if (ext != NULL)
+        for (i = 0; i < ARRAYLENGTH(extensions); ++i)
+            if (strcmpi(ext, extensions[i]) == 0)
+                return false;
 
-	return true;
+    return true;
 }
 
 
 /// Loads all entries in the specified grf file into the filelist.
 /// @param gentry index of the grf file name in the gentry_table
-static int grfio_entryread(const char* grfname, int gentry)
+static int grfio_entryread(const char *grfname, int gentry)
 {
-	long grf_size,list_size;
-	unsigned char grf_header[0x2e];
-	int entry,entrys,ofs,grf_version;
-	unsigned char *grf_filelist;
-
-	FILE* fp = fopen(grfname, "rb");
-	if( fp == NULL ) {
-		ShowWarning("GRF data file not found: '%s'\n",grfname);
-		return 1;	// 1:not found error
-	} else
-		ShowInfo("GRF data file found: '%s'\n",grfname);
-
-	fseek(fp,0,SEEK_END);
-	grf_size = ftell(fp);
-	fseek(fp,0,SEEK_SET);
-
-	if(fread(grf_header,1,0x2e,fp) != 0x2e) { ShowError("Couldn't read all grf_header element of %s \n", grfname); }
-	if( strcmp((const char*)grf_header,"Master of Magic") != 0 || fseek(fp,getlong(grf_header+0x1e),SEEK_CUR) != 0 ) {
-		fclose(fp);
-		ShowError("GRF %s read error\n", grfname);
-		return 2;	// 2:file format error
-	}
-
-	grf_version = getlong(grf_header+0x2a) >> 8;
-
-	if( grf_version == 0x01 ) {// ****** Grf version 01xx ******
-		list_size = grf_size - ftell(fp);
-		grf_filelist = (unsigned char *) aMalloc(list_size);
-		if(fread(grf_filelist,1,list_size,fp) != list_size) { ShowError("Couldn't read all grf_filelist element of %s \n", grfname); }
-		fclose(fp);
-
-		entrys = getlong(grf_header+0x26) - getlong(grf_header+0x22) - 7;
-
-		// Get an entry
-		for( entry = 0, ofs = 0; entry < entrys; ++entry ) {
-			FILELIST aentry;
-
-			int ofs2 = ofs+getlong(grf_filelist+ofs)+4;
-			unsigned char type = grf_filelist[ofs2+12];
-			if( type & FILELIST_TYPE_FILE ) {
-				char* fname = decode_filename(grf_filelist+ofs+6, grf_filelist[ofs]-6);
-				int srclen = getlong(grf_filelist+ofs2+0) - getlong(grf_filelist+ofs2+8) - 715;
-
-				if( strlen(fname) > sizeof(aentry.fn) - 1 ) {
-					ShowFatalError("GRF file name %s is too long\n", fname);
-					aFree(grf_filelist);
-					exit(EXIT_FAILURE);
-				}
-
-				type |= ( isFullEncrypt(fname) ) ? FILELIST_TYPE_ENCRYPT_MIXED : FILELIST_TYPE_ENCRYPT_HEADER;
-
-				aentry.srclen         = srclen;
-				aentry.srclen_aligned = getlong(grf_filelist+ofs2+4)-37579;
-				aentry.declen         = getlong(grf_filelist+ofs2+8);
-				aentry.srcpos         = getlong(grf_filelist+ofs2+13)+0x2e;
-				aentry.type           = type;
-				safestrncpy(aentry.fn, fname, sizeof(aentry.fn));
-				aentry.fnd			  = NULL;
-#ifdef	GRFIO_LOCAL
-				aentry.gentry         = -(gentry+1);	// As Flag for making it a negative number carrying out the first time LocalFileCheck
+    long grf_size,list_size;
+    unsigned char grf_header[0x2e];
+    int entry,entrys,ofs,grf_version;
+    unsigned char *grf_filelist;
+
+    FILE *fp = fopen(grfname, "rb");
+    if (fp == NULL) {
+        ShowWarning("GRF data file not found: '%s'\n",grfname);
+        return 1;   // 1:not found error
+    } else
+        ShowInfo("GRF data file found: '%s'\n",grfname);
+
+    fseek(fp,0,SEEK_END);
+    grf_size = ftell(fp);
+    fseek(fp,0,SEEK_SET);
+
+    if (fread(grf_header,1,0x2e,fp) != 0x2e) {
+        ShowError("Couldn't read all grf_header element of %s \n", grfname);
+    }
+    if (strcmp((const char *)grf_header,"Master of Magic") != 0 || fseek(fp,getlong(grf_header+0x1e),SEEK_CUR) != 0) {
+        fclose(fp);
+        ShowError("GRF %s read error\n", grfname);
+        return 2;   // 2:file format error
+    }
+
+    grf_version = getlong(grf_header+0x2a) >> 8;
+
+    if (grf_version == 0x01) { // ****** Grf version 01xx ******
+        list_size = grf_size - ftell(fp);
+        grf_filelist = (unsigned char *) aMalloc(list_size);
+        if (fread(grf_filelist,1,list_size,fp) != list_size) {
+            ShowError("Couldn't read all grf_filelist element of %s \n", grfname);
+        }
+        fclose(fp);
+
+        entrys = getlong(grf_header+0x26) - getlong(grf_header+0x22) - 7;
+
+        // Get an entry
+        for (entry = 0, ofs = 0; entry < entrys; ++entry) {
+            FILELIST aentry;
+
+            int ofs2 = ofs+getlong(grf_filelist+ofs)+4;
+            unsigned char type = grf_filelist[ofs2+12];
+            if (type & FILELIST_TYPE_FILE) {
+                char *fname = decode_filename(grf_filelist+ofs+6, grf_filelist[ofs]-6);
+                int srclen = getlong(grf_filelist+ofs2+0) - getlong(grf_filelist+ofs2+8) - 715;
+
+                if (strlen(fname) > sizeof(aentry.fn) - 1) {
+                    ShowFatalError("GRF file name %s is too long\n", fname);
+                    aFree(grf_filelist);
+                    exit(EXIT_FAILURE);
+                }
+
+                type |= (isFullEncrypt(fname)) ? FILELIST_TYPE_ENCRYPT_MIXED : FILELIST_TYPE_ENCRYPT_HEADER;
+
+                aentry.srclen         = srclen;
+                aentry.srclen_aligned = getlong(grf_filelist+ofs2+4)-37579;
+                aentry.declen         = getlong(grf_filelist+ofs2+8);
+                aentry.srcpos         = getlong(grf_filelist+ofs2+13)+0x2e;
+                aentry.type           = type;
+                safestrncpy(aentry.fn, fname, sizeof(aentry.fn));
+                aentry.fnd            = NULL;
+#ifdef  GRFIO_LOCAL
+                aentry.gentry         = -(gentry+1);    // As Flag for making it a negative number carrying out the first time LocalFileCheck
 #else
-				aentry.gentry         = gentry+1;		// With no first time LocalFileCheck
+                aentry.gentry         = gentry+1;       // With no first time LocalFileCheck
 #endif
-				filelist_modify(&aentry);
-			}
-
-			ofs = ofs2 + 17;
-		}
-
-		aFree(grf_filelist);
-	} else if( grf_version == 0x02 ) {// ****** Grf version 02xx ******
-		unsigned char eheader[8];
-		unsigned char *rBuf;
-		uLongf rSize, eSize;
-
-		if(fread(eheader,1,8,fp) != 8) ShowError("An error occured in fread while reading eheader buffer\n");
-		rSize = getlong(eheader);	// Read Size
-		eSize = getlong(eheader+4);	// Extend Size
-
-		if( (long)rSize > grf_size-ftell(fp) ) {
-			fclose(fp);
-			ShowError("Illegal data format: GRF compress entry size\n");
-			return 4;
-		}
-
-		rBuf = (unsigned char *)aMalloc(rSize);	// Get a Read Size
-		grf_filelist = (unsigned char *)aMalloc(eSize);	// Get a Extend Size
-		if(fread(rBuf,1,rSize,fp) != rSize) ShowError("An error occured in fread \n");
-		fclose(fp);
-		decode_zip(grf_filelist, &eSize, rBuf, rSize);	// Decode function
-		aFree(rBuf);
-
-		entrys = getlong(grf_header+0x26) - 7;
-
-		// Get an entry
-		for( entry = 0, ofs = 0; entry < entrys; ++entry ) {
-			FILELIST aentry;
-
-			char* fname = (char*)(grf_filelist+ofs);
-			int ofs2 = ofs + (int)strlen(fname)+1;
-			int type = grf_filelist[ofs2+12];
-
-			if( strlen(fname) > sizeof(aentry.fn)-1 ) {
-				ShowFatalError("GRF file name %s is too long\n", fname);
-				aFree(grf_filelist);
-				exit(EXIT_FAILURE);
-			}
-
-			if( type & FILELIST_TYPE_FILE ) {// file
-				aentry.srclen         = getlong(grf_filelist+ofs2+0);
-				aentry.srclen_aligned = getlong(grf_filelist+ofs2+4);
-				aentry.declen         = getlong(grf_filelist+ofs2+8);
-				aentry.srcpos         = getlong(grf_filelist+ofs2+13)+0x2e;
-				aentry.type           = type;
-				safestrncpy(aentry.fn, fname, sizeof(aentry.fn));
-				aentry.fnd			  = NULL;
-#ifdef	GRFIO_LOCAL
-				aentry.gentry         = -(gentry+1);	// As Flag for making it a negative number carrying out the first time LocalFileCheck
+                filelist_modify(&aentry);
+            }
+
+            ofs = ofs2 + 17;
+        }
+
+        aFree(grf_filelist);
+    } else if (grf_version == 0x02) { // ****** Grf version 02xx ******
+        unsigned char eheader[8];
+        unsigned char *rBuf;
+        uLongf rSize, eSize;
+
+        if (fread(eheader,1,8,fp) != 8) ShowError("An error occured in fread while reading eheader buffer\n");
+        rSize = getlong(eheader);   // Read Size
+        eSize = getlong(eheader+4); // Extend Size
+
+        if ((long)rSize > grf_size-ftell(fp)) {
+            fclose(fp);
+            ShowError("Illegal data format: GRF compress entry size\n");
+            return 4;
+        }
+
+        rBuf = (unsigned char *)aMalloc(rSize); // Get a Read Size
+        grf_filelist = (unsigned char *)aMalloc(eSize); // Get a Extend Size
+        if (fread(rBuf,1,rSize,fp) != rSize) ShowError("An error occured in fread \n");
+        fclose(fp);
+        decode_zip(grf_filelist, &eSize, rBuf, rSize);  // Decode function
+        aFree(rBuf);
+
+        entrys = getlong(grf_header+0x26) - 7;
+
+        // Get an entry
+        for (entry = 0, ofs = 0; entry < entrys; ++entry) {
+            FILELIST aentry;
+
+            char *fname = (char *)(grf_filelist+ofs);
+            int ofs2 = ofs + (int)strlen(fname)+1;
+            int type = grf_filelist[ofs2+12];
+
+            if (strlen(fname) > sizeof(aentry.fn)-1) {
+                ShowFatalError("GRF file name %s is too long\n", fname);
+                aFree(grf_filelist);
+                exit(EXIT_FAILURE);
+            }
+
+            if (type & FILELIST_TYPE_FILE) { // file
+                aentry.srclen         = getlong(grf_filelist+ofs2+0);
+                aentry.srclen_aligned = getlong(grf_filelist+ofs2+4);
+                aentry.declen         = getlong(grf_filelist+ofs2+8);
+                aentry.srcpos         = getlong(grf_filelist+ofs2+13)+0x2e;
+                aentry.type           = type;
+                safestrncpy(aentry.fn, fname, sizeof(aentry.fn));
+                aentry.fnd            = NULL;
+#ifdef  GRFIO_LOCAL
+                aentry.gentry         = -(gentry+1);    // As Flag for making it a negative number carrying out the first time LocalFileCheck
 #else
-				aentry.gentry         = gentry+1;		// With no first time LocalFileCheck
+                aentry.gentry         = gentry+1;       // With no first time LocalFileCheck
 #endif
-				filelist_modify(&aentry);
-			}
+                filelist_modify(&aentry);
+            }
 
-			ofs = ofs2 + 17;
-		}
+            ofs = ofs2 + 17;
+        }
 
-		aFree(grf_filelist);
-	} else {// ****** Grf Other version ******
-		fclose(fp);
-		ShowError("GRF version %04x not supported\n",getlong(grf_header+0x2a));
-		return 4;
-	}
+        aFree(grf_filelist);
+    } else {// ****** Grf Other version ******
+        fclose(fp);
+        ShowError("GRF version %04x not supported\n",getlong(grf_header+0x2a));
+        return 4;
+    }
 
-	filelist_compact();	// Unnecessary area release of filelist
+    filelist_compact(); // Unnecessary area release of filelist
 
-	return 0;	// 0:no error
+    return 0;   // 0:no error
 }
 
 
-static bool grfio_parse_restable_row(const char* row)
+static bool grfio_parse_restable_row(const char *row)
 {
-	char w1[256], w2[256];
-	char src[256], dst[256];
-	char local[256];
-	FILELIST* entry;
-
-	if( sscanf(row, "%[^#\r\n]#%[^#\r\n]#", w1, w2) != 2 )
-		return false;
-
-	if( strstr(w2, ".gat") == NULL && strstr(w2, ".rsw") == NULL )
-		return false; // we only need the maps' GAT and RSW files
-
-	sprintf(src, "data\\%s", w1);
-	sprintf(dst, "data\\%s", w2);
-
-	entry = filelist_find(dst);
-	if( entry != NULL )
-	{// alias for GRF resource
-		FILELIST fentry;
-		memcpy(&fentry, entry, sizeof(FILELIST));
-		safestrncpy(fentry.fn, src, sizeof(fentry.fn));
-		fentry.fnd = aStrdup(dst);
-		filelist_modify(&fentry);
-		return true;
-	}
-
-	grfio_localpath_create(local, sizeof(local), dst);
-	if( exists(local) )
-	{// alias for local resource
-		FILELIST fentry;
-		memset(&fentry, 0, sizeof(fentry));
-		safestrncpy(fentry.fn, src, sizeof(fentry.fn));
-		fentry.fnd = aStrdup(dst);
-		filelist_modify(&fentry);
-		return true;
-	}
-
-	return false;
+    char w1[256], w2[256];
+    char src[256], dst[256];
+    char local[256];
+    FILELIST *entry;
+
+    if (sscanf(row, "%[^#\r\n]#%[^#\r\n]#", w1, w2) != 2)
+        return false;
+
+    if (strstr(w2, ".gat") == NULL && strstr(w2, ".rsw") == NULL)
+        return false; // we only need the maps' GAT and RSW files
+
+    sprintf(src, "data\\%s", w1);
+    sprintf(dst, "data\\%s", w2);
+
+    entry = filelist_find(dst);
+    if (entry != NULL) {
+        // alias for GRF resource
+        FILELIST fentry;
+        memcpy(&fentry, entry, sizeof(FILELIST));
+        safestrncpy(fentry.fn, src, sizeof(fentry.fn));
+        fentry.fnd = aStrdup(dst);
+        filelist_modify(&fentry);
+        return true;
+    }
+
+    grfio_localpath_create(local, sizeof(local), dst);
+    if (exists(local)) {
+        // alias for local resource
+        FILELIST fentry;
+        memset(&fentry, 0, sizeof(fentry));
+        safestrncpy(fentry.fn, src, sizeof(fentry.fn));
+        fentry.fnd = aStrdup(dst);
+        filelist_modify(&fentry);
+        return true;
+    }
+
+    return false;
 }
 
 
 /// Grfio Resource file check.
 static void grfio_resourcecheck(void)
 {
-	char restable[256];
-	char *ptr, *buf;
-	int size;
-	FILE* fp;
-	int i = 0;
-
-	// read resnametable from data directory and return if successful
-	grfio_localpath_create(restable, sizeof(restable), "data\\resnametable.txt");
-
-	fp = fopen(restable, "rb");
-	if( fp != NULL )
-	{
-		char line[256];
-		while( fgets(line, sizeof(line), fp) )
-		{
-			if( grfio_parse_restable_row(line) )
-				++i;
-		}
-
-		fclose(fp);
-		ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' entries in '"CL_WHITE"%s"CL_RESET"'.\n", i, "resnametable.txt");
-		return;	// we're done here!
-	}
-
-	// read resnametable from loaded GRF's, only if it cannot be loaded from the data directory
-	buf = (char *)grfio_reads("data\\resnametable.txt", &size);
-	if( buf != NULL )
-	{
-		buf[size] = '\0';
-
-		ptr = buf;
-		while( ptr - buf < size )
-		{
-			if( grfio_parse_restable_row(ptr) )
-				++i;
-
-			ptr = strchr(ptr, '\n');
-			if( ptr == NULL ) break;
-			ptr++;
-		}
-
-		aFree(buf);
-		ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' entries in '"CL_WHITE"%s"CL_RESET"'.\n", i, "data\\resnametable.txt");
-		return;
-	}
+    char restable[256];
+    char *ptr, *buf;
+    int size;
+    FILE *fp;
+    int i = 0;
+
+    // read resnametable from data directory and return if successful
+    grfio_localpath_create(restable, sizeof(restable), "data\\resnametable.txt");
+
+    fp = fopen(restable, "rb");
+    if (fp != NULL) {
+        char line[256];
+        while (fgets(line, sizeof(line), fp)) {
+            if (grfio_parse_restable_row(line))
+                ++i;
+        }
+
+        fclose(fp);
+        ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' entries in '"CL_WHITE"%s"CL_RESET"'.\n", i, "resnametable.txt");
+        return; // we're done here!
+    }
+
+    // read resnametable from loaded GRF's, only if it cannot be loaded from the data directory
+    buf = (char *)grfio_reads("data\\resnametable.txt", &size);
+    if (buf != NULL) {
+        buf[size] = '\0';
+
+        ptr = buf;
+        while (ptr - buf < size) {
+            if (grfio_parse_restable_row(ptr))
+                ++i;
+
+            ptr = strchr(ptr, '\n');
+            if (ptr == NULL) break;
+            ptr++;
+        }
+
+        aFree(buf);
+        ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' entries in '"CL_WHITE"%s"CL_RESET"'.\n", i, "data\\resnametable.txt");
+        return;
+    }
 }
 
 
 /// Reads a grf file and adds it to the list.
-static int grfio_add(const char* fname)
+static int grfio_add(const char *fname)
 {
-	if( gentry_entrys >= gentry_maxentry )
-	{
-		#define	GENTRY_ADDS	4	// The number increment of gentry_table entries
-		gentry_maxentry += GENTRY_ADDS;
-		gentry_table = (char**)aRealloc(gentry_table, gentry_maxentry * sizeof(char*));
-		memset(gentry_table + (gentry_maxentry - GENTRY_ADDS), 0, sizeof(char*) * GENTRY_ADDS);
-	}
+    if (gentry_entrys >= gentry_maxentry) {
+#define GENTRY_ADDS 4   // The number increment of gentry_table entries
+        gentry_maxentry += GENTRY_ADDS;
+        gentry_table = (char **)aRealloc(gentry_table, gentry_maxentry * sizeof(char *));
+        memset(gentry_table + (gentry_maxentry - GENTRY_ADDS), 0, sizeof(char *) * GENTRY_ADDS);
+    }
 
-	gentry_table[gentry_entrys++] = aStrdup(fname);
+    gentry_table[gentry_entrys++] = aStrdup(fname);
 
-	return grfio_entryread(fname, gentry_entrys - 1);
+    return grfio_entryread(fname, gentry_entrys - 1);
 }
 
 
 /// Finalizes grfio.
 void grfio_final(void)
 {
-	if (filelist != NULL) {
-		int i;
-		for (i = 0; i < filelist_entrys; i++)
-			if (filelist[i].fnd != NULL)
-				aFree(filelist[i].fnd);
-
-		aFree(filelist);
-		filelist = NULL;
-	}
-	filelist_entrys = filelist_maxentry = 0;
-
-	if (gentry_table != NULL) {
-		int i;
-		for (i = 0; i < gentry_entrys; i++)
-			if (gentry_table[i] != NULL)
-				aFree(gentry_table[i]);
-
-		aFree(gentry_table);
-		gentry_table = NULL;
-	}
-	gentry_entrys = gentry_maxentry = 0;
+    if (filelist != NULL) {
+        int i;
+        for (i = 0; i < filelist_entrys; i++)
+            if (filelist[i].fnd != NULL)
+                aFree(filelist[i].fnd);
+
+        aFree(filelist);
+        filelist = NULL;
+    }
+    filelist_entrys = filelist_maxentry = 0;
+
+    if (gentry_table != NULL) {
+        int i;
+        for (i = 0; i < gentry_entrys; i++)
+            if (gentry_table[i] != NULL)
+                aFree(gentry_table[i]);
+
+        aFree(gentry_table);
+        gentry_table = NULL;
+    }
+    gentry_entrys = gentry_maxentry = 0;
 }
 
 
 /// Initializes grfio.
-void grfio_init(const char* fname)
+void grfio_init(const char *fname)
 {
-	FILE* data_conf;
-	int grf_num = 0;
-
-	hashinit();	// hash table initialization
-
-	data_conf = fopen(fname, "r");
-	if( data_conf != NULL )
-	{
-		char line[1024];
-		while( fgets(line, sizeof(line), data_conf) )
-		{
-			char w1[1024], w2[1024];
-
-			if( line[0] == '/' && line[1] == '/' )
-				continue; // skip comments
-
-			if( sscanf(line, "%[^:]: %[^\r\n]", w1, w2) != 2 )
-				continue; // skip unrecognized lines
-
-			// Entry table reading
-			if( strcmp(w1, "grf") == 0 ) // GRF file
-			{
-				if( grfio_add(w2) == 0 )
-					++grf_num;
-			}
-			else if( strcmp(w1,"data_dir") == 0 ) // Data directory
-			{
-				safestrncpy(data_dir, w2, sizeof(data_dir));
-			}
-		}
-
-		fclose(data_conf);
-		ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n", fname);
-	}
-
-	if( grf_num == 0 )
-		ShowInfo("No GRF loaded, using default data directory\n");
-
-	// Unneccessary area release of filelist
-	filelist_compact();
-
-	// Resource check
-	grfio_resourcecheck();
+    FILE *data_conf;
+    int grf_num = 0;
+
+    hashinit(); // hash table initialization
+
+    data_conf = fopen(fname, "r");
+    if (data_conf != NULL) {
+        char line[1024];
+        while (fgets(line, sizeof(line), data_conf)) {
+            char w1[1024], w2[1024];
+
+            if (line[0] == '/' && line[1] == '/')
+                continue; // skip comments
+
+            if (sscanf(line, "%[^:]: %[^\r\n]", w1, w2) != 2)
+                continue; // skip unrecognized lines
+
+            // Entry table reading
+            if (strcmp(w1, "grf") == 0) { // GRF file
+                if (grfio_add(w2) == 0)
+                    ++grf_num;
+            } else if (strcmp(w1,"data_dir") == 0) { // Data directory
+                safestrncpy(data_dir, w2, sizeof(data_dir));
+            }
+        }
+
+        fclose(data_conf);
+        ShowStatus("Done reading '"CL_WHITE"%s"CL_RESET"'.\n", fname);
+    }
+
+    if (grf_num == 0)
+        ShowInfo("No GRF loaded, using default data directory\n");
+
+    // Unneccessary area release of filelist
+    filelist_compact();
+
+    // Resource check
+    grfio_resourcecheck();
 }

+ 7 - 7
src/common/grfio.h

@@ -1,17 +1,17 @@
 // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
 // For more information, see LICENCE in the main folder
 
-#ifndef	_GRFIO_H_
-#define	_GRFIO_H_
+#ifndef _GRFIO_H_
+#define _GRFIO_H_
 
-void grfio_init(const char* fname);
+void grfio_init(const char *fname);
 void grfio_final(void);
-void* grfio_reads(const char* fname, int* size);
-char* grfio_find_file(const char* fname);
+void *grfio_reads(const char *fname, int *size);
+char *grfio_find_file(const char *fname);
 #define grfio_read(fn) grfio_reads(fn, NULL)
 
 unsigned long grfio_crc32(const unsigned char *buf, unsigned int len);
-int decode_zip(void* dest, unsigned long* destLen, const void* source, unsigned long sourceLen);
-int encode_zip(void* dest, unsigned long* destLen, const void* source, unsigned long sourceLen);
+int decode_zip(void *dest, unsigned long *destLen, const void *source, unsigned long sourceLen);
+int encode_zip(void *dest, unsigned long *destLen, const void *source, unsigned long sourceLen);
 
 #endif /* _GRFIO_H_ */

File diff suppressed because it is too large
+ 481 - 491
src/common/malloc.c


+ 29 - 29
src/common/malloc.h

@@ -33,31 +33,31 @@
 #undef LOG_MEMMGR
 #endif
 
-#	define aMalloc(n)		_mmalloc(n,ALC_MARK)
-#	define aCalloc(m,n)		_mcalloc(m,n,ALC_MARK)
-#	define aRealloc(p,n)	_mrealloc(p,n,ALC_MARK)
-#	define aStrdup(p)		_mstrdup(p,ALC_MARK)
-#	define aFree(p)			_mfree(p,ALC_MARK)
-
-	void* _mmalloc	(size_t size, const char *file, int line, const char *func);
-	void* _mcalloc	(size_t num, size_t size, const char *file, int line, const char *func);
-	void* _mrealloc	(void *p, size_t size, const char *file, int line, const char *func);
-	char* _mstrdup	(const char *p, const char *file, int line, const char *func);
-	void  _mfree	(void *p, const char *file, int line, const char *func);
+#   define aMalloc(n)       _mmalloc(n,ALC_MARK)
+#   define aCalloc(m,n)     _mcalloc(m,n,ALC_MARK)
+#   define aRealloc(p,n)    _mrealloc(p,n,ALC_MARK)
+#   define aStrdup(p)       _mstrdup(p,ALC_MARK)
+#   define aFree(p)         _mfree(p,ALC_MARK)
+
+void *_mmalloc(size_t size, const char *file, int line, const char *func);
+void *_mcalloc(size_t num, size_t size, const char *file, int line, const char *func);
+void *_mrealloc(void *p, size_t size, const char *file, int line, const char *func);
+char *_mstrdup(const char *p, const char *file, int line, const char *func);
+void  _mfree(void *p, const char *file, int line, const char *func);
 
 #else
 
-#	define aMalloc(n)		aMalloc_((n),ALC_MARK)
-#	define aCalloc(m,n)		aCalloc_((m),(n),ALC_MARK)
-#	define aRealloc(p,n)	aRealloc_(p,n,ALC_MARK)
-#	define aStrdup(p)		aStrdup_(p,ALC_MARK)
-#	define aFree(p)			aFree_(p,ALC_MARK)
+#   define aMalloc(n)       aMalloc_((n),ALC_MARK)
+#   define aCalloc(m,n)     aCalloc_((m),(n),ALC_MARK)
+#   define aRealloc(p,n)    aRealloc_(p,n,ALC_MARK)
+#   define aStrdup(p)       aStrdup_(p,ALC_MARK)
+#   define aFree(p)         aFree_(p,ALC_MARK)
 
-	void* aMalloc_	(size_t size, const char *file, int line, const char *func);
-	void* aCalloc_	(size_t num, size_t size, const char *file, int line, const char *func);
-	void* aRealloc_	(void *p, size_t size, const char *file, int line, const char *func);
-	char* aStrdup_	(const char *p, const char *file, int line, const char *func);
-	void  aFree_	(void *p, const char *file, int line, const char *func);
+void *aMalloc_(size_t size, const char *file, int line, const char *func);
+void *aCalloc_(size_t num, size_t size, const char *file, int line, const char *func);
+void *aRealloc_(void *p, size_t size, const char *file, int line, const char *func);
+char *aStrdup_(const char *p, const char *file, int line, const char *func);
+void  aFree_(void *p, const char *file, int line, const char *func);
 
 #endif
 
@@ -66,13 +66,13 @@
 
 #ifdef __GNUC__ // GCC has variable length arrays
 
-	#define CREATE_BUFFER(name, type, size) type name[size]
-	#define DELETE_BUFFER(name)
+#define CREATE_BUFFER(name, type, size) type name[size]
+#define DELETE_BUFFER(name)
 
 #else // others don't, so we emulate them
 
-	#define CREATE_BUFFER(name, type, size) type *name = (type *) aCalloc (size, sizeof(type))
-	#define DELETE_BUFFER(name) aFree(name)
+#define CREATE_BUFFER(name, type, size) type *name = (type *) aCalloc (size, sizeof(type))
+#define DELETE_BUFFER(name) aFree(name)
 
 #endif
 
@@ -84,9 +84,9 @@
 ////////////////////////////////////////////////
 
 void malloc_memory_check(void);
-bool malloc_verify_ptr(void* ptr);
-size_t malloc_usage (void);
-void malloc_init (void);
-void malloc_final (void);
+bool malloc_verify_ptr(void *ptr);
+size_t malloc_usage(void);
+void malloc_init(void);
+void malloc_final(void);
 
 #endif /* _MALLOC_H_ */

+ 124 - 127
src/common/mapindex.c

@@ -12,7 +12,7 @@
 #include <stdlib.h>
 
 struct _indexes {
-	char name[MAP_NAME_LENGTH]; //Stores map name
+    char name[MAP_NAME_LENGTH]; //Stores map name
 } indexes[MAX_MAPINDEX];
 
 int max_index = 0;
@@ -23,161 +23,158 @@ char mapindex_cfgfile[80] = "db/map_index.txt";
 
 /// Retrieves the map name from 'string' (removing .gat extension if present).
 /// Result gets placed either into 'buf' or in a static local buffer.
-const char* mapindex_getmapname(const char* string, char* output)
+const char *mapindex_getmapname(const char *string, char *output)
 {
-	static char buf[MAP_NAME_LENGTH];
-	char* dest = (output != NULL) ? output : buf;
-	
-	size_t len = strnlen(string, MAP_NAME_LENGTH_EXT);
-	if (len == MAP_NAME_LENGTH_EXT) {
-		ShowWarning("(mapindex_normalize_name) Map name '%*s' is too long!\n", 2*MAP_NAME_LENGTH_EXT, string);
-		len--;
-	}
-	if (len >= 4 && stricmp(&string[len-4], ".gat") == 0)
-		len -= 4; // strip .gat extension
-	
-	len = min(len, MAP_NAME_LENGTH-1);
-	strncpy(dest, string, len+1);
-	memset(&dest[len], '\0', MAP_NAME_LENGTH-len);
-	
-	return dest;
+    static char buf[MAP_NAME_LENGTH];
+    char *dest = (output != NULL) ? output : buf;
+
+    size_t len = strnlen(string, MAP_NAME_LENGTH_EXT);
+    if (len == MAP_NAME_LENGTH_EXT) {
+        ShowWarning("(mapindex_normalize_name) Map name '%*s' is too long!\n", 2*MAP_NAME_LENGTH_EXT, string);
+        len--;
+    }
+    if (len >= 4 && stricmp(&string[len-4], ".gat") == 0)
+        len -= 4; // strip .gat extension
+
+    len = min(len, MAP_NAME_LENGTH-1);
+    strncpy(dest, string, len+1);
+    memset(&dest[len], '\0', MAP_NAME_LENGTH-len);
+
+    return dest;
 }
 
 /// Retrieves the map name from 'string' (adding .gat extension if not already present).
 /// Result gets placed either into 'buf' or in a static local buffer.
-const char* mapindex_getmapname_ext(const char* string, char* output)
+const char *mapindex_getmapname_ext(const char *string, char *output)
 {
-	static char buf[MAP_NAME_LENGTH_EXT];
-	char* dest = (output != NULL) ? output : buf;
+    static char buf[MAP_NAME_LENGTH_EXT];
+    char *dest = (output != NULL) ? output : buf;
 
-	size_t len;
+    size_t len;
 
-	strcpy(buf,string);
-	sscanf(string,"%*[^#]%*[#]%s",buf);
+    strcpy(buf,string);
+    sscanf(string,"%*[^#]%*[#]%s",buf);
 
-	len = safestrnlen(buf, MAP_NAME_LENGTH);
+    len = safestrnlen(buf, MAP_NAME_LENGTH);
 
-	if (len == MAP_NAME_LENGTH) {
-		ShowWarning("(mapindex_normalize_name) Map name '%*s' is too long!\n", 2*MAP_NAME_LENGTH, buf);
-		len--;
-	}
-	strncpy(dest, buf, len+1);
+    if (len == MAP_NAME_LENGTH) {
+        ShowWarning("(mapindex_normalize_name) Map name '%*s' is too long!\n", 2*MAP_NAME_LENGTH, buf);
+        len--;
+    }
+    strncpy(dest, buf, len+1);
 
-	if (len < 4 || stricmp(&dest[len-4], ".gat") != 0) {
-		strcpy(&dest[len], ".gat");
-		len += 4; // add .gat extension
-	}
+    if (len < 4 || stricmp(&dest[len-4], ".gat") != 0) {
+        strcpy(&dest[len], ".gat");
+        len += 4; // add .gat extension
+    }
 
-	memset(&dest[len], '\0', MAP_NAME_LENGTH_EXT-len);
-	
-	return dest;
+    memset(&dest[len], '\0', MAP_NAME_LENGTH_EXT-len);
+
+    return dest;
 }
 
 /// Adds a map to the specified index
 /// Returns 1 if successful, 0 oherwise
-int mapindex_addmap(int index, const char* name)
+int mapindex_addmap(int index, const char *name)
 {
-	char map_name[MAP_NAME_LENGTH];
-
-	if (index == -1){
-		for (index = 1; index < max_index; index++)
-		{
-			//if (strcmp(indexes[index].name,"#CLEARED#")==0)
-			if (indexes[index].name[0] == '\0')
-				break;
-		}
-	}
-
-	if (index < 0 || index >= MAX_MAPINDEX) {
-		ShowError("(mapindex_add) Map index (%d) for \"%s\" out of range (max is %d)\n", index, name, MAX_MAPINDEX);
-		return 0;
-	}
-
-	mapindex_getmapname(name, map_name);
-
-	if (map_name[0] == '\0') {
-		ShowError("(mapindex_add) Cannot add maps with no name.\n");
-		return 0;
-	}
-
-	if (strlen(map_name) >= MAP_NAME_LENGTH) {
-		ShowError("(mapindex_add) Map name %s is too long. Maps are limited to %d characters.\n", map_name, MAP_NAME_LENGTH);
-		return 0;
-	}
-
-	if (mapindex_exists(index))
-		ShowWarning("(mapindex_add) Overriding index %d: map \"%s\" -> \"%s\"\n", index, indexes[index].name, map_name);
-
-	safestrncpy(indexes[index].name, map_name, MAP_NAME_LENGTH);
-	if (max_index <= index)
-		max_index = index+1;
-
-	return index;
+    char map_name[MAP_NAME_LENGTH];
+
+    if (index == -1) {
+        for (index = 1; index < max_index; index++) {
+            //if (strcmp(indexes[index].name,"#CLEARED#")==0)
+            if (indexes[index].name[0] == '\0')
+                break;
+        }
+    }
+
+    if (index < 0 || index >= MAX_MAPINDEX) {
+        ShowError("(mapindex_add) Map index (%d) for \"%s\" out of range (max is %d)\n", index, name, MAX_MAPINDEX);
+        return 0;
+    }
+
+    mapindex_getmapname(name, map_name);
+
+    if (map_name[0] == '\0') {
+        ShowError("(mapindex_add) Cannot add maps with no name.\n");
+        return 0;
+    }
+
+    if (strlen(map_name) >= MAP_NAME_LENGTH) {
+        ShowError("(mapindex_add) Map name %s is too long. Maps are limited to %d characters.\n", map_name, MAP_NAME_LENGTH);
+        return 0;
+    }
+
+    if (mapindex_exists(index))
+        ShowWarning("(mapindex_add) Overriding index %d: map \"%s\" -> \"%s\"\n", index, indexes[index].name, map_name);
+
+    safestrncpy(indexes[index].name, map_name, MAP_NAME_LENGTH);
+    if (max_index <= index)
+        max_index = index+1;
+
+    return index;
 }
 
-unsigned short mapindex_name2id(const char* name)
+unsigned short mapindex_name2id(const char *name)
 {
-	//TODO: Perhaps use a db to speed this up? [Skotlex]
-	int i;
-
-	char map_name[MAP_NAME_LENGTH];
-	mapindex_getmapname(name, map_name);
-
-	for (i = 1; i < max_index; i++)
-	{
-		if (strcmpi(indexes[i].name,map_name)==0)
-			return i;
-	}
-	ShowDebug("mapindex_name2id: Map \"%s\" not found in index list!\n", map_name);
-	return 0;
+    //TODO: Perhaps use a db to speed this up? [Skotlex]
+    int i;
+
+    char map_name[MAP_NAME_LENGTH];
+    mapindex_getmapname(name, map_name);
+
+    for (i = 1; i < max_index; i++) {
+        if (strcmpi(indexes[i].name,map_name)==0)
+            return i;
+    }
+    ShowDebug("mapindex_name2id: Map \"%s\" not found in index list!\n", map_name);
+    return 0;
 }
 
-const char* mapindex_id2name(unsigned short id)
+const char *mapindex_id2name(unsigned short id)
 {
-	if (id > MAX_MAPINDEX || !mapindex_exists(id)) {
-		ShowDebug("mapindex_id2name: Requested name for non-existant map index [%d] in cache.\n", id);
-		return indexes[0].name; // dummy empty string so that the callee doesn't crash
-	}
-	return indexes[id].name;
+    if (id > MAX_MAPINDEX || !mapindex_exists(id)) {
+        ShowDebug("mapindex_id2name: Requested name for non-existant map index [%d] in cache.\n", id);
+        return indexes[0].name; // dummy empty string so that the callee doesn't crash
+    }
+    return indexes[id].name;
 }
 
 void mapindex_init(void)
 {
-	FILE *fp;
-	char line[1024];
-	int last_index = -1;
-	int index;
-	char map_name[1024];
-	
-	memset (&indexes, 0, sizeof (indexes));
-	fp=fopen(mapindex_cfgfile,"r");
-	if(fp==NULL){
-		ShowFatalError("Unable to read mapindex config file %s!\n", mapindex_cfgfile);
-		exit(EXIT_FAILURE); //Server can't really run without this file.
-	}
-	while(fgets(line, sizeof(line), fp))
-	{
-		if(line[0] == '/' && line[1] == '/')
-			continue;
-
-		switch (sscanf(line, "%1023s\t%d", map_name, &index))
-		{
-			case 1: //Map with no ID given, auto-assign
-				index = last_index+1;
-			case 2: //Map with ID given
-				mapindex_addmap(index,map_name);
-				break;
-			default:
-				continue;
-		}
-		last_index = index;
-	}
-	fclose(fp);
+    FILE *fp;
+    char line[1024];
+    int last_index = -1;
+    int index;
+    char map_name[1024];
+
+    memset(&indexes, 0, sizeof(indexes));
+    fp=fopen(mapindex_cfgfile,"r");
+    if (fp==NULL) {
+        ShowFatalError("Unable to read mapindex config file %s!\n", mapindex_cfgfile);
+        exit(EXIT_FAILURE); //Server can't really run without this file.
+    }
+    while (fgets(line, sizeof(line), fp)) {
+        if (line[0] == '/' && line[1] == '/')
+            continue;
+
+        switch (sscanf(line, "%1023s\t%d", map_name, &index)) {
+            case 1: //Map with no ID given, auto-assign
+                index = last_index+1;
+            case 2: //Map with ID given
+                mapindex_addmap(index,map_name);
+                break;
+            default:
+                continue;
+        }
+        last_index = index;
+    }
+    fclose(fp);
 }
 
-int mapindex_removemap(int index){
-	indexes[index].name[0] = '\0';
-	return 0;
+int mapindex_removemap(int index)
+{
+    indexes[index].name[0] = '\0';
+    return 0;
 }
 
 void mapindex_final(void)

+ 5 - 5
src/common/mapindex.h

@@ -47,14 +47,14 @@ extern char mapindex_cfgfile[80];
 #define MAP_MALAYA "malaya"
 #define MAP_ECLAGE "eclage"
 
-const char* mapindex_getmapname(const char* string, char* output);
-const char* mapindex_getmapname_ext(const char* string, char* output);
-unsigned short mapindex_name2id(const char*);
-const char* mapindex_id2name(unsigned short);
+const char *mapindex_getmapname(const char *string, char *output);
+const char *mapindex_getmapname_ext(const char *string, char *output);
+unsigned short mapindex_name2id(const char *);
+const char *mapindex_id2name(unsigned short);
 void mapindex_init(void);
 void mapindex_final(void);
 
-int mapindex_addmap(int index, const char* name);
+int mapindex_addmap(int index, const char *name);
 int mapindex_removemap(int index);
 
 #endif /* _MAPINDEX_H_ */

+ 205 - 157
src/common/md5calc.c

@@ -21,22 +21,22 @@ static unsigned int *pX;
 
 // String Table
 static const unsigned int T[] = {
-   0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, //0
-   0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, //4
-   0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, //8
-   0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, //12
-   0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, //16
-   0xd62f105d,  0x2441453, 0xd8a1e681, 0xe7d3fbc8, //20
-   0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, //24
-   0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, //28
-   0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, //32
-   0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, //36
-   0x289b7ec6, 0xeaa127fa, 0xd4ef3085,  0x4881d05, //40
-   0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, //44
-   0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, //48
-   0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, //52
-   0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, //56
-   0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391  //60
+    0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, //0
+    0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, //4
+    0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, //8
+    0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, //12
+    0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, //16
+    0xd62f105d,  0x2441453, 0xd8a1e681, 0xe7d3fbc8, //20
+    0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, //24
+    0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, //28
+    0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, //32
+    0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, //36
+    0x289b7ec6, 0xeaa127fa, 0xd4ef3085,  0x4881d05, //40
+    0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, //44
+    0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, //48
+    0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, //52
+    0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, //56
+    0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391  //60
 };
 
 // ROTATE_LEFT   The left is made to rotate x [ n-bit ]. This is diverted as it is from RFC.
@@ -45,196 +45,244 @@ static const unsigned int T[] = {
 // The function used for other calculation
 static unsigned int F(unsigned int X, unsigned int Y, unsigned int Z)
 {
-   return (X & Y) | (~X & Z);
+    return (X & Y) | (~X & Z);
 }
 static unsigned int G(unsigned int X, unsigned int Y, unsigned int Z)
 {
-   return (X & Z) | (Y & ~Z);
+    return (X & Z) | (Y & ~Z);
 }
 static unsigned int H(unsigned int X, unsigned int Y, unsigned int Z)
 {
-   return X ^ Y ^ Z;
+    return X ^ Y ^ Z;
 }
 static unsigned int I(unsigned int X, unsigned int Y, unsigned int Z)
 {
-   return Y ^ (X | ~Z);
+    return Y ^ (X | ~Z);
 }
 
 static unsigned int Round(unsigned int a, unsigned int b, unsigned int FGHI,
-                     unsigned int k, unsigned int s, unsigned int i)
+                          unsigned int k, unsigned int s, unsigned int i)
 {
-   return b + ROTATE_LEFT(a + FGHI + pX[k] + T[i], s);
+    return b + ROTATE_LEFT(a + FGHI + pX[k] + T[i], s);
 }
 
 static void Round1(unsigned int *a, unsigned int b, unsigned int c,
-		unsigned int d,unsigned int k, unsigned int s, unsigned int i)
+                   unsigned int d,unsigned int k, unsigned int s, unsigned int i)
 {
-	*a = Round(*a, b, F(b,c,d), k, s, i);
+    *a = Round(*a, b, F(b,c,d), k, s, i);
 }
 static void Round2(unsigned int *a, unsigned int b, unsigned int c,
-		unsigned int d,unsigned int k, unsigned int s, unsigned int i)
+                   unsigned int d,unsigned int k, unsigned int s, unsigned int i)
 {
-	*a = Round(*a, b, G(b,c,d), k, s, i);
+    *a = Round(*a, b, G(b,c,d), k, s, i);
 }
 static void Round3(unsigned int *a, unsigned int b, unsigned int c,
-		unsigned int d,unsigned int k, unsigned int s, unsigned int i)
+                   unsigned int d,unsigned int k, unsigned int s, unsigned int i)
 {
-	*a = Round(*a, b, H(b,c,d), k, s, i);
+    *a = Round(*a, b, H(b,c,d), k, s, i);
 }
 static void Round4(unsigned int *a, unsigned int b, unsigned int c,
-		unsigned int d,unsigned int k, unsigned int s, unsigned int i)
+                   unsigned int d,unsigned int k, unsigned int s, unsigned int i)
 {
-	*a = Round(*a, b, I(b,c,d), k, s, i);
+    *a = Round(*a, b, I(b,c,d), k, s, i);
 }
 
 static void MD5_Round_Calculate(const unsigned char *block,
-	unsigned int *A2, unsigned int *B2, unsigned int *C2, unsigned int *D2)
+                                unsigned int *A2, unsigned int *B2, unsigned int *C2, unsigned int *D2)
 {
-	//create X It is since it is required.
-	unsigned int X[16]; //512bit 64byte
-	int j,k;
-
-	//Save A as AA, B as BB, C as CC, and and D as DD (saving of A, B, C, and D)
-	unsigned int A=*A2, B=*B2, C=*C2, D=*D2;
-	unsigned int AA = A,BB = B,CC = C,DD = D;
-
-	//It is a large region variable reluctantly because of calculation of a round. . . for Round1...4
-	pX = X;
-
-	//Copy block(padding_message) i into X
-	for (j=0,k=0; j<64; j+=4,k++)
-		X[k] = ( (unsigned int )block[j] )         // 8byte*4 -> 32byte conversion
-			| ( ((unsigned int )block[j+1]) << 8 ) // A function called Decode as used in the field of RFC
-			| ( ((unsigned int )block[j+2]) << 16 )
-			| ( ((unsigned int )block[j+3]) << 24 );
-
-
-   //Round 1
-   Round1(&A,B,C,D,  0, 7,  0); Round1(&D,A,B,C,  1, 12,  1); Round1(&C,D,A,B,  2, 17,  2); Round1(&B,C,D,A,  3, 22,  3);
-   Round1(&A,B,C,D,  4, 7,  4); Round1(&D,A,B,C,  5, 12,  5); Round1(&C,D,A,B,  6, 17,  6); Round1(&B,C,D,A,  7, 22,  7);
-   Round1(&A,B,C,D,  8, 7,  8); Round1(&D,A,B,C,  9, 12,  9); Round1(&C,D,A,B, 10, 17, 10); Round1(&B,C,D,A, 11, 22, 11);
-   Round1(&A,B,C,D, 12, 7, 12); Round1(&D,A,B,C, 13, 12, 13); Round1(&C,D,A,B, 14, 17, 14); Round1(&B,C,D,A, 15, 22, 15);
-
-   //Round 2
-   Round2(&A,B,C,D,  1, 5, 16); Round2(&D,A,B,C,  6, 9, 17); Round2(&C,D,A,B, 11, 14, 18); Round2(&B,C,D,A,  0, 20, 19);
-   Round2(&A,B,C,D,  5, 5, 20); Round2(&D,A,B,C, 10, 9, 21); Round2(&C,D,A,B, 15, 14, 22); Round2(&B,C,D,A,  4, 20, 23);
-   Round2(&A,B,C,D,  9, 5, 24); Round2(&D,A,B,C, 14, 9, 25); Round2(&C,D,A,B,  3, 14, 26); Round2(&B,C,D,A,  8, 20, 27);
-   Round2(&A,B,C,D, 13, 5, 28); Round2(&D,A,B,C,  2, 9, 29); Round2(&C,D,A,B,  7, 14, 30); Round2(&B,C,D,A, 12, 20, 31);
-
-   //Round 3
-   Round3(&A,B,C,D,  5, 4, 32); Round3(&D,A,B,C,  8, 11, 33); Round3(&C,D,A,B, 11, 16, 34); Round3(&B,C,D,A, 14, 23, 35);
-   Round3(&A,B,C,D,  1, 4, 36); Round3(&D,A,B,C,  4, 11, 37); Round3(&C,D,A,B,  7, 16, 38); Round3(&B,C,D,A, 10, 23, 39);
-   Round3(&A,B,C,D, 13, 4, 40); Round3(&D,A,B,C,  0, 11, 41); Round3(&C,D,A,B,  3, 16, 42); Round3(&B,C,D,A,  6, 23, 43);
-   Round3(&A,B,C,D,  9, 4, 44); Round3(&D,A,B,C, 12, 11, 45); Round3(&C,D,A,B, 15, 16, 46); Round3(&B,C,D,A,  2, 23, 47);
-
-   //Round 4
-   Round4(&A,B,C,D,  0, 6, 48); Round4(&D,A,B,C,  7, 10, 49); Round4(&C,D,A,B, 14, 15, 50); Round4(&B,C,D,A,  5, 21, 51);
-   Round4(&A,B,C,D, 12, 6, 52); Round4(&D,A,B,C,  3, 10, 53); Round4(&C,D,A,B, 10, 15, 54); Round4(&B,C,D,A,  1, 21, 55);
-   Round4(&A,B,C,D,  8, 6, 56); Round4(&D,A,B,C, 15, 10, 57); Round4(&C,D,A,B,  6, 15, 58); Round4(&B,C,D,A, 13, 21, 59);
-   Round4(&A,B,C,D,  4, 6, 60); Round4(&D,A,B,C, 11, 10, 61); Round4(&C,D,A,B,  2, 15, 62); Round4(&B,C,D,A,  9, 21, 63);
-
-   // Then perform the following additions. (let's add)
-   *A2 = A + AA;
-   *B2 = B + BB;
-   *C2 = C + CC;
-   *D2 = D + DD;
-
-   //The clearance of confidential information
-   memset(pX, 0, sizeof(X));
+    //create X It is since it is required.
+    unsigned int X[16]; //512bit 64byte
+    int j,k;
+
+    //Save A as AA, B as BB, C as CC, and and D as DD (saving of A, B, C, and D)
+    unsigned int A=*A2, B=*B2, C=*C2, D=*D2;
+    unsigned int AA = A,BB = B,CC = C,DD = D;
+
+    //It is a large region variable reluctantly because of calculation of a round. . . for Round1...4
+    pX = X;
+
+    //Copy block(padding_message) i into X
+    for (j=0,k=0; j<64; j+=4,k++)
+        X[k] = ((unsigned int)block[j])            // 8byte*4 -> 32byte conversion
+               | (((unsigned int)block[j+1]) << 8)    // A function called Decode as used in the field of RFC
+               | (((unsigned int)block[j+2]) << 16)
+               | (((unsigned int)block[j+3]) << 24);
+
+
+    //Round 1
+    Round1(&A,B,C,D,  0, 7,  0);
+    Round1(&D,A,B,C,  1, 12,  1);
+    Round1(&C,D,A,B,  2, 17,  2);
+    Round1(&B,C,D,A,  3, 22,  3);
+    Round1(&A,B,C,D,  4, 7,  4);
+    Round1(&D,A,B,C,  5, 12,  5);
+    Round1(&C,D,A,B,  6, 17,  6);
+    Round1(&B,C,D,A,  7, 22,  7);
+    Round1(&A,B,C,D,  8, 7,  8);
+    Round1(&D,A,B,C,  9, 12,  9);
+    Round1(&C,D,A,B, 10, 17, 10);
+    Round1(&B,C,D,A, 11, 22, 11);
+    Round1(&A,B,C,D, 12, 7, 12);
+    Round1(&D,A,B,C, 13, 12, 13);
+    Round1(&C,D,A,B, 14, 17, 14);
+    Round1(&B,C,D,A, 15, 22, 15);
+
+    //Round 2
+    Round2(&A,B,C,D,  1, 5, 16);
+    Round2(&D,A,B,C,  6, 9, 17);
+    Round2(&C,D,A,B, 11, 14, 18);
+    Round2(&B,C,D,A,  0, 20, 19);
+    Round2(&A,B,C,D,  5, 5, 20);
+    Round2(&D,A,B,C, 10, 9, 21);
+    Round2(&C,D,A,B, 15, 14, 22);
+    Round2(&B,C,D,A,  4, 20, 23);
+    Round2(&A,B,C,D,  9, 5, 24);
+    Round2(&D,A,B,C, 14, 9, 25);
+    Round2(&C,D,A,B,  3, 14, 26);
+    Round2(&B,C,D,A,  8, 20, 27);
+    Round2(&A,B,C,D, 13, 5, 28);
+    Round2(&D,A,B,C,  2, 9, 29);
+    Round2(&C,D,A,B,  7, 14, 30);
+    Round2(&B,C,D,A, 12, 20, 31);
+
+    //Round 3
+    Round3(&A,B,C,D,  5, 4, 32);
+    Round3(&D,A,B,C,  8, 11, 33);
+    Round3(&C,D,A,B, 11, 16, 34);
+    Round3(&B,C,D,A, 14, 23, 35);
+    Round3(&A,B,C,D,  1, 4, 36);
+    Round3(&D,A,B,C,  4, 11, 37);
+    Round3(&C,D,A,B,  7, 16, 38);
+    Round3(&B,C,D,A, 10, 23, 39);
+    Round3(&A,B,C,D, 13, 4, 40);
+    Round3(&D,A,B,C,  0, 11, 41);
+    Round3(&C,D,A,B,  3, 16, 42);
+    Round3(&B,C,D,A,  6, 23, 43);
+    Round3(&A,B,C,D,  9, 4, 44);
+    Round3(&D,A,B,C, 12, 11, 45);
+    Round3(&C,D,A,B, 15, 16, 46);
+    Round3(&B,C,D,A,  2, 23, 47);
+
+    //Round 4
+    Round4(&A,B,C,D,  0, 6, 48);
+    Round4(&D,A,B,C,  7, 10, 49);
+    Round4(&C,D,A,B, 14, 15, 50);
+    Round4(&B,C,D,A,  5, 21, 51);
+    Round4(&A,B,C,D, 12, 6, 52);
+    Round4(&D,A,B,C,  3, 10, 53);
+    Round4(&C,D,A,B, 10, 15, 54);
+    Round4(&B,C,D,A,  1, 21, 55);
+    Round4(&A,B,C,D,  8, 6, 56);
+    Round4(&D,A,B,C, 15, 10, 57);
+    Round4(&C,D,A,B,  6, 15, 58);
+    Round4(&B,C,D,A, 13, 21, 59);
+    Round4(&A,B,C,D,  4, 6, 60);
+    Round4(&D,A,B,C, 11, 10, 61);
+    Round4(&C,D,A,B,  2, 15, 62);
+    Round4(&B,C,D,A,  9, 21, 63);
+
+    // Then perform the following additions. (let's add)
+    *A2 = A + AA;
+    *B2 = B + BB;
+    *C2 = C + CC;
+    *D2 = D + DD;
+
+    //The clearance of confidential information
+    memset(pX, 0, sizeof(X));
 }
 
-static void MD5_String2binary(const char * string, unsigned char * output)
+static void MD5_String2binary(const char *string, unsigned char *output)
 {
-//var
-   /*8bit*/
-   unsigned char padding_message[64]; //Extended message   512bit 64byte
-   unsigned char *pstring;            //The position of string in the present scanning notes is held.
-
-   /*32bit*/
-   unsigned int string_byte_len,     //The byte chief of string is held.
-                string_bit_len,      //The bit length of string is held.
-                copy_len,            //The number of bytes which is used by 1-3 and which remained
-                msg_digest[4];       //Message digest   128bit 4byte
-   unsigned int *A = &msg_digest[0], //The message digest in accordance with RFC (reference)
-                *B = &msg_digest[1],
-                *C = &msg_digest[2],
-                *D = &msg_digest[3];
-	int i;
-
-//prog
-   //Step 3.Initialize MD Buffer (although it is the initialization; step 3 of A, B, C, and D -- unavoidable -- a head)
-   *A = 0x67452301;
-   *B = 0xefcdab89;
-   *C = 0x98badcfe;
-   *D = 0x10325476;
-
-   //Step 1.Append Padding Bits (extension of a mark bit)
-   //1-1
-   string_byte_len = (unsigned int)strlen(string);    //The byte chief of a character sequence is acquired.
-   pstring = (unsigned char *)string; //The position of the present character sequence is set.
-
-   //1-2  Repeat calculation until length becomes less than 64 bytes.
-   for (i=string_byte_len; 64<=i; i-=64,pstring+=64)
+    //var
+    /*8bit*/
+    unsigned char padding_message[64]; //Extended message   512bit 64byte
+    unsigned char *pstring;            //The position of string in the present scanning notes is held.
+
+    /*32bit*/
+    unsigned int string_byte_len,     //The byte chief of string is held.
+             string_bit_len,      //The bit length of string is held.
+             copy_len,            //The number of bytes which is used by 1-3 and which remained
+             msg_digest[4];       //Message digest   128bit 4byte
+    unsigned int *A = &msg_digest[0], //The message digest in accordance with RFC (reference)
+                  *B = &msg_digest[1],
+                   *C = &msg_digest[2],
+                    *D = &msg_digest[3];
+    int i;
+
+    //prog
+    //Step 3.Initialize MD Buffer (although it is the initialization; step 3 of A, B, C, and D -- unavoidable -- a head)
+    *A = 0x67452301;
+    *B = 0xefcdab89;
+    *C = 0x98badcfe;
+    *D = 0x10325476;
+
+    //Step 1.Append Padding Bits (extension of a mark bit)
+    //1-1
+    string_byte_len = (unsigned int)strlen(string);    //The byte chief of a character sequence is acquired.
+    pstring = (unsigned char *)string; //The position of the present character sequence is set.
+
+    //1-2  Repeat calculation until length becomes less than 64 bytes.
+    for (i=string_byte_len; 64<=i; i-=64,pstring+=64)
         MD5_Round_Calculate(pstring, A,B,C,D);
 
-   //1-3
-   copy_len = string_byte_len % 64;                               //The number of bytes which remained is computed.
-   strncpy((char *)padding_message, (char *)pstring, copy_len); //A message is copied to an extended bit sequence.
-   memset(padding_message+copy_len, 0, 64 - copy_len);           //It buries by 0 until it becomes extended bit length.
-   padding_message[copy_len] |= 0x80;                            //The next of a message is 1.
-
-   //1-4
-   //If 56 bytes or more (less than 64 bytes) of remainder becomes, it will calculate by extending to 64 bytes.
-   if (56 <= copy_len) {
-       MD5_Round_Calculate(padding_message, A,B,C,D);
-       memset(padding_message, 0, 56); //56 bytes is newly fill uped with 0.
-   }
-
-   //Step 2.Append Length (the information on length is added)
-   string_bit_len = string_byte_len * 8;             //From the byte chief to bit length (32 bytes of low rank)
-   memcpy(&padding_message[56], &string_bit_len, 4); //32 bytes of low rank is set.
-
-   //When bit length cannot be expressed in 32 bytes of low rank, it is a beam raising to a higher rank.
-  if (UINT_MAX / 8 < string_byte_len) {
-      unsigned int high = (string_byte_len - UINT_MAX / 8) * 8;
-      memcpy(&padding_message[60], &high, 4);
-  } else
-      memset(&padding_message[60], 0, 4); //In this case, it is good for a higher rank at 0.
-
-   //Step 4.Process Message in 16-Word Blocks (calculation of MD5)
-   MD5_Round_Calculate(padding_message, A,B,C,D);
-
-   //Step 5.Output (output)
-   memcpy(output,msg_digest,16);
+    //1-3
+    copy_len = string_byte_len % 64;                               //The number of bytes which remained is computed.
+    strncpy((char *)padding_message, (char *)pstring, copy_len); //A message is copied to an extended bit sequence.
+    memset(padding_message+copy_len, 0, 64 - copy_len);           //It buries by 0 until it becomes extended bit length.
+    padding_message[copy_len] |= 0x80;                            //The next of a message is 1.
+
+    //1-4
+    //If 56 bytes or more (less than 64 bytes) of remainder becomes, it will calculate by extending to 64 bytes.
+    if (56 <= copy_len) {
+        MD5_Round_Calculate(padding_message, A,B,C,D);
+        memset(padding_message, 0, 56); //56 bytes is newly fill uped with 0.
+    }
+
+    //Step 2.Append Length (the information on length is added)
+    string_bit_len = string_byte_len * 8;             //From the byte chief to bit length (32 bytes of low rank)
+    memcpy(&padding_message[56], &string_bit_len, 4); //32 bytes of low rank is set.
+
+    //When bit length cannot be expressed in 32 bytes of low rank, it is a beam raising to a higher rank.
+    if (UINT_MAX / 8 < string_byte_len) {
+        unsigned int high = (string_byte_len - UINT_MAX / 8) * 8;
+        memcpy(&padding_message[60], &high, 4);
+    } else
+        memset(&padding_message[60], 0, 4); //In this case, it is good for a higher rank at 0.
+
+    //Step 4.Process Message in 16-Word Blocks (calculation of MD5)
+    MD5_Round_Calculate(padding_message, A,B,C,D);
+
+    //Step 5.Output (output)
+    memcpy(output,msg_digest,16);
 }
 
 //-------------------------------------------------------------------
 // The function for the exteriors
 
 /** output is the coded binary in the character sequence which wants to code string. */
-void MD5_Binary(const char * string, unsigned char * output)
+void MD5_Binary(const char *string, unsigned char *output)
 {
-	MD5_String2binary(string,output);
+    MD5_String2binary(string,output);
 }
 
 /** output is the coded character sequence in the character sequence which wants to code string. */
-void MD5_String(const char * string, char * output)
+void MD5_String(const char *string, char *output)
 {
-	unsigned char digest[16];
-
-	MD5_String2binary(string,digest);
-	sprintf(output,	"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
-		digest[ 0], digest[ 1], digest[ 2], digest[ 3],
-		digest[ 4], digest[ 5], digest[ 6], digest[ 7],
-		digest[ 8], digest[ 9], digest[10], digest[11],
-		digest[12], digest[13], digest[14], digest[15]);
+    unsigned char digest[16];
+
+    MD5_String2binary(string,digest);
+    sprintf(output, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+            digest[ 0], digest[ 1], digest[ 2], digest[ 3],
+            digest[ 4], digest[ 5], digest[ 6], digest[ 7],
+            digest[ 8], digest[ 9], digest[10], digest[11],
+            digest[12], digest[13], digest[14], digest[15]);
 }
 
 /** output is a sequence of non-zero characters to be used as password salt. */
-void MD5_Salt(unsigned int len, char * output)
+void MD5_Salt(unsigned int len, char *output)
 {
-	unsigned int i;
-	for( i = 0; i < len; ++i )
-		output[i] = (char)(1 + rnd() % 255);
+    unsigned int i;
+    for (i = 0; i < len; ++i)
+        output[i] = (char)(1 + rnd() % 255);
 
 }

+ 3 - 3
src/common/md5calc.h

@@ -1,8 +1,8 @@
 #ifndef _MD5CALC_H_
 #define _MD5CALC_H_
 
-void MD5_String(const char * string, char * output);
-void MD5_Binary(const char * string, unsigned char * output);
-void MD5_Salt(unsigned int len, char * output);
+void MD5_String(const char *string, char *output);
+void MD5_Binary(const char *string, unsigned char *output);
+void MD5_Salt(unsigned int len, char *output);
 
 #endif /* _MD5CALC_H_ */

+ 454 - 445
src/common/mempool.c

@@ -30,9 +30,9 @@
 #include "../common/malloc.h"
 #include "../common/mutex.h"
 
-#define ALIGN16	ra_align(16)
+#define ALIGN16 ra_align(16)
 #define ALIGN_TO(x, a) (x + ( a - ( x % a) ) )
-#define ALIGN_TO_16(x)	ALIGN_TO(x, 16)
+#define ALIGN_TO_16(x)  ALIGN_TO(x, 16)
 
 #undef MEMPOOL_DEBUG
 #define MEMPOOLASSERT
@@ -40,523 +40,532 @@
 
 #define NODE_TO_DATA(x) ( ((char*)x) + sizeof(struct node) )
 #define DATA_TO_NODE(x) ( (struct node*)(((char*)x) - sizeof(struct node)) )
-struct ra_align(16) node{
-	void 	*next;
-	void 	*segment;
+struct ra_align(16) node {
+    void    *next;
+    void    *segment;
 #ifdef MEMPOOLASSERT
-	bool	used;
-	uint64	magic;
-	#define NODE_MAGIC 0xBEEF00EAEACAFE07ll
+    bool    used;
+    uint64  magic;
+#define NODE_MAGIC 0xBEEF00EAEACAFE07ll
 #endif
 };
 
 
 // The Pointer to this struct is the base address of the segment itself.
-struct pool_segment{
-	mempool	pool; // pool, this segment belongs to
-	struct 	pool_segment *next;
-	int64	num_nodes_total;	
-	int64	num_bytes;
+struct pool_segment {
+    mempool pool; // pool, this segment belongs to
+    struct  pool_segment *next;
+    int64   num_nodes_total;
+    int64   num_bytes;
 };
 
 
-struct mempool{
-	// Settings
-	char *name;
-	uint64	elem_size;
-	uint64	elem_realloc_step;
-	int64	elem_realloc_thresh;
-	
-	// Callbacks that get called for every node that gets allocated
-	// Example usage: initialization of mutex/lock for each node.
-	memPoolOnNodeAllocationProc		onalloc;
-	memPoolOnNodeDeallocationProc	ondealloc;
-
-	// Locks
-	SPIN_LOCK segmentLock;
-	SPIN_LOCK nodeLock;
-	
-
-	// Internal 
-	struct pool_segment *segments;
-	struct node	*free_list;
-		
-	volatile int64  num_nodes_total;
-	volatile int64	num_nodes_free;
-
-	volatile int64	num_segments;
-	volatile int64	num_bytes_total;
-	
-	volatile int64	peak_nodes_used;		// Peak Node Usage 
-	volatile int64	num_realloc_events; 	// Number of reallocations done. (allocate additional nodes)
-
-	// list (used for global management such as allocator..)
-	struct mempool *next;
+struct mempool {
+    // Settings
+    char *name;
+    uint64  elem_size;
+    uint64  elem_realloc_step;
+    int64   elem_realloc_thresh;
+
+    // Callbacks that get called for every node that gets allocated
+    // Example usage: initialization of mutex/lock for each node.
+    memPoolOnNodeAllocationProc     onalloc;
+    memPoolOnNodeDeallocationProc   ondealloc;
+
+    // Locks
+    SPIN_LOCK segmentLock;
+    SPIN_LOCK nodeLock;
+
+
+    // Internal
+    struct pool_segment *segments;
+    struct node *free_list;
+
+    volatile int64  num_nodes_total;
+    volatile int64  num_nodes_free;
+
+    volatile int64  num_segments;
+    volatile int64  num_bytes_total;
+
+    volatile int64  peak_nodes_used;        // Peak Node Usage
+    volatile int64  num_realloc_events;     // Number of reallocations done. (allocate additional nodes)
+
+    // list (used for global management such as allocator..)
+    struct mempool *next;
 } ra_align(8); // Dont touch the alignment, otherwise interlocked functions are broken ..
 
 
-/// 
+///
 // Implementation:
 //
 static void segment_allocate_add(mempool p,  uint64 count);
 
 static SPIN_LOCK l_mempoolListLock;
-static mempool 	l_mempoolList = NULL;
+static mempool  l_mempoolList = NULL;
 static rAthread l_async_thread = NULL;
-static ramutex	l_async_lock = NULL;
-static racond	l_async_cond = NULL;
+static ramutex  l_async_lock = NULL;
+static racond   l_async_cond = NULL;
 static volatile int32 l_async_terminate = 0;
 
-static void *mempool_async_allocator(void *x){
-	mempool p;
-	
-	
-	while(1){
-		if(l_async_terminate > 0)
-			break;
-
-		EnterSpinLock(&l_mempoolListLock);
-		
-			for(p = l_mempoolList;  p != NULL;  p = p->next){
-				
-				if(p->num_nodes_free < p->elem_realloc_thresh){
-					// add new segment.
-					segment_allocate_add(p, p->elem_realloc_step);
-					// increase stats counter
-					InterlockedIncrement64(&p->num_realloc_events);
-				}
-				
-			}
-	
-		LeaveSpinLock(&l_mempoolListLock);
-		
-		ramutex_lock( l_async_lock );
-		racond_wait( l_async_cond,	l_async_lock,  -1 );
-		ramutex_unlock( l_async_lock );
-	}
-	
-	
-	return NULL;
+static void *mempool_async_allocator(void *x)
+{
+    mempool p;
+
+
+    while (1) {
+        if (l_async_terminate > 0)
+            break;
+
+        EnterSpinLock(&l_mempoolListLock);
+
+        for (p = l_mempoolList;  p != NULL;  p = p->next) {
+
+            if (p->num_nodes_free < p->elem_realloc_thresh) {
+                // add new segment.
+                segment_allocate_add(p, p->elem_realloc_step);
+                // increase stats counter
+                InterlockedIncrement64(&p->num_realloc_events);
+            }
+
+        }
+
+        LeaveSpinLock(&l_mempoolListLock);
+
+        ramutex_lock(l_async_lock);
+        racond_wait(l_async_cond,   l_async_lock,  -1);
+        ramutex_unlock(l_async_lock);
+    }
+
+
+    return NULL;
 }//end: mempool_async_allocator()
 
 
-void mempool_init(){
-	
-	if(sizeof(struct node)%16 != 0 ){
-		ShowFatalError("mempool_init: struct node alignment failure.  %u != multiple of 16\n", sizeof(struct node));
-		exit(EXIT_FAILURE);
-	}
-	
-	// Global List start
-	InitializeSpinLock(&l_mempoolListLock);
-	l_mempoolList = NULL;
-
-	// Initialize mutex + stuff needed for async allocator worker.
-	l_async_terminate = 0;
-	l_async_lock = ramutex_create();
-	l_async_cond = racond_create();
-
-	l_async_thread = rathread_createEx(mempool_async_allocator, NULL, 1024*1024,  RAT_PRIO_NORMAL);
-	if(l_async_thread == NULL){
-		ShowFatalError("mempool_init: cannot spawn Async Allocator Thread.\n");
-		exit(EXIT_FAILURE);
-	}
+void mempool_init()
+{
+
+    if (sizeof(struct node)%16 != 0) {
+        ShowFatalError("mempool_init: struct node alignment failure.  %u != multiple of 16\n", sizeof(struct node));
+        exit(EXIT_FAILURE);
+    }
+
+    // Global List start
+    InitializeSpinLock(&l_mempoolListLock);
+    l_mempoolList = NULL;
+
+    // Initialize mutex + stuff needed for async allocator worker.
+    l_async_terminate = 0;
+    l_async_lock = ramutex_create();
+    l_async_cond = racond_create();
+
+    l_async_thread = rathread_createEx(mempool_async_allocator, NULL, 1024*1024,  RAT_PRIO_NORMAL);
+    if (l_async_thread == NULL) {
+        ShowFatalError("mempool_init: cannot spawn Async Allocator Thread.\n");
+        exit(EXIT_FAILURE);
+    }
 
 }//end: mempool_init()
 
 
-void mempool_final(){
-	mempool p, pn;
-	
-	ShowStatus("Mempool: Terminating async. allocation worker and remaining pools.\n");
-
-	// Terminate worker / wait until its terminated.
-	InterlockedIncrement(&l_async_terminate);
-	racond_signal(l_async_cond);
-	rathread_wait(l_async_thread, NULL);
-	
-	// Destroy cond var and mutex.
-	racond_destroy( l_async_cond );
-	ramutex_destroy( l_async_lock );
-	
-	// Free remaining mempools
-	// ((bugged code! this should halppen, every mempool should 
-	//		be freed by the subsystem that has allocated it.)
-	//
-	EnterSpinLock(&l_mempoolListLock);
-	p = l_mempoolList;
-	while(1){
-		if(p == NULL)
-			break;
-			
-		pn = p->next;
-
-		ShowWarning("Mempool [%s] was not properly destroyed - forcing destroy.\n", p->name);
-		mempool_destroy(p);
-
-		p = pn;
-	}
-	LeaveSpinLock(&l_mempoolListLock);
-	
+void mempool_final()
+{
+    mempool p, pn;
+
+    ShowStatus("Mempool: Terminating async. allocation worker and remaining pools.\n");
+
+    // Terminate worker / wait until its terminated.
+    InterlockedIncrement(&l_async_terminate);
+    racond_signal(l_async_cond);
+    rathread_wait(l_async_thread, NULL);
+
+    // Destroy cond var and mutex.
+    racond_destroy(l_async_cond);
+    ramutex_destroy(l_async_lock);
+
+    // Free remaining mempools
+    // ((bugged code! this should halppen, every mempool should
+    //      be freed by the subsystem that has allocated it.)
+    //
+    EnterSpinLock(&l_mempoolListLock);
+    p = l_mempoolList;
+    while (1) {
+        if (p == NULL)
+            break;
+
+        pn = p->next;
+
+        ShowWarning("Mempool [%s] was not properly destroyed - forcing destroy.\n", p->name);
+        mempool_destroy(p);
+
+        p = pn;
+    }
+    LeaveSpinLock(&l_mempoolListLock);
+
 }//end: mempool_final()
 
 
-static void segment_allocate_add(mempool p,  uint64 count){
-	
-	// Required Memory:
-	//	sz( segment ) 
-	//  count * sz( real_node_size )
-	// 
-	//  where real node size is:
-	//		ALIGN_TO_16( sz( node ) ) + p->elem_size 
-	//  so the nodes usable address is  nodebase + ALIGN_TO_16(sz(node)) 
-	//
-	size_t total_sz;
-	struct pool_segment *seg = NULL;
-	struct node *nodeList = NULL;
-	struct node *node = NULL;
-	char *ptr = NULL;	
-	uint64 i;
-	
-	total_sz = ALIGN_TO_16( sizeof(struct pool_segment) ) 
-				+ ( (size_t)count * (sizeof(struct node) + (size_t)p->elem_size) ) ;
+static void segment_allocate_add(mempool p,  uint64 count)
+{
+
+    // Required Memory:
+    //  sz( segment )
+    //  count * sz( real_node_size )
+    //
+    //  where real node size is:
+    //      ALIGN_TO_16( sz( node ) ) + p->elem_size
+    //  so the nodes usable address is  nodebase + ALIGN_TO_16(sz(node))
+    //
+    size_t total_sz;
+    struct pool_segment *seg = NULL;
+    struct node *nodeList = NULL;
+    struct node *node = NULL;
+    char *ptr = NULL;
+    uint64 i;
+
+    total_sz = ALIGN_TO_16(sizeof(struct pool_segment))
+               + ((size_t)count * (sizeof(struct node) + (size_t)p->elem_size)) ;
 
 #ifdef MEMPOOL_DEBUG
-	ShowDebug("Mempool [%s] Segment AllocateAdd (num: %u, total size: %0.2fMiB)\n", p->name, count, (float)total_sz/1024.f/1024.f);
+    ShowDebug("Mempool [%s] Segment AllocateAdd (num: %u, total size: %0.2fMiB)\n", p->name, count, (float)total_sz/1024.f/1024.f);
 #endif
 
-	// allocate! (spin forever until weve got the memory.)
-	i=0;
-	while(1){
-		ptr = (char*)aMalloc(total_sz);
-		if(ptr != NULL)	break;
-		
-		i++; // increase failcount.
-		if(!(i & 7)){
-			ShowWarning("Mempool [%s] Segment AllocateAdd => System seems to be Out of Memory (%0.2f MiB). Try #%u\n", (float)total_sz/1024.f/1024.f,  i);
+    // allocate! (spin forever until weve got the memory.)
+    i=0;
+    while (1) {
+        ptr = (char *)aMalloc(total_sz);
+        if (ptr != NULL) break;
+
+        i++; // increase failcount.
+        if (!(i & 7)) {
+            ShowWarning("Mempool [%s] Segment AllocateAdd => System seems to be Out of Memory (%0.2f MiB). Try #%u\n", (float)total_sz/1024.f/1024.f,  i);
 #ifdef WIN32
-			Sleep(1000);
+            Sleep(1000);
 #else
-			sleep(1);
+            sleep(1);
 #endif
-		}else{
-			rathread_yield(); /// allow/force vuln. ctxswitch 
-		}
-	}//endwhile: allocation spinloop.
-	
-	// Clear Memory.
-	memset(ptr, 0x00, total_sz);
-	
-	// Initialize segment struct.
-	seg = (struct pool_segment*)ptr;
-	ptr += ALIGN_TO_16(sizeof(struct pool_segment));
-	
-	seg->pool = p;
-	seg->num_nodes_total = count;
-	seg->num_bytes = total_sz;
-	
-	
-	// Initialze nodes! 
-	nodeList = NULL; 
-	for(i = 0; i < count; i++){
-		node = (struct node*)ptr;
-		ptr += sizeof(struct node);
-		ptr += p->elem_size;
-			
-		node->segment = seg;
+        } else {
+            rathread_yield(); /// allow/force vuln. ctxswitch
+        }
+    }//endwhile: allocation spinloop.
+
+    // Clear Memory.
+    memset(ptr, 0x00, total_sz);
+
+    // Initialize segment struct.
+    seg = (struct pool_segment *)ptr;
+    ptr += ALIGN_TO_16(sizeof(struct pool_segment));
+
+    seg->pool = p;
+    seg->num_nodes_total = count;
+    seg->num_bytes = total_sz;
+
+
+    // Initialze nodes!
+    nodeList = NULL;
+    for (i = 0; i < count; i++) {
+        node = (struct node *)ptr;
+        ptr += sizeof(struct node);
+        ptr += p->elem_size;
+
+        node->segment = seg;
 #ifdef MEMPOOLASSERT
-		node->used = false;
-		node->magic = NODE_MAGIC;
+        node->used = false;
+        node->magic = NODE_MAGIC;
 #endif
 
-		if(p->onalloc != NULL)  p->onalloc( NODE_TO_DATA(node) );
-
-		node->next = nodeList;
-		nodeList = node;
-	}	
-
-
-	
-	// Link in Segment.
-	EnterSpinLock(&p->segmentLock);
-		seg->next = p->segments;
-		p->segments = seg;
-	LeaveSpinLock(&p->segmentLock);
-	
-	// Link in Nodes
-	EnterSpinLock(&p->nodeLock);
-		nodeList->next = p->free_list;
-		p->free_list = nodeList;
-	LeaveSpinLock(&p->nodeLock);
-
-
-	// Increase Stats:
-	InterlockedExchangeAdd64(&p->num_nodes_total,  count);
-	InterlockedExchangeAdd64(&p->num_nodes_free,   count);
-	InterlockedIncrement64(&p->num_segments);
-	InterlockedExchangeAdd64(&p->num_bytes_total,	total_sz);
-	
+        if (p->onalloc != NULL)  p->onalloc(NODE_TO_DATA(node));
+
+        node->next = nodeList;
+        nodeList = node;
+    }
+
+
+
+    // Link in Segment.
+    EnterSpinLock(&p->segmentLock);
+    seg->next = p->segments;
+    p->segments = seg;
+    LeaveSpinLock(&p->segmentLock);
+
+    // Link in Nodes
+    EnterSpinLock(&p->nodeLock);
+    nodeList->next = p->free_list;
+    p->free_list = nodeList;
+    LeaveSpinLock(&p->nodeLock);
+
+
+    // Increase Stats:
+    InterlockedExchangeAdd64(&p->num_nodes_total,  count);
+    InterlockedExchangeAdd64(&p->num_nodes_free,   count);
+    InterlockedIncrement64(&p->num_segments);
+    InterlockedExchangeAdd64(&p->num_bytes_total,   total_sz);
+
 }//end: segment_allocate_add()
 
 
 mempool mempool_create(const char *name,
-						uint64 elem_size,
-						uint64 initial_count,
-						uint64 realloc_count,
-						memPoolOnNodeAllocationProc onNodeAlloc,
-						memPoolOnNodeDeallocationProc onNodeDealloc){
-	//..
-	uint64 realloc_thresh;
-	mempool pool;
-	pool = (mempool)aCalloc( 1,  sizeof(struct mempool) );
-	
-	if(pool == NULL){
-		ShowFatalError("mempool_create: Failed to allocate %u bytes memory.\n", sizeof(struct mempool) );
-		exit(EXIT_FAILURE);		
-	}
-	
-	// Check minimum initial count / realloc count requirements.
-	if(initial_count < 50)
-		initial_count = 50;
-	if(realloc_count < 50)
-		realloc_count = 50;
-	
-	// Set Reallocation threshold to 5% of realloc_count, at least 10.
-	realloc_thresh = (realloc_count/100)*5; // 
-	if(realloc_thresh < 10)
-		realloc_thresh = 10;
-
-	// Initialize members..
-	pool->name = aStrdup(name);
-	pool->elem_size	= ALIGN_TO_16(elem_size);
-	pool->elem_realloc_step = realloc_count;
-	pool->elem_realloc_thresh = realloc_thresh;
-	pool->onalloc = onNodeAlloc;
-	pool->ondealloc = onNodeDealloc;
-	
-	InitializeSpinLock(&pool->segmentLock);
-	InitializeSpinLock(&pool->nodeLock);
-
-	// Initial Statistic values:
-	pool->num_nodes_total = 0;
-	pool->num_nodes_free = 0;
-	pool->num_segments = 0;
-	pool->num_bytes_total = 0;
-	pool->peak_nodes_used = 0;
-	pool->num_realloc_events = 0;
-		
-	//
+                       uint64 elem_size,
+                       uint64 initial_count,
+                       uint64 realloc_count,
+                       memPoolOnNodeAllocationProc onNodeAlloc,
+                       memPoolOnNodeDeallocationProc onNodeDealloc)
+{
+    //..
+    uint64 realloc_thresh;
+    mempool pool;
+    pool = (mempool)aCalloc(1,  sizeof(struct mempool));
+
+    if (pool == NULL) {
+        ShowFatalError("mempool_create: Failed to allocate %u bytes memory.\n", sizeof(struct mempool));
+        exit(EXIT_FAILURE);
+    }
+
+    // Check minimum initial count / realloc count requirements.
+    if (initial_count < 50)
+        initial_count = 50;
+    if (realloc_count < 50)
+        realloc_count = 50;
+
+    // Set Reallocation threshold to 5% of realloc_count, at least 10.
+    realloc_thresh = (realloc_count/100)*5; //
+    if (realloc_thresh < 10)
+        realloc_thresh = 10;
+
+    // Initialize members..
+    pool->name = aStrdup(name);
+    pool->elem_size = ALIGN_TO_16(elem_size);
+    pool->elem_realloc_step = realloc_count;
+    pool->elem_realloc_thresh = realloc_thresh;
+    pool->onalloc = onNodeAlloc;
+    pool->ondealloc = onNodeDealloc;
+
+    InitializeSpinLock(&pool->segmentLock);
+    InitializeSpinLock(&pool->nodeLock);
+
+    // Initial Statistic values:
+    pool->num_nodes_total = 0;
+    pool->num_nodes_free = 0;
+    pool->num_segments = 0;
+    pool->num_bytes_total = 0;
+    pool->peak_nodes_used = 0;
+    pool->num_realloc_events = 0;
+
+    //
 #ifdef MEMPOOL_DEBUG
-	ShowDebug("Mempool [%s] Init (ElemSize: %u,  Initial Count: %u,  Realloc Count: %u)\n", pool->name,  pool->elem_size,  initial_count,  pool->elem_realloc_step);
+    ShowDebug("Mempool [%s] Init (ElemSize: %u,  Initial Count: %u,  Realloc Count: %u)\n", pool->name,  pool->elem_size,  initial_count,  pool->elem_realloc_step);
 #endif
 
-	// Allocate first segment directly :) 	
-	segment_allocate_add(pool, initial_count);
-	
+    // Allocate first segment directly :)
+    segment_allocate_add(pool, initial_count);
+
+
+    // Add Pool to the global pool list
+    EnterSpinLock(&l_mempoolListLock);
+    pool->next = l_mempoolList;
+    l_mempoolList = pool;
+    LeaveSpinLock(&l_mempoolListLock);
 
-	// Add Pool to the global pool list
-	EnterSpinLock(&l_mempoolListLock);
-		pool->next = l_mempoolList;
-		l_mempoolList = pool;
-	LeaveSpinLock(&l_mempoolListLock);
 
-	
-	return pool;	
+    return pool;
 }//end: mempool_create()
 
 
-void mempool_destroy(mempool p){
-	struct  pool_segment *seg, *segnext;
-	struct	node *niter;
-	mempool piter, pprev;
-	char *ptr;
-	int64 i;
+void mempool_destroy(mempool p)
+{
+    struct  pool_segment *seg, *segnext;
+    struct  node *niter;
+    mempool piter, pprev;
+    char *ptr;
+    int64 i;
 
 #ifdef MEMPOOL_DEBUG
     ShowDebug("Mempool [%s] Destroy\n", p->name);
 #endif
-    
-	// Unlink from global list.
-	EnterSpinLock(&l_mempoolListLock);
-		piter = l_mempoolList;
-		pprev = l_mempoolList;
-		while(1){
-			if(piter == NULL)
-				break;
-			
-			
-			if(piter == p){
-				// unlink from list,
-				// 
-				if(pprev == l_mempoolList){
-					// this (p) is list begin. so set next as head.
-					l_mempoolList = p->next;
-				}else{
-					// replace prevs next wuth our next.
-					pprev->next = p->next;
-				}
-				break;
-			}
-			
-			pprev = piter;			
-			piter = piter->next;
-		}
-
-		p->next = NULL;
-	LeaveSpinLock(&l_mempoolListLock);
-	
-	
-	// Get both locks.
-	EnterSpinLock(&p->segmentLock);
-	EnterSpinLock(&p->nodeLock);
-
-
-	if(p->num_nodes_free != p->num_nodes_total)
-		ShowWarning("Mempool [%s] Destroy - %u nodes are not freed properly!\n", p->name, (p->num_nodes_total - p->num_nodes_free) );
-	
-	// Free All Segments (this will also free all nodes)
-	// The segment pointer is the base pointer to the whole segment.
-	seg = p->segments;
-	while(1){
-		if(seg == NULL)
-			break;
-		
-		segnext = seg->next;
-	
-		// ..
-		if(p->ondealloc != NULL){
-			// walk over the segment, and call dealloc callback!
-			ptr = (char*)seg;
-			ptr += ALIGN_TO_16(sizeof(struct pool_segment));
-			for(i = 0; i < seg->num_nodes_total; i++){
-				niter = (struct node*)ptr;
-				ptr += sizeof(struct node);
-				ptr += p->elem_size;
+
+    // Unlink from global list.
+    EnterSpinLock(&l_mempoolListLock);
+    piter = l_mempoolList;
+    pprev = l_mempoolList;
+    while (1) {
+        if (piter == NULL)
+            break;
+
+
+        if (piter == p) {
+            // unlink from list,
+            //
+            if (pprev == l_mempoolList) {
+                // this (p) is list begin. so set next as head.
+                l_mempoolList = p->next;
+            } else {
+                // replace prevs next wuth our next.
+                pprev->next = p->next;
+            }
+            break;
+        }
+
+        pprev = piter;
+        piter = piter->next;
+    }
+
+    p->next = NULL;
+    LeaveSpinLock(&l_mempoolListLock);
+
+
+    // Get both locks.
+    EnterSpinLock(&p->segmentLock);
+    EnterSpinLock(&p->nodeLock);
+
+
+    if (p->num_nodes_free != p->num_nodes_total)
+        ShowWarning("Mempool [%s] Destroy - %u nodes are not freed properly!\n", p->name, (p->num_nodes_total - p->num_nodes_free));
+
+    // Free All Segments (this will also free all nodes)
+    // The segment pointer is the base pointer to the whole segment.
+    seg = p->segments;
+    while (1) {
+        if (seg == NULL)
+            break;
+
+        segnext = seg->next;
+
+        // ..
+        if (p->ondealloc != NULL) {
+            // walk over the segment, and call dealloc callback!
+            ptr = (char *)seg;
+            ptr += ALIGN_TO_16(sizeof(struct pool_segment));
+            for (i = 0; i < seg->num_nodes_total; i++) {
+                niter = (struct node *)ptr;
+                ptr += sizeof(struct node);
+                ptr += p->elem_size;
 #ifdef MEMPOOLASSERT
-				if(niter->magic != NODE_MAGIC){
-					ShowError("Mempool [%s] Destroy - walk over segment - node %p invalid magic!\n", p->name, niter);
-					continue;
-				}
+                if (niter->magic != NODE_MAGIC) {
+                    ShowError("Mempool [%s] Destroy - walk over segment - node %p invalid magic!\n", p->name, niter);
+                    continue;
+                }
 #endif
-				
-				p->ondealloc( NODE_TO_DATA(niter) );
-				
-				
-			}
-		}//endif: ondealloc callback?
-		
-		// simple ..
-		aFree(seg);
-		
-		seg = segnext;
-	}
-	
-	// Clear node ptr 
-	p->free_list = NULL;
-	InterlockedExchange64(&p->num_nodes_free, 0);	
-	InterlockedExchange64(&p->num_nodes_total, 0);
-	InterlockedExchange64(&p->num_segments, 0);
-	InterlockedExchange64(&p->num_bytes_total, 0);
-	
-	LeaveSpinLock(&p->nodeLock);
-	LeaveSpinLock(&p->segmentLock);
-
-	// Free pool itself :D
-	aFree(p->name);
-	aFree(p);
+
+                p->ondealloc(NODE_TO_DATA(niter));
+
+
+            }
+        }//endif: ondealloc callback?
+
+        // simple ..
+        aFree(seg);
+
+        seg = segnext;
+    }
+
+    // Clear node ptr
+    p->free_list = NULL;
+    InterlockedExchange64(&p->num_nodes_free, 0);
+    InterlockedExchange64(&p->num_nodes_total, 0);
+    InterlockedExchange64(&p->num_segments, 0);
+    InterlockedExchange64(&p->num_bytes_total, 0);
+
+    LeaveSpinLock(&p->nodeLock);
+    LeaveSpinLock(&p->segmentLock);
+
+    // Free pool itself :D
+    aFree(p->name);
+    aFree(p);
 
 }//end: mempool_destroy()
 
 
-void *mempool_node_get(mempool p){
-	struct node *node;
-	int64 num_used;
-	
-	if(p->num_nodes_free < p->elem_realloc_thresh)
-		racond_signal(l_async_cond);
-	
-	while(1){
-
-		EnterSpinLock(&p->nodeLock);
-		
-			node = p->free_list;
-			if(node != NULL)
-				p->free_list = node->next;
-		
-		LeaveSpinLock(&p->nodeLock);
-
-		if(node != NULL)
-			break;
-			
-		rathread_yield();
-	}
-
-	InterlockedDecrement64(&p->num_nodes_free);
-	
-	// Update peak value
-	num_used = (p->num_nodes_total - p->num_nodes_free);
-	if(num_used > p->peak_nodes_used){
-		InterlockedExchange64(&p->peak_nodes_used, num_used);
-	}
-	
+void *mempool_node_get(mempool p)
+{
+    struct node *node;
+    int64 num_used;
+
+    if (p->num_nodes_free < p->elem_realloc_thresh)
+        racond_signal(l_async_cond);
+
+    while (1) {
+
+        EnterSpinLock(&p->nodeLock);
+
+        node = p->free_list;
+        if (node != NULL)
+            p->free_list = node->next;
+
+        LeaveSpinLock(&p->nodeLock);
+
+        if (node != NULL)
+            break;
+
+        rathread_yield();
+    }
+
+    InterlockedDecrement64(&p->num_nodes_free);
+
+    // Update peak value
+    num_used = (p->num_nodes_total - p->num_nodes_free);
+    if (num_used > p->peak_nodes_used) {
+        InterlockedExchange64(&p->peak_nodes_used, num_used);
+    }
+
 #ifdef MEMPOOLASSERT
-	node->used = true;
+    node->used = true;
 #endif
 
-	return NODE_TO_DATA(node);
+    return NODE_TO_DATA(node);
 }//end: mempool_node_get()
 
 
-void mempool_node_put(mempool p, void *data){
-	struct node *node;
-	
-	node = DATA_TO_NODE(data);
+void mempool_node_put(mempool p, void *data)
+{
+    struct node *node;
+
+    node = DATA_TO_NODE(data);
 #ifdef MEMPOOLASSERT
-	if(node->magic != NODE_MAGIC){
-		ShowError("Mempool [%s] node_put failed, given address (%p) has invalid magic.\n", p->name,  data);
-		return; // lost, 
-	}
-
-	{
-		struct pool_segment *node_seg = node->segment;
-		if(node_seg->pool != p){
-			ShowError("Mempool [%s] node_put faild, given node (data address %p) doesnt belongs to this pool. ( Node Origin is [%s] )\n", p->name, data, node_seg->pool);
-			return;
-		}
-	}
-	
-	// reset used flag.
-	node->used = false;
+    if (node->magic != NODE_MAGIC) {
+        ShowError("Mempool [%s] node_put failed, given address (%p) has invalid magic.\n", p->name,  data);
+        return; // lost,
+    }
+
+    {
+        struct pool_segment *node_seg = node->segment;
+        if (node_seg->pool != p) {
+            ShowError("Mempool [%s] node_put faild, given node (data address %p) doesnt belongs to this pool. ( Node Origin is [%s] )\n", p->name, data, node_seg->pool);
+            return;
+        }
+    }
+
+    // reset used flag.
+    node->used = false;
 #endif
 
-	// 
-	EnterSpinLock(&p->nodeLock);
-		node->next = p->free_list;
-		p->free_list = node;
-	LeaveSpinLock(&p->nodeLock);
-	
-	InterlockedIncrement64(&p->num_nodes_free);
+    //
+    EnterSpinLock(&p->nodeLock);
+    node->next = p->free_list;
+    p->free_list = node;
+    LeaveSpinLock(&p->nodeLock);
+
+    InterlockedIncrement64(&p->num_nodes_free);
 
 }//end: mempool_node_put()
 
 
-mempool_stats mempool_get_stats(mempool pool){
-	mempool_stats stats;
-	
-	// initialize all with zeros
-	memset(&stats, 0x00, sizeof(mempool_stats));
-	
-	stats.num_nodes_total	= pool->num_nodes_total;
-	stats.num_nodes_free	= pool->num_nodes_free;
-	stats.num_nodes_used	= (stats.num_nodes_total - stats.num_nodes_free);
-	stats.num_segments		= pool->num_segments;
-	stats.num_realloc_events= pool->num_realloc_events;
-	stats.peak_nodes_used	= pool->peak_nodes_used;
-	stats.num_bytes_total	= pool->num_bytes_total;
-
-	// Pushing such a large block over the stack as return value isnt nice
-	// but lazy :) and should be okay in this case (Stats / Debug..)
-	// if you dont like it - feel free and refactor it.	
-	return stats;
+mempool_stats mempool_get_stats(mempool pool)
+{
+    mempool_stats stats;
+
+    // initialize all with zeros
+    memset(&stats, 0x00, sizeof(mempool_stats));
+
+    stats.num_nodes_total   = pool->num_nodes_total;
+    stats.num_nodes_free    = pool->num_nodes_free;
+    stats.num_nodes_used    = (stats.num_nodes_total - stats.num_nodes_free);
+    stats.num_segments      = pool->num_segments;
+    stats.num_realloc_events= pool->num_realloc_events;
+    stats.peak_nodes_used   = pool->peak_nodes_used;
+    stats.num_bytes_total   = pool->num_bytes_total;
+
+    // Pushing such a large block over the stack as return value isnt nice
+    // but lazy :) and should be okay in this case (Stats / Debug..)
+    // if you dont like it - feel free and refactor it.
+    return stats;
 }//end: mempool_get_stats()
 

+ 31 - 31
src/common/mempool.h

@@ -8,67 +8,67 @@ typedef struct mempool *mempool;
 typedef void (*memPoolOnNodeAllocationProc)(void *ptr);
 typedef void (*memPoolOnNodeDeallocationProc)(void *ptr);
 
-typedef struct mempool_stats{
-	int64	num_nodes_total;
-	int64	num_nodes_free;
-	int64	num_nodes_used;
-	
-	int64	num_segments;
-	int64	num_realloc_events;
-	
-	int64	peak_nodes_used;
-	
-	int64	num_bytes_total;
+typedef struct mempool_stats {
+    int64   num_nodes_total;
+    int64   num_nodes_free;
+    int64   num_nodes_used;
+
+    int64   num_segments;
+    int64   num_realloc_events;
+
+    int64   peak_nodes_used;
+
+    int64   num_bytes_total;
 } mempool_stats;
 
 
-// 
+//
 void mempool_init();
 void mempool_final();
 
 
-/** 
+/**
  * Creates a new Mempool
  *
  * @param name - Name of the pool (used for debug / error messages)
  * @param elem_size - size of each element
- * @param initial_count - preallocation count 
+ * @param initial_count - preallocation count
  * @param realloc_count - #no of nodes being allocated when pool is running empty.
  * @param onNodeAlloc - Node Allocation callback (see @note!)
  * @param onNodeDealloc - Node Deallocation callback (see @note!)
  *
  * @note:
- *	The onNode(De)alloc callbacks are only called once during segment allocation 
- *	(pool initialization / rallocation )
+ *  The onNode(De)alloc callbacks are only called once during segment allocation
+ *  (pool initialization / rallocation )
  *  you can use this callbacks for example to initlaize a mutex or somethingelse
- *	you definitly need during runtime
+ *  you definitly need during runtime
  *
  * @return not NULL
  */
 mempool mempool_create(const char *name,
-						uint64 elem_size,
-						uint64 initial_count,
-						uint64 realloc_count,
-						
-						memPoolOnNodeAllocationProc	onNodeAlloc,
-						memPoolOnNodeDeallocationProc onNodeDealloc);
-						
-						
+                       uint64 elem_size,
+                       uint64 initial_count,
+                       uint64 realloc_count,
+
+                       memPoolOnNodeAllocationProc onNodeAlloc,
+                       memPoolOnNodeDeallocationProc onNodeDealloc);
+
+
 /**
  * Destroys a Mempool
- * 
+ *
  * @param pool - the mempool to destroy
  *
  * @note:
- *	Everything gets deallocated, regardless if everything was freed properly!
- *	So you have to ensure that all references are cleared properly!
+ *  Everything gets deallocated, regardless if everything was freed properly!
+ *  So you have to ensure that all references are cleared properly!
  */
 void mempool_destroy(mempool pool);
 
 
 /**
  * Gets a new / empty node from the given mempool.
- * 
+ *
  * @param pool - the pool to get an empty node from.
  *
  * @return Address of empty Node
@@ -80,12 +80,12 @@ void *mempool_node_get(mempool pool);
  * Returns the given node to the given mempool
  *
  * @param pool - the pool to put the node, to
- * @param node - the node to return 
+ * @param node - the node to return
  */
 void mempool_node_put(mempool pool, void *node);
 
 
-/** 
+/**
  * Returns Statistics for the given mempool
  *
  * @param pool - the pool to get thats for

+ 464 - 465
src/common/mmo.h

@@ -1,8 +1,8 @@
 // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
 // For more information, see LICENCE in the main folder
 
-#ifndef	_MMO_H_
-#define	_MMO_H_
+#ifndef _MMO_H_
+#define _MMO_H_
 
 #include "cbasetypes.h"
 #include <time.h>
@@ -46,25 +46,25 @@
 // 20120307 - 2012-03-07aRagexeRE+ - 0x970
 
 #ifndef PACKETVER
-	#define PACKETVER 20120410
-	//#define PACKETVER 20111116
+#define PACKETVER 20120410
+//#define PACKETVER 20111116
 #endif
 
 //Remove/Comment this line to disable sc_data saving. [Skotlex]
-#define ENABLE_SC_SAVING 
+#define ENABLE_SC_SAVING
 //Remove/Comment this line to disable server-side hot-key saving support [Skotlex]
 //Note that newer clients no longer save hotkeys in the registry!
 #define HOTKEY_SAVING
 
 #if PACKETVER < 20090603
-        // (27 = 9 skills x 3 bars)               (0x02b9,191)
-        #define MAX_HOTKEYS 27
+// (27 = 9 skills x 3 bars)               (0x02b9,191)
+#define MAX_HOTKEYS 27
 #elif PACKETVER < 20090617
-        // (36 = 9 skills x 4 bars)               (0x07d9,254)
-        #define MAX_HOTKEYS 36
+// (36 = 9 skills x 4 bars)               (0x07d9,254)
+#define MAX_HOTKEYS 36
 #else
-        // (38 = 9 skills x 4 bars & 2 Quickslots)(0x07d9,268)
-        #define MAX_HOTKEYS 38
+// (38 = 9 skills x 4 bars & 2 Quickslots)(0x07d9,268)
+#define MAX_HOTKEYS 38
 #endif
 
 #define MAX_MAP_PER_SERVER 1500 // Increased to allow creation of Instance Maps
@@ -91,13 +91,13 @@
 #define MAX_STORAGE 600
 #define MAX_GUILD_STORAGE 600
 #define MAX_PARTY 12
-#define MAX_GUILD 16+10*6	// increased max guild members +6 per 1 extension levels [Lupus]
-#define MAX_GUILDPOSITION 20	// increased max guild positions to accomodate for all members [Valaris] (removed) [PoW]
+#define MAX_GUILD 16+10*6   // increased max guild members +6 per 1 extension levels [Lupus]
+#define MAX_GUILDPOSITION 20    // increased max guild positions to accomodate for all members [Valaris] (removed) [PoW]
 #define MAX_GUILDEXPULSION 32
 #define MAX_GUILDALLIANCE 16
-#define MAX_GUILDSKILL	15 // increased max guild skills because of new skills [Sara-chan]
+#define MAX_GUILDSKILL  15 // increased max guild skills because of new skills [Sara-chan]
 #define MAX_GUILDLEVEL 50
-#define MAX_GUARDIANS 8	//Local max per castle. [Skotlex]
+#define MAX_GUARDIANS 8 //Local max per castle. [Skotlex]
 #define MAX_QUEST_DB 2000 //Max quests that the server will load
 #define MAX_QUEST_OBJECTIVES 3 //Max quest objectives for a quest
 
@@ -140,7 +140,7 @@
 //Base Homun skill.
 #define HM_SKILLBASE 8001
 #define MAX_HOMUNSKILL 43
-#define MAX_HOMUNCULUS_CLASS	52	//[orn], Increased to 60 from 16 to allow new Homun-S.
+#define MAX_HOMUNCULUS_CLASS    52  //[orn], Increased to 60 from 16 to allow new Homun-S.
 #define HM_CLASS_BASE 6001
 #define HM_CLASS_MAX (HM_CLASS_BASE+MAX_HOMUNCULUS_CLASS-1)
 
@@ -163,20 +163,20 @@
 #define EL_CLASS_MAX (EL_CLASS_BASE+MAX_ELEMENTAL_CLASS-1)
 
 enum item_types {
-	IT_HEALING = 0,
-	IT_UNKNOWN, //1
-	IT_USABLE,  //2
-	IT_ETC,     //3
-	IT_WEAPON,  //4
-	IT_ARMOR,   //5
-	IT_CARD,    //6
-	IT_PETEGG,  //7
-	IT_PETARMOR,//8
-	IT_UNKNOWN2,//9
-	IT_AMMO,    //10
-	IT_DELAYCONSUME,//11
-	IT_CASH = 18,
-	IT_MAX 
+    IT_HEALING = 0,
+    IT_UNKNOWN, //1
+    IT_USABLE,  //2
+    IT_ETC,     //3
+    IT_WEAPON,  //4
+    IT_ARMOR,   //5
+    IT_CARD,    //6
+    IT_PETEGG,  //7
+    IT_PETARMOR,//8
+    IT_UNKNOWN2,//9
+    IT_AMMO,    //10
+    IT_DELAYCONSUME,//11
+    IT_CASH = 18,
+    IT_MAX
 };
 
 
@@ -184,556 +184,555 @@ enum item_types {
 typedef enum quest_state { Q_INACTIVE, Q_ACTIVE, Q_COMPLETE } quest_state;
 
 struct quest {
-	int quest_id;
-	unsigned int time;
-	int count[MAX_QUEST_OBJECTIVES];
-	quest_state state;
+    int quest_id;
+    unsigned int time;
+    int count[MAX_QUEST_OBJECTIVES];
+    quest_state state;
 };
 
 struct item {
-	int id;
-	short nameid;
-	short amount;
-	unsigned short equip; // location(s) where item is equipped (using enum equip_pos for bitmasking)
-	char identify;
-	char refine;
-	char attribute;
-	short card[MAX_SLOTS];
-	unsigned int expire_time;
-	char favorite;
+    int id;
+    short nameid;
+    short amount;
+    unsigned short equip; // location(s) where item is equipped (using enum equip_pos for bitmasking)
+    char identify;
+    char refine;
+    char attribute;
+    short card[MAX_SLOTS];
+    unsigned int expire_time;
+    char favorite;
 };
 
 struct point {
-	unsigned short map;
-	short x,y;
+    unsigned short map;
+    short x,y;
 };
 
-enum e_skill_flag
-{
-	SKILL_FLAG_PERMANENT,
-	SKILL_FLAG_TEMPORARY,
-	SKILL_FLAG_PLAGIARIZED,
-	SKILL_FLAG_REPLACED_LV_0, // temporary skill overshadowing permanent skill of level 'N - SKILL_FLAG_REPLACED_LV_0'
-	//...
+enum e_skill_flag {
+    SKILL_FLAG_PERMANENT,
+    SKILL_FLAG_TEMPORARY,
+    SKILL_FLAG_PLAGIARIZED,
+    SKILL_FLAG_REPLACED_LV_0, // temporary skill overshadowing permanent skill of level 'N - SKILL_FLAG_REPLACED_LV_0'
+    //...
 };
 
 struct s_skill {
-	unsigned short id;
-	unsigned char lv;
-	unsigned char flag; // see enum e_skill_flag
+    unsigned short id;
+    unsigned char lv;
+    unsigned char flag; // see enum e_skill_flag
 };
 
 struct global_reg {
-	char str[32];
-	char value[256];
+    char str[32];
+    char value[256];
 };
 
 //Holds array of global registries, used by the char server and converter.
 struct accreg {
-	int account_id, char_id;
-	int reg_num;
-	struct global_reg reg[MAX_REG_NUM];
+    int account_id, char_id;
+    int reg_num;
+    struct global_reg reg[MAX_REG_NUM];
 };
 
 //For saving status changes across sessions. [Skotlex]
 struct status_change_data {
-	unsigned short type; //SC_type
-	long val1, val2, val3, val4, tick; //Remaining duration.
+    unsigned short type; //SC_type
+    long val1, val2, val3, val4, tick; //Remaining duration.
 };
 
 struct storage_data {
-	int storage_amount;
-	struct item items[MAX_STORAGE];
+    int storage_amount;
+    struct item items[MAX_STORAGE];
 };
 
 struct guild_storage {
-	int dirty;
-	int guild_id;
-	short storage_status;
-	short storage_amount;
-	struct item items[MAX_GUILD_STORAGE];
+    int dirty;
+    int guild_id;
+    short storage_status;
+    short storage_amount;
+    struct item items[MAX_GUILD_STORAGE];
 };
 
 struct s_pet {
-	int account_id;
-	int char_id;
-	int pet_id;
-	short class_;
-	short level;
-	short egg_id;//pet egg id
-	short equip;//pet equip name_id
-	short intimate;//pet friendly
-	short hungry;//pet hungry
-	char name[NAME_LENGTH];
-	char rename_flag;
-	char incuvate;
-};
-
-struct s_homunculus {	//[orn]
-	char name[NAME_LENGTH];
-	int hom_id;
-	int char_id;
-	short class_;
-	short prev_class;
-	int hp,max_hp,sp,max_sp;
-	unsigned int intimacy;	//[orn]
-	short hunger;
-	struct s_skill hskill[MAX_HOMUNSKILL]; //albator
-	short skillpts;
-	short level;
-	unsigned int exp;
-	short rename_flag;
-	short vaporize; //albator
-	int str ;
-	int agi ;
-	int vit ;
-	int int_ ;
-	int dex ;
-	int luk ;
+    int account_id;
+    int char_id;
+    int pet_id;
+    short class_;
+    short level;
+    short egg_id;//pet egg id
+    short equip;//pet equip name_id
+    short intimate;//pet friendly
+    short hungry;//pet hungry
+    char name[NAME_LENGTH];
+    char rename_flag;
+    char incuvate;
+};
+
+struct s_homunculus {   //[orn]
+    char name[NAME_LENGTH];
+    int hom_id;
+    int char_id;
+    short class_;
+    short prev_class;
+    int hp,max_hp,sp,max_sp;
+    unsigned int intimacy;  //[orn]
+    short hunger;
+    struct s_skill hskill[MAX_HOMUNSKILL]; //albator
+    short skillpts;
+    short level;
+    unsigned int exp;
+    short rename_flag;
+    short vaporize; //albator
+    int str ;
+    int agi ;
+    int vit ;
+    int int_ ;
+    int dex ;
+    int luk ;
 };
 
 struct s_mercenary {
-	int mercenary_id;
-	int char_id;
-	short class_;
-	int hp, sp;
-	unsigned int kill_count;
-	unsigned int life_time;
+    int mercenary_id;
+    int char_id;
+    short class_;
+    int hp, sp;
+    unsigned int kill_count;
+    unsigned int life_time;
 };
 
 struct s_elemental {
-	int elemental_id;
-	int char_id;
-	short class_;
-	int mode;
-	int hp, sp, max_hp, max_sp, str, agi, vit, int_, dex, luk;
-	int life_time;
+    int elemental_id;
+    int char_id;
+    short class_;
+    int mode;
+    int hp, sp, max_hp, max_sp, str, agi, vit, int_, dex, luk;
+    int life_time;
 };
 
 struct s_friend {
-	int account_id;
-	int char_id;
-	char name[NAME_LENGTH];
+    int account_id;
+    int char_id;
+    char name[NAME_LENGTH];
 };
 
 #ifdef HOTKEY_SAVING
 struct hotkey {
-	unsigned int id;
-	unsigned short lv;
-	unsigned char type; // 0: item, 1: skill
+    unsigned int id;
+    unsigned short lv;
+    unsigned char type; // 0: item, 1: skill
 };
 #endif
 
 struct mmo_charstatus {
-	int char_id;
-	int account_id;
-	int partner_id;
-	int father;
-	int mother;
-	int child;
-
-	unsigned int base_exp,job_exp;
-	int zeny;
-
-	short class_;
-	unsigned int status_point,skill_point;
-	int hp,max_hp,sp,max_sp;
-	unsigned int option;
-	short manner;
-	unsigned char karma;
-	short hair,hair_color,clothes_color;
-	int party_id,guild_id,pet_id,hom_id,mer_id,ele_id;
-	int fame;
-
-	// Mercenary Guilds Rank
-	int arch_faith, arch_calls;
-	int spear_faith, spear_calls;
-	int sword_faith, sword_calls;
-
-	short weapon; // enum weapon_type
-	short shield; // view-id
-	short head_top,head_mid,head_bottom;
-	short robe;
-
-	char name[NAME_LENGTH];
-	unsigned int base_level,job_level;
-	short str,agi,vit,int_,dex,luk;
-	unsigned char slot,sex;
-
-	uint32 mapip;
-	uint16 mapport;
-
-	struct point last_point,save_point,memo_point[MAX_MEMOPOINTS];
-	struct item inventory[MAX_INVENTORY],cart[MAX_CART];
-	struct storage_data storage;
-	struct s_skill skill[MAX_SKILL];
-
-	struct s_friend friends[MAX_FRIENDS]; //New friend system [Skotlex]
+    int char_id;
+    int account_id;
+    int partner_id;
+    int father;
+    int mother;
+    int child;
+
+    unsigned int base_exp,job_exp;
+    int zeny;
+
+    short class_;
+    unsigned int status_point,skill_point;
+    int hp,max_hp,sp,max_sp;
+    unsigned int option;
+    short manner;
+    unsigned char karma;
+    short hair,hair_color,clothes_color;
+    int party_id,guild_id,pet_id,hom_id,mer_id,ele_id;
+    int fame;
+
+    // Mercenary Guilds Rank
+    int arch_faith, arch_calls;
+    int spear_faith, spear_calls;
+    int sword_faith, sword_calls;
+
+    short weapon; // enum weapon_type
+    short shield; // view-id
+    short head_top,head_mid,head_bottom;
+    short robe;
+
+    char name[NAME_LENGTH];
+    unsigned int base_level,job_level;
+    short str,agi,vit,int_,dex,luk;
+    unsigned char slot,sex;
+
+    uint32 mapip;
+    uint16 mapport;
+
+    struct point last_point,save_point,memo_point[MAX_MEMOPOINTS];
+    struct item inventory[MAX_INVENTORY],cart[MAX_CART];
+    struct storage_data storage;
+    struct s_skill skill[MAX_SKILL];
+
+    struct s_friend friends[MAX_FRIENDS]; //New friend system [Skotlex]
 #ifdef HOTKEY_SAVING
-	struct hotkey hotkeys[MAX_HOTKEYS];
+    struct hotkey hotkeys[MAX_HOTKEYS];
 #endif
-	bool show_equip;
-	short rename;
+    bool show_equip;
+    short rename;
 
-	time_t delete_date;
+    time_t delete_date;
 };
 
 typedef enum mail_status {
-	MAIL_NEW,
-	MAIL_UNREAD,
-	MAIL_READ,
+    MAIL_NEW,
+    MAIL_UNREAD,
+    MAIL_READ,
 } mail_status;
 
 struct mail_message {
-	int id;
-	int send_id;
-	char send_name[NAME_LENGTH];
-	int dest_id;
-	char dest_name[NAME_LENGTH];
-	char title[MAIL_TITLE_LENGTH];
-	char body[MAIL_BODY_LENGTH];
+    int id;
+    int send_id;
+    char send_name[NAME_LENGTH];
+    int dest_id;
+    char dest_name[NAME_LENGTH];
+    char title[MAIL_TITLE_LENGTH];
+    char body[MAIL_BODY_LENGTH];
 
-	mail_status status;
-	time_t timestamp; // marks when the message was sent
+    mail_status status;
+    time_t timestamp; // marks when the message was sent
 
-	int zeny;
-	struct item item;
+    int zeny;
+    struct item item;
 };
 
 struct mail_data {
-	short amount;
-	bool full;
-	short unchecked, unread;
-	struct mail_message msg[MAIL_MAX_INBOX];
+    short amount;
+    bool full;
+    short unchecked, unread;
+    struct mail_message msg[MAIL_MAX_INBOX];
 };
 
 struct auction_data {
-	unsigned int auction_id;
-	int seller_id;
-	char seller_name[NAME_LENGTH];
-	int buyer_id;
-	char buyer_name[NAME_LENGTH];
-	
-	struct item item;
-	// This data is required for searching, as itemdb is not read by char server
-	char item_name[ITEM_NAME_LENGTH];
-	short type;
-
-	unsigned short hours;
-	int price, buynow;
-	time_t timestamp; // auction's end time
-	int auction_end_timer;
+    unsigned int auction_id;
+    int seller_id;
+    char seller_name[NAME_LENGTH];
+    int buyer_id;
+    char buyer_name[NAME_LENGTH];
+
+    struct item item;
+    // This data is required for searching, as itemdb is not read by char server
+    char item_name[ITEM_NAME_LENGTH];
+    short type;
+
+    unsigned short hours;
+    int price, buynow;
+    time_t timestamp; // auction's end time
+    int auction_end_timer;
 };
 
 struct registry {
-	int global_num;
-	struct global_reg global[GLOBAL_REG_NUM];
-	int account_num;
-	struct global_reg account[ACCOUNT_REG_NUM];
-	int account2_num;
-	struct global_reg account2[ACCOUNT_REG2_NUM];
+    int global_num;
+    struct global_reg global[GLOBAL_REG_NUM];
+    int account_num;
+    struct global_reg account[ACCOUNT_REG_NUM];
+    int account2_num;
+    struct global_reg account2[ACCOUNT_REG2_NUM];
 };
 
 struct party_member {
-	int account_id;
-	int char_id;
-	char name[NAME_LENGTH];
-	unsigned short class_;
-	unsigned short map;
-	unsigned short lv;
-	unsigned leader : 1,
-	         online : 1;
+    int account_id;
+    int char_id;
+    char name[NAME_LENGTH];
+    unsigned short class_;
+    unsigned short map;
+    unsigned short lv;
+    unsigned leader : 1,
+             online : 1;
 };
 
 struct party {
-	int party_id;
-	char name[NAME_LENGTH];
-	unsigned char count; //Count of online characters.
-	unsigned exp : 1,
-				item : 2; //&1: Party-Share (round-robin), &2: pickup style: shared.
-	struct party_member member[MAX_PARTY];
+    int party_id;
+    char name[NAME_LENGTH];
+    unsigned char count; //Count of online characters.
+    unsigned exp : 1,
+             item : 2; //&1: Party-Share (round-robin), &2: pickup style: shared.
+    struct party_member member[MAX_PARTY];
 };
 
 struct map_session_data;
 struct guild_member {
-	int account_id, char_id;
-	short hair,hair_color,gender,class_,lv;
-	uint64 exp;
-	int exp_payper;
-	short online,position;
-	char name[NAME_LENGTH];
-	struct map_session_data *sd;
-	unsigned char modified;
+    int account_id, char_id;
+    short hair,hair_color,gender,class_,lv;
+    uint64 exp;
+    int exp_payper;
+    short online,position;
+    char name[NAME_LENGTH];
+    struct map_session_data *sd;
+    unsigned char modified;
 };
 
 struct guild_position {
-	char name[NAME_LENGTH];
-	int mode;
-	int exp_mode;
-	unsigned char modified;
+    char name[NAME_LENGTH];
+    int mode;
+    int exp_mode;
+    unsigned char modified;
 };
 
 struct guild_alliance {
-	int opposition;
-	int guild_id;
-	char name[NAME_LENGTH];
+    int opposition;
+    int guild_id;
+    char name[NAME_LENGTH];
 };
 
 struct guild_expulsion {
-	char name[NAME_LENGTH];
-	char mes[40];
-	int account_id;
+    char name[NAME_LENGTH];
+    char mes[40];
+    int account_id;
 };
 
 struct guild_skill {
-	int id,lv;
+    int id,lv;
 };
 
 struct guild {
-	int guild_id;
-	short guild_lv, connect_member, max_member, average_lv;
-	uint64 exp;
-	unsigned int next_exp;
-	int skill_point;
-	char name[NAME_LENGTH],master[NAME_LENGTH];
-	struct guild_member member[MAX_GUILD];
-	struct guild_position position[MAX_GUILDPOSITION];
-	char mes1[MAX_GUILDMES1],mes2[MAX_GUILDMES2];
-	int emblem_len,emblem_id;
-	char emblem_data[2048];
-	struct guild_alliance alliance[MAX_GUILDALLIANCE];
-	struct guild_expulsion expulsion[MAX_GUILDEXPULSION];
-	struct guild_skill skill[MAX_GUILDSKILL];
-
-	unsigned short save_flag; // for TXT saving
+    int guild_id;
+    short guild_lv, connect_member, max_member, average_lv;
+    uint64 exp;
+    unsigned int next_exp;
+    int skill_point;
+    char name[NAME_LENGTH],master[NAME_LENGTH];
+    struct guild_member member[MAX_GUILD];
+    struct guild_position position[MAX_GUILDPOSITION];
+    char mes1[MAX_GUILDMES1],mes2[MAX_GUILDMES2];
+    int emblem_len,emblem_id;
+    char emblem_data[2048];
+    struct guild_alliance alliance[MAX_GUILDALLIANCE];
+    struct guild_expulsion expulsion[MAX_GUILDEXPULSION];
+    struct guild_skill skill[MAX_GUILDSKILL];
+
+    unsigned short save_flag; // for TXT saving
 };
 
 struct guild_castle {
-	int castle_id;
-	int mapindex;
-	char castle_name[NAME_LENGTH];
-	char castle_event[NAME_LENGTH];
-	int guild_id;
-	int economy;
-	int defense;
-	int triggerE;
-	int triggerD;
-	int nextTime;
-	int payTime;
-	int createTime;
-	int visibleC;
-	struct {
-		unsigned visible : 1;
-		int id; // object id
-	} guardian[MAX_GUARDIANS];
-	int* temp_guardians; // ids of temporary guardians (mobs)
-	int temp_guardians_max;
+    int castle_id;
+    int mapindex;
+    char castle_name[NAME_LENGTH];
+    char castle_event[NAME_LENGTH];
+    int guild_id;
+    int economy;
+    int defense;
+    int triggerE;
+    int triggerD;
+    int nextTime;
+    int payTime;
+    int createTime;
+    int visibleC;
+    struct {
+        unsigned visible : 1;
+        int id; // object id
+    } guardian[MAX_GUARDIANS];
+    int *temp_guardians; // ids of temporary guardians (mobs)
+    int temp_guardians_max;
 };
 
 struct fame_list {
-	int id;
-	int fame;
-	char name[NAME_LENGTH];
+    int id;
+    int fame;
+    char name[NAME_LENGTH];
 };
 
-enum { //Change Guild Infos 
-	GBI_EXP	=1,		// Guild Experience (EXP)
-	GBI_GUILDLV,		// Guild level
-	GBI_SKILLPOINT,		// Guild skillpoints
-	GBI_SKILLLV,		// Guild skilllv ?? seem unused
+enum { //Change Guild Infos
+    GBI_EXP =1,     // Guild Experience (EXP)
+    GBI_GUILDLV,        // Guild level
+    GBI_SKILLPOINT,     // Guild skillpoints
+    GBI_SKILLLV,        // Guild skilllv ?? seem unused
 };
 
 enum { //Change Member Infos
-	GMI_POSITION	=0,		
-	GMI_EXP,
-	GMI_HAIR,
-	GMI_HAIR_COLOR,
-	GMI_GENDER,
-	GMI_CLASS,
-	GMI_LEVEL,
+    GMI_POSITION    =0,
+    GMI_EXP,
+    GMI_HAIR,
+    GMI_HAIR_COLOR,
+    GMI_GENDER,
+    GMI_CLASS,
+    GMI_LEVEL,
 };
 
 enum {
-	GD_SKILLBASE=10000,
-	GD_APPROVAL=10000,
-	GD_KAFRACONTRACT=10001,
-	GD_GUARDRESEARCH=10002,
-	GD_GUARDUP=10003,
-	GD_EXTENSION=10004,
-	GD_GLORYGUILD=10005,
-	GD_LEADERSHIP=10006,
-	GD_GLORYWOUNDS=10007,
-	GD_SOULCOLD=10008,
-	GD_HAWKEYES=10009,
-	GD_BATTLEORDER=10010,
-	GD_REGENERATION=10011,
-	GD_RESTORE=10012,
-	GD_EMERGENCYCALL=10013,
-	GD_DEVELOPMENT=10014,
-	GD_MAX,
+    GD_SKILLBASE=10000,
+    GD_APPROVAL=10000,
+    GD_KAFRACONTRACT=10001,
+    GD_GUARDRESEARCH=10002,
+    GD_GUARDUP=10003,
+    GD_EXTENSION=10004,
+    GD_GLORYGUILD=10005,
+    GD_LEADERSHIP=10006,
+    GD_GLORYWOUNDS=10007,
+    GD_SOULCOLD=10008,
+    GD_HAWKEYES=10009,
+    GD_BATTLEORDER=10010,
+    GD_REGENERATION=10011,
+    GD_RESTORE=10012,
+    GD_EMERGENCYCALL=10013,
+    GD_DEVELOPMENT=10014,
+    GD_MAX,
 };
 
 
 //These mark the ID of the jobs, as expected by the client. [Skotlex]
 enum {
-	JOB_NOVICE,
-	JOB_SWORDMAN,
-	JOB_MAGE,
-	JOB_ARCHER,
-	JOB_ACOLYTE,
-	JOB_MERCHANT,
-	JOB_THIEF,
-	JOB_KNIGHT,
-	JOB_PRIEST,
-	JOB_WIZARD,
-	JOB_BLACKSMITH,
-	JOB_HUNTER,
-	JOB_ASSASSIN,
-	JOB_KNIGHT2,
-	JOB_CRUSADER,
-	JOB_MONK,
-	JOB_SAGE,
-	JOB_ROGUE,
-	JOB_ALCHEMIST,
-	JOB_BARD,
-	JOB_DANCER,
-	JOB_CRUSADER2,
-	JOB_WEDDING,
-	JOB_SUPER_NOVICE,
-	JOB_GUNSLINGER,
-	JOB_NINJA,
-	JOB_XMAS,
-	JOB_SUMMER,
-	JOB_MAX_BASIC,
-
-	JOB_NOVICE_HIGH = 4001,
-	JOB_SWORDMAN_HIGH,
-	JOB_MAGE_HIGH,
-	JOB_ARCHER_HIGH,
-	JOB_ACOLYTE_HIGH,
-	JOB_MERCHANT_HIGH,
-	JOB_THIEF_HIGH,
-	JOB_LORD_KNIGHT,
-	JOB_HIGH_PRIEST,
-	JOB_HIGH_WIZARD,
-	JOB_WHITESMITH,
-	JOB_SNIPER,
-	JOB_ASSASSIN_CROSS,
-	JOB_LORD_KNIGHT2,
-	JOB_PALADIN,
-	JOB_CHAMPION,
-	JOB_PROFESSOR,
-	JOB_STALKER,
-	JOB_CREATOR,
-	JOB_CLOWN,
-	JOB_GYPSY,
-	JOB_PALADIN2,
-
-	JOB_BABY,
-	JOB_BABY_SWORDMAN,
-	JOB_BABY_MAGE,
-	JOB_BABY_ARCHER,
-	JOB_BABY_ACOLYTE,
-	JOB_BABY_MERCHANT,
-	JOB_BABY_THIEF,
-	JOB_BABY_KNIGHT,
-	JOB_BABY_PRIEST,
-	JOB_BABY_WIZARD,
-	JOB_BABY_BLACKSMITH,
-	JOB_BABY_HUNTER,
-	JOB_BABY_ASSASSIN,
-	JOB_BABY_KNIGHT2,
-	JOB_BABY_CRUSADER,
-	JOB_BABY_MONK,
-	JOB_BABY_SAGE,
-	JOB_BABY_ROGUE,
-	JOB_BABY_ALCHEMIST,
-	JOB_BABY_BARD,
-	JOB_BABY_DANCER,
-	JOB_BABY_CRUSADER2,
-	JOB_SUPER_BABY,
-
-	JOB_TAEKWON,
-	JOB_STAR_GLADIATOR,
-	JOB_STAR_GLADIATOR2,
-	JOB_SOUL_LINKER,
-
-	JOB_GANGSI,
-	JOB_DEATH_KNIGHT,
-	JOB_DARK_COLLECTOR,
-
-	JOB_RUNE_KNIGHT = 4054,
-	JOB_WARLOCK,
-	JOB_RANGER,
-	JOB_ARCH_BISHOP,
-	JOB_MECHANIC,
-	JOB_GUILLOTINE_CROSS,
-
-	JOB_RUNE_KNIGHT_T,
-	JOB_WARLOCK_T,
-	JOB_RANGER_T,
-	JOB_ARCH_BISHOP_T,
-	JOB_MECHANIC_T,
-	JOB_GUILLOTINE_CROSS_T,
-
-	JOB_ROYAL_GUARD,
-	JOB_SORCERER,
-	JOB_MINSTREL,
-	JOB_WANDERER,
-	JOB_SURA,
-	JOB_GENETIC,
-	JOB_SHADOW_CHASER,
-
-	JOB_ROYAL_GUARD_T,
-	JOB_SORCERER_T,
-	JOB_MINSTREL_T,
-	JOB_WANDERER_T,
-	JOB_SURA_T,
-	JOB_GENETIC_T,
-	JOB_SHADOW_CHASER_T,
-
-	JOB_RUNE_KNIGHT2,
-	JOB_RUNE_KNIGHT_T2,
-	JOB_ROYAL_GUARD2,
-	JOB_ROYAL_GUARD_T2,
-	JOB_RANGER2,
-	JOB_RANGER_T2,
-	JOB_MECHANIC2,
-	JOB_MECHANIC_T2,
-
-	JOB_BABY_RUNE = 4096,
-	JOB_BABY_WARLOCK,
-	JOB_BABY_RANGER,
-	JOB_BABY_BISHOP,
-	JOB_BABY_MECHANIC,
-	JOB_BABY_CROSS,
-
-	JOB_BABY_GUARD,
-	JOB_BABY_SORCERER,
-	JOB_BABY_MINSTREL,
-	JOB_BABY_WANDERER,
-	JOB_BABY_SURA,
-	JOB_BABY_GENETIC,
-	JOB_BABY_CHASER,
-
-	JOB_BABY_RUNE2,
-	JOB_BABY_GUARD2,
-	JOB_BABY_RANGER2,
-	JOB_BABY_MECHANIC2,
-
-	JOB_SUPER_NOVICE_E = 4190,
-	JOB_SUPER_BABY_E,
-
-	JOB_KAGEROU = 4211,
-	JOB_OBORO,
-
-	JOB_MAX,
+    JOB_NOVICE,
+    JOB_SWORDMAN,
+    JOB_MAGE,
+    JOB_ARCHER,
+    JOB_ACOLYTE,
+    JOB_MERCHANT,
+    JOB_THIEF,
+    JOB_KNIGHT,
+    JOB_PRIEST,
+    JOB_WIZARD,
+    JOB_BLACKSMITH,
+    JOB_HUNTER,
+    JOB_ASSASSIN,
+    JOB_KNIGHT2,
+    JOB_CRUSADER,
+    JOB_MONK,
+    JOB_SAGE,
+    JOB_ROGUE,
+    JOB_ALCHEMIST,
+    JOB_BARD,
+    JOB_DANCER,
+    JOB_CRUSADER2,
+    JOB_WEDDING,
+    JOB_SUPER_NOVICE,
+    JOB_GUNSLINGER,
+    JOB_NINJA,
+    JOB_XMAS,
+    JOB_SUMMER,
+    JOB_MAX_BASIC,
+
+    JOB_NOVICE_HIGH = 4001,
+    JOB_SWORDMAN_HIGH,
+    JOB_MAGE_HIGH,
+    JOB_ARCHER_HIGH,
+    JOB_ACOLYTE_HIGH,
+    JOB_MERCHANT_HIGH,
+    JOB_THIEF_HIGH,
+    JOB_LORD_KNIGHT,
+    JOB_HIGH_PRIEST,
+    JOB_HIGH_WIZARD,
+    JOB_WHITESMITH,
+    JOB_SNIPER,
+    JOB_ASSASSIN_CROSS,
+    JOB_LORD_KNIGHT2,
+    JOB_PALADIN,
+    JOB_CHAMPION,
+    JOB_PROFESSOR,
+    JOB_STALKER,
+    JOB_CREATOR,
+    JOB_CLOWN,
+    JOB_GYPSY,
+    JOB_PALADIN2,
+
+    JOB_BABY,
+    JOB_BABY_SWORDMAN,
+    JOB_BABY_MAGE,
+    JOB_BABY_ARCHER,
+    JOB_BABY_ACOLYTE,
+    JOB_BABY_MERCHANT,
+    JOB_BABY_THIEF,
+    JOB_BABY_KNIGHT,
+    JOB_BABY_PRIEST,
+    JOB_BABY_WIZARD,
+    JOB_BABY_BLACKSMITH,
+    JOB_BABY_HUNTER,
+    JOB_BABY_ASSASSIN,
+    JOB_BABY_KNIGHT2,
+    JOB_BABY_CRUSADER,
+    JOB_BABY_MONK,
+    JOB_BABY_SAGE,
+    JOB_BABY_ROGUE,
+    JOB_BABY_ALCHEMIST,
+    JOB_BABY_BARD,
+    JOB_BABY_DANCER,
+    JOB_BABY_CRUSADER2,
+    JOB_SUPER_BABY,
+
+    JOB_TAEKWON,
+    JOB_STAR_GLADIATOR,
+    JOB_STAR_GLADIATOR2,
+    JOB_SOUL_LINKER,
+
+    JOB_GANGSI,
+    JOB_DEATH_KNIGHT,
+    JOB_DARK_COLLECTOR,
+
+    JOB_RUNE_KNIGHT = 4054,
+    JOB_WARLOCK,
+    JOB_RANGER,
+    JOB_ARCH_BISHOP,
+    JOB_MECHANIC,
+    JOB_GUILLOTINE_CROSS,
+
+    JOB_RUNE_KNIGHT_T,
+    JOB_WARLOCK_T,
+    JOB_RANGER_T,
+    JOB_ARCH_BISHOP_T,
+    JOB_MECHANIC_T,
+    JOB_GUILLOTINE_CROSS_T,
+
+    JOB_ROYAL_GUARD,
+    JOB_SORCERER,
+    JOB_MINSTREL,
+    JOB_WANDERER,
+    JOB_SURA,
+    JOB_GENETIC,
+    JOB_SHADOW_CHASER,
+
+    JOB_ROYAL_GUARD_T,
+    JOB_SORCERER_T,
+    JOB_MINSTREL_T,
+    JOB_WANDERER_T,
+    JOB_SURA_T,
+    JOB_GENETIC_T,
+    JOB_SHADOW_CHASER_T,
+
+    JOB_RUNE_KNIGHT2,
+    JOB_RUNE_KNIGHT_T2,
+    JOB_ROYAL_GUARD2,
+    JOB_ROYAL_GUARD_T2,
+    JOB_RANGER2,
+    JOB_RANGER_T2,
+    JOB_MECHANIC2,
+    JOB_MECHANIC_T2,
+
+    JOB_BABY_RUNE = 4096,
+    JOB_BABY_WARLOCK,
+    JOB_BABY_RANGER,
+    JOB_BABY_BISHOP,
+    JOB_BABY_MECHANIC,
+    JOB_BABY_CROSS,
+
+    JOB_BABY_GUARD,
+    JOB_BABY_SORCERER,
+    JOB_BABY_MINSTREL,
+    JOB_BABY_WANDERER,
+    JOB_BABY_SURA,
+    JOB_BABY_GENETIC,
+    JOB_BABY_CHASER,
+
+    JOB_BABY_RUNE2,
+    JOB_BABY_GUARD2,
+    JOB_BABY_RANGER2,
+    JOB_BABY_MECHANIC2,
+
+    JOB_SUPER_NOVICE_E = 4190,
+    JOB_SUPER_BABY_E,
+
+    JOB_KAGEROU = 4211,
+    JOB_OBORO,
+
+    JOB_MAX,
 };
 
 enum {
-	SEX_FEMALE = 0,
-	SEX_MALE,
-	SEX_SERVER
+    SEX_FEMALE = 0,
+    SEX_MALE,
+    SEX_SERVER
 };
 
 // sanity checks...

+ 133 - 123
src/common/mutex.c

@@ -15,26 +15,26 @@
 #include "../common/timer.h"
 #include "../common/mutex.h"
 
-struct ramutex{
+struct ramutex {
 #ifdef WIN32
-	CRITICAL_SECTION hMutex;
+    CRITICAL_SECTION hMutex;
 #else
-	pthread_mutex_t hMutex;
+    pthread_mutex_t hMutex;
 #endif
 };
 
 
-struct racond{
+struct racond {
 #ifdef WIN32
-	HANDLE events[2];
-	ra_align(8) volatile LONG nWaiters;
-	CRITICAL_SECTION waiters_lock;
+    HANDLE events[2];
+    ra_align(8) volatile LONG nWaiters;
+    CRITICAL_SECTION waiters_lock;
 
 #define EVENT_COND_SIGNAL 0
 #define EVENT_COND_BROADCAST 1
 
 #else
-	pthread_cond_t hCond;
+    pthread_cond_t hCond;
 #endif
 };
 
@@ -46,68 +46,73 @@ struct racond{
 //
 
 
-ramutex ramutex_create(){
-	struct ramutex *m;
-	
-	m = (struct ramutex*)aMalloc( sizeof(struct ramutex) );
-	if(m == NULL){
-		ShowFatalError("ramutex_create: OOM while allocating %u bytes.\n", sizeof(struct ramutex));
-		return NULL;
-	}
-	
+ramutex ramutex_create()
+{
+    struct ramutex *m;
+
+    m = (struct ramutex *)aMalloc(sizeof(struct ramutex));
+    if (m == NULL) {
+        ShowFatalError("ramutex_create: OOM while allocating %u bytes.\n", sizeof(struct ramutex));
+        return NULL;
+    }
+
 #ifdef WIN32
-	InitializeCriticalSection(&m->hMutex);
+    InitializeCriticalSection(&m->hMutex);
 #else
-	pthread_mutex_init(&m->hMutex, NULL);
+    pthread_mutex_init(&m->hMutex, NULL);
 #endif
-		
-	return m;
+
+    return m;
 }//end: ramutex_create()
 
 
-void ramutex_destroy( ramutex m ){
+void ramutex_destroy(ramutex m)
+{
 
 #ifdef WIN32
-	DeleteCriticalSection(&m->hMutex);
+    DeleteCriticalSection(&m->hMutex);
 #else
-	pthread_mutex_destroy(&m->hMutex);
+    pthread_mutex_destroy(&m->hMutex);
 #endif
 
-	aFree(m);
+    aFree(m);
 
 }//end: ramutex_destroy()
 
 
-void ramutex_lock( ramutex m ){
+void ramutex_lock(ramutex m)
+{
 
 #ifdef WIN32
-	EnterCriticalSection(&m->hMutex);
+    EnterCriticalSection(&m->hMutex);
 #else
-	pthread_mutex_lock(&m->hMutex);
+    pthread_mutex_lock(&m->hMutex);
 #endif
 }//end: ramutex_lock
 
 
-bool ramutex_trylock( ramutex m ){
+bool ramutex_trylock(ramutex m)
+{
 #ifdef WIN32
-	if(TryEnterCriticalSection(&m->hMutex) == TRUE)
-		return true;
+    if (TryEnterCriticalSection(&m->hMutex) == TRUE)
+        return true;
 
-	return false;
+    return false;
 #else
-	if(pthread_mutex_trylock(&m->hMutex) == 0)
-		return true;
-	
-	return false;
+    if (pthread_mutex_trylock(&m->hMutex) == 0)
+        return true;
+
+    return false;
 #endif
 }//end: ramutex_trylock()
 
 
-void ramutex_unlock( ramutex m ){
+void ramutex_unlock(ramutex m)
+{
 #ifdef WIN32
-	LeaveCriticalSection(&m->hMutex);
+    LeaveCriticalSection(&m->hMutex);
 #else
-	pthread_mutex_unlock(&m->hMutex);
+    pthread_mutex_unlock(&m->hMutex);
 #endif
 
 }//end: ramutex_unlock()
@@ -116,131 +121,136 @@ void ramutex_unlock( ramutex m ){
 
 ///////////////
 // Condition Variables
-// 
+//
 // Implementation:
 //
 
-racond racond_create(){
-	struct racond *c;
-	
-	c = (struct racond*)aMalloc( sizeof(struct racond) );
-	if(c == NULL){
-		ShowFatalError("racond_create: OOM while allocating %u bytes\n", sizeof(struct racond));
-		return NULL;
-	}
+racond racond_create()
+{
+    struct racond *c;
+
+    c = (struct racond *)aMalloc(sizeof(struct racond));
+    if (c == NULL) {
+        ShowFatalError("racond_create: OOM while allocating %u bytes\n", sizeof(struct racond));
+        return NULL;
+    }
 
 #ifdef WIN32
-	c->nWaiters = 0;
-	c->events[ EVENT_COND_SIGNAL ]		= CreateEvent( NULL,  FALSE,  FALSE,  NULL );
-	c->events[ EVENT_COND_BROADCAST ]	= CreateEvent( NULL,  TRUE,   FALSE,  NULL );
-	InitializeCriticalSection( &c->waiters_lock );
+    c->nWaiters = 0;
+    c->events[ EVENT_COND_SIGNAL ]      = CreateEvent(NULL,  FALSE,  FALSE,  NULL);
+    c->events[ EVENT_COND_BROADCAST ]   = CreateEvent(NULL,  TRUE,   FALSE,  NULL);
+    InitializeCriticalSection(&c->waiters_lock);
 #else
-	pthread_cond_init(&c->hCond, NULL);
+    pthread_cond_init(&c->hCond, NULL);
 #endif
-	
-	return c;
+
+    return c;
 }//end: racond_create()
 
 
-void racond_destroy( racond c ){
+void racond_destroy(racond c)
+{
 #ifdef WIN32
-	CloseHandle( c->events[ EVENT_COND_SIGNAL ] );
-	CloseHandle( c->events[ EVENT_COND_BROADCAST ] );
-	DeleteCriticalSection( &c->waiters_lock );
+    CloseHandle(c->events[ EVENT_COND_SIGNAL ]);
+    CloseHandle(c->events[ EVENT_COND_BROADCAST ]);
+    DeleteCriticalSection(&c->waiters_lock);
 #else
-	pthread_cond_destroy(&c->hCond);
+    pthread_cond_destroy(&c->hCond);
 #endif
 
-	aFree(c);
+    aFree(c);
 }//end: racond_destroy()
 
 
-void racond_wait( racond c,  ramutex m,  sysint timeout_ticks){
+void racond_wait(racond c,  ramutex m,  sysint timeout_ticks)
+{
 #ifdef WIN32
-	register DWORD ms;
-	int result;
-	bool is_last = false;
+    register DWORD ms;
+    int result;
+    bool is_last = false;
 
 
-	EnterCriticalSection(&c->waiters_lock);
-	c->nWaiters++;
-	LeaveCriticalSection(&c->waiters_lock);
+    EnterCriticalSection(&c->waiters_lock);
+    c->nWaiters++;
+    LeaveCriticalSection(&c->waiters_lock);
 
-	if(timeout_ticks < 0)
-		ms = INFINITE;
-	else
-		ms = (timeout_ticks > MAXDWORD) ? (MAXDWORD - 1) : (DWORD)timeout_ticks;
-		
-	
-	// we can release the mutex (m) here, cause win's
-	// manual reset events maintain state when used with
-	// SetEvent()
-	ramutex_unlock(m);
+    if (timeout_ticks < 0)
+        ms = INFINITE;
+    else
+        ms = (timeout_ticks > MAXDWORD) ? (MAXDWORD - 1) : (DWORD)timeout_ticks;
 
-	result = WaitForMultipleObjects(2, c->events, FALSE, ms);
-	
-	
-	EnterCriticalSection(&c->waiters_lock);
-	c->nWaiters--;
-	if( (result == WAIT_OBJECT_0 + EVENT_COND_BROADCAST) && (c->nWaiters == 0) )
-		is_last = true; // Broadcast called!
-	LeaveCriticalSection(&c->waiters_lock);
 
-	
+    // we can release the mutex (m) here, cause win's
+    // manual reset events maintain state when used with
+    // SetEvent()
+    ramutex_unlock(m);
 
-	// we are the last waiter that has to be notified, or to stop waiting
-	// so we have to do a manual reset
-	if(is_last == true)
-		ResetEvent( c->events[EVENT_COND_BROADCAST] );
+    result = WaitForMultipleObjects(2, c->events, FALSE, ms);
 
 
-	ramutex_lock(m);
+    EnterCriticalSection(&c->waiters_lock);
+    c->nWaiters--;
+    if ((result == WAIT_OBJECT_0 + EVENT_COND_BROADCAST) && (c->nWaiters == 0))
+        is_last = true; // Broadcast called!
+    LeaveCriticalSection(&c->waiters_lock);
+
+
+
+    // we are the last waiter that has to be notified, or to stop waiting
+    // so we have to do a manual reset
+    if (is_last == true)
+        ResetEvent(c->events[EVENT_COND_BROADCAST]);
+
+
+    ramutex_lock(m);
 
 #else
-	if(timeout_ticks < 0){
-		pthread_cond_wait( &c->hCond,  &m->hMutex );
-	}else{
-		struct timespec wtime;
-		int64 exact_timeout = gettick() + timeout_ticks;
-	
-		wtime.tv_sec = exact_timeout/1000;
-		wtime.tv_nsec = (exact_timeout%1000)*1000000;
-		
-		pthread_cond_timedwait( &c->hCond,  &m->hMutex,  &wtime);
-	}
+    if (timeout_ticks < 0) {
+        pthread_cond_wait(&c->hCond,  &m->hMutex);
+    } else {
+        struct timespec wtime;
+        int64 exact_timeout = gettick() + timeout_ticks;
+
+        wtime.tv_sec = exact_timeout/1000;
+        wtime.tv_nsec = (exact_timeout%1000)*1000000;
+
+        pthread_cond_timedwait(&c->hCond,  &m->hMutex,  &wtime);
+    }
 
 #endif
 }//end: racond_wait()
 
 
-void racond_signal( racond c ){
+void racond_signal(racond c)
+{
 #ifdef WIN32
-//	bool has_waiters = false;
-//	EnterCriticalSection(&c->waiters_lock);
-//	if(c->nWaiters > 0)
-//			has_waiters = true;
-//	LeaveCriticalSection(&c->waiters_lock);
-	
-//	if(has_waiters == true)
-		SetEvent( c->events[ EVENT_COND_SIGNAL ] );
+    //  bool has_waiters = false;
+    //  EnterCriticalSection(&c->waiters_lock);
+    //  if(c->nWaiters > 0)
+    //          has_waiters = true;
+    //  LeaveCriticalSection(&c->waiters_lock);
+
+    //  if(has_waiters == true)
+    SetEvent(c->events[ EVENT_COND_SIGNAL ]);
 #else
-	pthread_cond_signal(&c->hCond);
+    pthread_cond_signal(&c->hCond);
 #endif
 }//end: racond_signal()
 
 
-void racond_broadcast( racond c ){
+void racond_broadcast(racond c)
+{
 #ifdef WIN32
-//	bool has_waiters = false;
-//	EnterCriticalSection(&c->waiters_lock);
-//	if(c->nWaiters > 0)
-//			has_waiters = true;
-//	LeaveCriticalSection(&c->waiters_lock);
-	
-//	if(has_waiters == true)
-		SetEvent( c->events[ EVENT_COND_BROADCAST ] );
+    //  bool has_waiters = false;
+    //  EnterCriticalSection(&c->waiters_lock);
+    //  if(c->nWaiters > 0)
+    //          has_waiters = true;
+    //  LeaveCriticalSection(&c->waiters_lock);
+
+    //  if(has_waiters == true)
+    SetEvent(c->events[ EVENT_COND_BROADCAST ]);
 #else
-	pthread_cond_broadcast(&c->hCond);
+    pthread_cond_broadcast(&c->hCond);
 #endif
 }//end: racond_broadcast()
 

+ 25 - 25
src/common/mutex.h

@@ -1,5 +1,5 @@
 // Copyright (c) rAthena Project (www.rathena.org) - Licensed under GNU GPL
-// For more information, see LICENCE in the main folder  
+// For more information, see LICENCE in the main folder
 
 #ifndef _rA_MUTEX_H_
 #define _rA_MUTEX_H_
@@ -9,67 +9,67 @@ typedef struct ramutex *ramutex; // Mutex
 typedef struct racond *racond; // Condition Var
 
 /**
- * Creates a Mutex 
+ * Creates a Mutex
  *
  * @return not NULL
  */
 ramutex ramutex_create();
 
-/** 
+/**
  * Destroys a Mutex
- * 
+ *
  * @param m - the mutex to destroy
  */
-void ramutex_destroy( ramutex m );
+void ramutex_destroy(ramutex m);
 
-/** 
+/**
  * Gets a lock
  *
  * @param m - the mutex to lock
  */
-void ramutex_lock( ramutex m);
+void ramutex_lock(ramutex m);
 
-/** 
+/**
  * Trys to get the Lock
- * 
+ *
  * @param m - the mutex try to lock
- * 
+ *
  * @return boolean (true = got the lock)
  */
-bool ramutex_trylock( ramutex m );
+bool ramutex_trylock(ramutex m);
 
-/** 
+/**
  * Unlocks a mutex
  *
  * @param m - the mutex to unlock
  */
-void ramutex_unlock( ramutex m);
+void ramutex_unlock(ramutex m);
 
 
-/** 
+/**
  * Creates a Condition variable
  *
  * @return not NULL
  */
 racond racond_create();
 
-/** 
+/**
  * Destroy a Condition variable
  *
  * @param c - the condition varaible to destroy
  */
-void racond_destroy( racond c );
+void racond_destroy(racond c);
 
 /**
  * Waits Until state is signalled
- * 
- * @param c - the condition var to wait for signalled state 
+ *
+ * @param c - the condition var to wait for signalled state
  * @param m - the mutex used for syncronization
  * @param timeout_ticks - timeout in ticks ( -1 = INFINITE )
  */
-void racond_wait( racond c,  ramutex m,  sysint timeout_ticks);
+void racond_wait(racond c,  ramutex m,  sysint timeout_ticks);
 
-/** 
+/**
  * Sets the given condition var to signalled state
  *
  * @param c - condition var to set in signalled state.
@@ -77,16 +77,16 @@ void racond_wait( racond c,  ramutex m,  sysint timeout_ticks);
  * @note:
  *  Only one waiter gets notified.
  */
-void racond_signal( racond c );
+void racond_signal(racond c);
 
-/** 
+/**
  * Sets notifys all waiting threads thats signalled.
  * @param c - condition var to set in signalled state
- * 
+ *
  * @note:
  *  All Waiters getting notified.
- */ 
-void racond_broadcast( racond c );
+ */
+void racond_broadcast(racond c);
 
 
 #endif

+ 183 - 166
src/common/netbuffer.c

@@ -26,10 +26,10 @@
 #include "../common/netbuffer.h"
 
 
-// 
+//
 // Buffers are available in the following sizes:
-//	48,		192,	2048,		8192
-//	65536 (inter server connects may use it for charstatus struct..)  
+//  48,     192,    2048,       8192
+//  65536 (inter server connects may use it for charstatus struct..)
 //
 
 
@@ -42,180 +42,197 @@ static sysint *l_poolElemSize = NULL;
 static mempool *l_pool = NULL;
 
 
-void netbuffer_init(){
-	char localsection[32];
-	raconf conf;
-	sysint i;
-	
-	// Initialize Statistic counters:
-	l_nEmergencyAllocations = 0;
-	
-	// Set localsection name according to running serverype.
-	switch(SERVER_TYPE){
-		case ATHENA_SERVER_LOGIN:	strcpy(localsection, "login-netbuffer");		break;
-		case ATHENA_SERVER_CHAR:	strcpy(localsection, "char-netbuffer");			break;
-		case ATHENA_SERVER_INTER:	strcpy(localsection, "inter-netbuffer");		break;
-		case ATHENA_SERVER_MAP:		strcpy(localsection, "map-netbuffer");			break;
-		default:					strcpy(localsection, "unsupported_type");		break;
-	}
-	
-	
-	conf = raconf_parse("conf/network.conf");
-	if(conf == NULL){
-		ShowFatalError("Failed to Parse required Configuration (conf/network.conf)");
-		exit(EXIT_FAILURE);
-	}
-	
-	// Get Values from config file
-	l_nPools = (sysint)raconf_getintEx(conf,  localsection,  "netbuffer", "num", 0);
-	if(l_nPools == 0){
-		ShowFatalError("Netbuffer (network.conf) failure - requires at least 1 Pool.\n");		
-		exit(EXIT_FAILURE);
-	}	
-
-	// Allocate arrays.
-	l_poolElemSize = (sysint*)aCalloc( l_nPools, sizeof(sysint) );
-	l_pool = (mempool*)aCalloc( l_nPools, sizeof(mempool) );
-	
-
-	for(i = 0; i < l_nPools; i++){
-		int64 num_prealloc, num_realloc;
-		char key[32];
-		
-		sprintf(key, "pool_%u_size", (uint32)i+1);
-		l_poolElemSize[i] = (sysint)raconf_getintEx(conf, localsection, "netbuffer", key, 4096);
-		if(l_poolElemSize[i] < 32){
-			ShowWarning("Netbuffer (network.conf) failure - minimum allowed buffer size is 32 byte) - fixed.\n");
-			l_poolElemSize[i] = 32;
-		}
-		
-		sprintf(key, "pool_%u_prealloc", (uint32)i+1);
-		num_prealloc = raconf_getintEx(conf, localsection, "netbuffer", key, 150);
-		
-		sprintf(key, "pool_%u_realloc_step", (uint32)i+1);
-		num_realloc = raconf_getintEx(conf, localsection, "netbuffer", key, 100);
-			
-		// Create Pool!
-		sprintf(key, "Netbuffer %u", (uint32)l_poolElemSize[i]); // name.
-
-		// Info
-		ShowInfo("NetBuffer: Creating Pool %u (Prealloc: %u, Realloc Step: %u) - %0.2f MiB\n", l_poolElemSize[i], num_prealloc, num_realloc, (float)((sizeof(struct netbuf) + l_poolElemSize[i] - 32)* num_prealloc)/1024.0f/1024.0f);
-		
-		//
-		// Size Calculation:
-		//  struct netbuf  +  requested buffer size - 32 (because the struct already contains 32 byte buffer space at the end of struct)
-		l_pool[i] = mempool_create(key,  (sizeof(struct netbuf) + l_poolElemSize[i] - 32),  num_prealloc,  num_realloc, NULL, NULL);
-		if(l_pool[i] == NULL){
-			ShowFatalError("Netbuffer: cannot create Pool for %u byte buffers.\n", l_poolElemSize[i]);
-			// @leak: clean everything :D
-			exit(EXIT_FAILURE);
-		}		
-				
-	}// 
-		
-	
-	raconf_destroy(conf);
+void netbuffer_init()
+{
+    char localsection[32];
+    raconf conf;
+    sysint i;
+
+    // Initialize Statistic counters:
+    l_nEmergencyAllocations = 0;
+
+    // Set localsection name according to running serverype.
+    switch (SERVER_TYPE) {
+        case ATHENA_SERVER_LOGIN:
+            strcpy(localsection, "login-netbuffer");
+            break;
+        case ATHENA_SERVER_CHAR:
+            strcpy(localsection, "char-netbuffer");
+            break;
+        case ATHENA_SERVER_INTER:
+            strcpy(localsection, "inter-netbuffer");
+            break;
+        case ATHENA_SERVER_MAP:
+            strcpy(localsection, "map-netbuffer");
+            break;
+        default:
+            strcpy(localsection, "unsupported_type");
+            break;
+    }
+
+
+    conf = raconf_parse("conf/network.conf");
+    if (conf == NULL) {
+        ShowFatalError("Failed to Parse required Configuration (conf/network.conf)");
+        exit(EXIT_FAILURE);
+    }
+
+    // Get Values from config file
+    l_nPools = (sysint)raconf_getintEx(conf,  localsection,  "netbuffer", "num", 0);
+    if (l_nPools == 0) {
+        ShowFatalError("Netbuffer (network.conf) failure - requires at least 1 Pool.\n");
+        exit(EXIT_FAILURE);
+    }
+
+    // Allocate arrays.
+    l_poolElemSize = (sysint *)aCalloc(l_nPools, sizeof(sysint));
+    l_pool = (mempool *)aCalloc(l_nPools, sizeof(mempool));
+
+
+    for (i = 0; i < l_nPools; i++) {
+        int64 num_prealloc, num_realloc;
+        char key[32];
+
+        sprintf(key, "pool_%u_size", (uint32)i+1);
+        l_poolElemSize[i] = (sysint)raconf_getintEx(conf, localsection, "netbuffer", key, 4096);
+        if (l_poolElemSize[i] < 32) {
+            ShowWarning("Netbuffer (network.conf) failure - minimum allowed buffer size is 32 byte) - fixed.\n");
+            l_poolElemSize[i] = 32;
+        }
+
+        sprintf(key, "pool_%u_prealloc", (uint32)i+1);
+        num_prealloc = raconf_getintEx(conf, localsection, "netbuffer", key, 150);
+
+        sprintf(key, "pool_%u_realloc_step", (uint32)i+1);
+        num_realloc = raconf_getintEx(conf, localsection, "netbuffer", key, 100);
+
+        // Create Pool!
+        sprintf(key, "Netbuffer %u", (uint32)l_poolElemSize[i]); // name.
+
+        // Info
+        ShowInfo("NetBuffer: Creating Pool %u (Prealloc: %u, Realloc Step: %u) - %0.2f MiB\n", l_poolElemSize[i], num_prealloc, num_realloc, (float)((sizeof(struct netbuf) + l_poolElemSize[i] - 32)* num_prealloc)/1024.0f/1024.0f);
+
+        //
+        // Size Calculation:
+        //  struct netbuf  +  requested buffer size - 32 (because the struct already contains 32 byte buffer space at the end of struct)
+        l_pool[i] = mempool_create(key, (sizeof(struct netbuf) + l_poolElemSize[i] - 32),  num_prealloc,  num_realloc, NULL, NULL);
+        if (l_pool[i] == NULL) {
+            ShowFatalError("Netbuffer: cannot create Pool for %u byte buffers.\n", l_poolElemSize[i]);
+            // @leak: clean everything :D
+            exit(EXIT_FAILURE);
+        }
+
+    }//
+
+
+    raconf_destroy(conf);
 
 }//end: netbuffer_init()
 
 
-void netbuffer_final(){
-	sysint i;
-	
-	if(l_nPools > 0){
-		/// .. finalize mempools
-		for(i = 0; i < l_nPools; i++){
-			mempool_stats stats = mempool_get_stats(l_pool[i]);
-			
-			ShowInfo("Netbuffer: Freeing Pool %u (Peak Usage: %u, Realloc Events: %u)\n", l_poolElemSize[i], stats.peak_nodes_used, stats.num_realloc_events);
-						
-			mempool_destroy(l_pool[i]);
-		}	
-	
-		if(l_nEmergencyAllocations > 0){
-			ShowWarning("Netbuffer: did %u Emergency Allocations, please tune your network.conf!\n", l_nEmergencyAllocations);
-			l_nEmergencyAllocations = 0;
-		}
-	
-		aFree(l_poolElemSize);  l_poolElemSize = NULL;
-		aFree(l_pool);	l_pool = NULL;
-		l_nPools = 0;
-	}
-	
-	
+void netbuffer_final()
+{
+    sysint i;
+
+    if (l_nPools > 0) {
+        /// .. finalize mempools
+        for (i = 0; i < l_nPools; i++) {
+            mempool_stats stats = mempool_get_stats(l_pool[i]);
+
+            ShowInfo("Netbuffer: Freeing Pool %u (Peak Usage: %u, Realloc Events: %u)\n", l_poolElemSize[i], stats.peak_nodes_used, stats.num_realloc_events);
+
+            mempool_destroy(l_pool[i]);
+        }
+
+        if (l_nEmergencyAllocations > 0) {
+            ShowWarning("Netbuffer: did %u Emergency Allocations, please tune your network.conf!\n", l_nEmergencyAllocations);
+            l_nEmergencyAllocations = 0;
+        }
+
+        aFree(l_poolElemSize);
+        l_poolElemSize = NULL;
+        aFree(l_pool);
+        l_pool = NULL;
+        l_nPools = 0;
+    }
+
+
 }//end: netbuffer_final()
 
 
-netbuf netbuffer_get( sysint sz ){
-	sysint i;
-	netbuf nb = NULL;
-	
-	// Search an appropriate pool
-	for(i = 0; i < l_nPools; i++){
-		if(sz <= l_poolElemSize[i]){
-			// match 
-			
-			nb = (netbuf)mempool_node_get(l_pool[i]); 
-			nb->pool = i;
-			
-			break;
-		}		
-	}
-	
-	// No Bufferpool found that mets there quirements?.. (thats bad..)
-	if(nb == NULL){
-		ShowWarning("Netbuffer: get(%u): => no appropriate pool found - emergency allocation required.\n", sz);
-		ShowWarning("Please reconfigure your network.conf!");
-		
-		InterlockedIncrement(&l_nEmergencyAllocations);
-
-		// .. better to check (netbuf struct provides 32 byte bufferspace itself.
-		if(sz < 32)	sz = 32;
-		
-		// allocate memory using malloc .. 
-		while(1){
-			nb = (netbuf) aMalloc(  (sizeof(struct netbuf) + sz - 32) );
-			if(nb != NULL){
-				memset(nb, 0x00, (sizeof(struct netbuf) + sz - 32) ); // zero memory! (to enforce commit @ os.)
-				nb->pool = -1; // emergency alloc.
-				break;
-			}
-			
-			rathread_yield();
-		}// spin allocation.
-		
-	}
-	
-	
-	nb->refcnt = 1;	 // Initial refcount is 1
-
-	return nb;	
+netbuf netbuffer_get(sysint sz)
+{
+    sysint i;
+    netbuf nb = NULL;
+
+    // Search an appropriate pool
+    for (i = 0; i < l_nPools; i++) {
+        if (sz <= l_poolElemSize[i]) {
+            // match
+
+            nb = (netbuf)mempool_node_get(l_pool[i]);
+            nb->pool = i;
+
+            break;
+        }
+    }
+
+    // No Bufferpool found that mets there quirements?.. (thats bad..)
+    if (nb == NULL) {
+        ShowWarning("Netbuffer: get(%u): => no appropriate pool found - emergency allocation required.\n", sz);
+        ShowWarning("Please reconfigure your network.conf!");
+
+        InterlockedIncrement(&l_nEmergencyAllocations);
+
+        // .. better to check (netbuf struct provides 32 byte bufferspace itself.
+        if (sz < 32) sz = 32;
+
+        // allocate memory using malloc ..
+        while (1) {
+            nb = (netbuf) aMalloc((sizeof(struct netbuf) + sz - 32));
+            if (nb != NULL) {
+                memset(nb, 0x00, (sizeof(struct netbuf) + sz - 32));  // zero memory! (to enforce commit @ os.)
+                nb->pool = -1; // emergency alloc.
+                break;
+            }
+
+            rathread_yield();
+        }// spin allocation.
+
+    }
+
+
+    nb->refcnt = 1;  // Initial refcount is 1
+
+    return nb;
 }//end: netbuffer_get()
 
 
-void netbuffer_put( netbuf nb ){
-	
-	// Decrement reference counter, if > 0 do nothing :)
-	if( InterlockedDecrement(&nb->refcnt) > 0 )
-		return;
-	
-	// Is this buffer an emergency allocated buffer?
-	if(nb->pool == -1){
-		aFree(nb); 
-		return;
-	}
-	
-	
-	// Otherwise its a normal mempool based buffer
-	// return it to the according mempool:
-	mempool_node_put( l_pool[nb->pool], nb);
-	
-	
+void netbuffer_put(netbuf nb)
+{
+
+    // Decrement reference counter, if > 0 do nothing :)
+    if (InterlockedDecrement(&nb->refcnt) > 0)
+        return;
+
+    // Is this buffer an emergency allocated buffer?
+    if (nb->pool == -1) {
+        aFree(nb);
+        return;
+    }
+
+
+    // Otherwise its a normal mempool based buffer
+    // return it to the according mempool:
+    mempool_node_put(l_pool[nb->pool], nb);
+
+
 }//end: netbuffer_put()
 
 
-void netbuffer_incref( netbuf nb ){
-	
-	InterlockedIncrement(&nb->refcnt);
-	
+void netbuffer_incref(netbuf nb)
+{
+
+    InterlockedIncrement(&nb->refcnt);
+
 }//end: netbuf_incref()

+ 39 - 39
src/common/netbuffer.h

@@ -6,37 +6,37 @@
 
 #include "../common/cbasetypes.h"
 
-typedef struct netbuf{
-	sysint	pool;				// The pool ID this buffer belongs to,
-								// is set to -1 if its an emergency allocated buffer 
-	
-	struct netbuf *next;		// Used by Network system.
-
-	volatile int32 refcnt;		// Internal Refcount, it gets lowered every call to netbuffer_put, 
-								// if its getting zero, the buffer will returned back to the pool
-								// and can be reused.
-
-	int32	dataPos;	// Current Offset
-						// Used only for Reading (recv job)
-						// write cases are using the sessions local datapos member due to
-						// shared write buffer support.
-	
-	int32	dataLen;	// read buffer case:
-						//	The length expected to read to.
-						//	when this->dataPos == dateLen, read job has been completed.
-						// write buffer case:
-						//	The lngth of data in te buffer
-						//	when s->dataPos == dataLen, write job has been completed
-						//
-						// Note:
-						//	leftBytes = (dateLen - dataPos)
-						//
-						//	Due to shared buffer support
-						//	dataPos gets not used in write case (each connection has its local offset)
-						//
-
-	// The Bufferspace itself.
-	char buf[32];
+typedef struct netbuf {
+    sysint  pool;               // The pool ID this buffer belongs to,
+    // is set to -1 if its an emergency allocated buffer
+
+    struct netbuf *next;        // Used by Network system.
+
+    volatile int32 refcnt;      // Internal Refcount, it gets lowered every call to netbuffer_put,
+    // if its getting zero, the buffer will returned back to the pool
+    // and can be reused.
+
+    int32   dataPos;    // Current Offset
+    // Used only for Reading (recv job)
+    // write cases are using the sessions local datapos member due to
+    // shared write buffer support.
+
+    int32   dataLen;    // read buffer case:
+    //  The length expected to read to.
+    //  when this->dataPos == dateLen, read job has been completed.
+    // write buffer case:
+    //  The lngth of data in te buffer
+    //  when s->dataPos == dataLen, write job has been completed
+    //
+    // Note:
+    //  leftBytes = (dateLen - dataPos)
+    //
+    //  Due to shared buffer support
+    //  dataPos gets not used in write case (each connection has its local offset)
+    //
+
+    // The Bufferspace itself.
+    char buf[32];
 } *netbuf;
 
 
@@ -47,29 +47,29 @@ void netbuffer_final();
  * Gets a netbuffer that has atleast (sz) byes space.
  *
  * @note: The netbuffer system guarantees that youll always recevie a buffer.
- *			no check for null is required!
+ *          no check for null is required!
  *
  * @param sz - minimum size needed.
  *
  * @return pointer to netbuf struct
  */
-netbuf netbuffer_get( sysint sz );
+netbuf netbuffer_get(sysint sz);
 
 
-/** 
+/**
  * Returns the given netbuffer (decreases refcount, if its 0 - the buffer will get returned to the pool)
  *
- * @param buf - the buffer to return 
+ * @param buf - the buffer to return
  */
-void netbuffer_put( netbuf buf );
+void netbuffer_put(netbuf buf);
 
 
-/** 
- * Increases the Refcount on the given buffer 
+/**
+ * Increases the Refcount on the given buffer
  * (used for areasends .. etc)
  *
  */
-void netbuffer_incref( netbuf buf );
+void netbuffer_incref(netbuf buf);
 
 
 // Some Useful macros

+ 909 - 900
src/common/network.c

@@ -51,1011 +51,1020 @@ static bool onSend(int32 fd);
 
 
 #define _network_free_netbuf_async( buf ) add_timer( 0, _network_async_free_netbuf_proc, 0,  (intptr_t) buf)
-static int _network_async_free_netbuf_proc(int tid, unsigned int tick, int id, intptr_t data){
-	// netbuf is in data
-	netbuffer_put( (netbuf)data );
+static int _network_async_free_netbuf_proc(int tid, unsigned int tick, int id, intptr_t data)
+{
+    // netbuf is in data
+    netbuffer_put((netbuf)data);
 
-	return 0;
+    return 0;
 }//end: _network_async_free_netbuf_proc()
 
 
 
-void network_init(){
-	SESSION *s;
-	int32 i;
-	
-	memset(g_Session, 0x00, (sizeof(SESSION) * MAXCONN) );
-	
-	for(i = 0; i < MAXCONN; i++){
-		s = &g_Session[i];
-		
-		s->type = NST_FREE;
-		s->disconnect_in_progress = false;
-				
-	}
-	
-	// Initialize the correspondig event dispatcher
-	evdp_init();
-
-	//
-	add_timer_func_list(_network_async_free_netbuf_proc, "_network_async_free_netbuf_proc");
-		
+void network_init()
+{
+    SESSION *s;
+    int32 i;
+
+    memset(g_Session, 0x00, (sizeof(SESSION) * MAXCONN));
+
+    for (i = 0; i < MAXCONN; i++) {
+        s = &g_Session[i];
+
+        s->type = NST_FREE;
+        s->disconnect_in_progress = false;
+
+    }
+
+    // Initialize the correspondig event dispatcher
+    evdp_init();
+
+    //
+    add_timer_func_list(_network_async_free_netbuf_proc, "_network_async_free_netbuf_proc");
+
 }//end: network_init()
 
 
-void network_final(){
+void network_final()
+{
+
+    // @TODO:
+    // .. disconnect and cleanup everything!
 
-	// @TODO:
-	// .. disconnect and cleanup everything!
-	
-	evdp_final();
+    evdp_final();
 
 }//end: network_final()
 
 
-void network_do(){
-	struct EVDP_EVENT l_events[EVENTS_PER_CYCLE];
-	register struct EVDP_EVENT *ev;
-	register int n, nfds;
-	register SESSION *s;
-	
-	nfds = evdp_wait( l_events,	EVENTS_PER_CYCLE, 1000); // @TODO: timer_getnext()
-	
-	for(n = 0; n < nfds; n++){
-		ev = &l_events[n];
-		s = &g_Session[ ev->fd ];
-		
-		if(ev->events & EVDP_EVENT_HUP){
-			network_disconnect( ev->fd );	
-			continue; // no further event processing.
-		}// endif vent is HUP (disconnect)
-		
-		
-		if(ev->events & EVDP_EVENT_IN){
-			
-			if(s->onRecv != NULL){
-				if( false == s->onRecv(ev->fd) ){
-					network_disconnect(ev->fd);
-					continue; // ..
-				}
-			}else{
-				ShowError("network_do: fd #%u has no onRecv proc set. - disconnecting\n", ev->fd);
-				network_disconnect(ev->fd);
-				continue;
-			}	
-						
-		}// endif event is IN (recv)
-		
-		
-		if(ev->events & EVDP_EVENT_OUT){
-			if(s->onSend != NULL){
-				if( false == s->onSend(ev->fd) ){
-					network_disconnect(ev->fd);
-					continue;
-				}
-			}else{
-				ShowError("network_do: fd #%u has no onSend proc set. - disconnecting\n", ev->fd);
-				network_disconnect(ev->fd);
-				continue;
-			}
-		}// endif event is OUT (send)
-		
-	}//endfor
-			
+void network_do()
+{
+    struct EVDP_EVENT l_events[EVENTS_PER_CYCLE];
+    register struct EVDP_EVENT *ev;
+    register int n, nfds;
+    register SESSION *s;
+
+    nfds = evdp_wait(l_events,  EVENTS_PER_CYCLE, 1000);  // @TODO: timer_getnext()
+
+    for (n = 0; n < nfds; n++) {
+        ev = &l_events[n];
+        s = &g_Session[ ev->fd ];
+
+        if (ev->events & EVDP_EVENT_HUP) {
+            network_disconnect(ev->fd);
+            continue; // no further event processing.
+        }// endif vent is HUP (disconnect)
+
+
+        if (ev->events & EVDP_EVENT_IN) {
+
+            if (s->onRecv != NULL) {
+                if (false == s->onRecv(ev->fd)) {
+                    network_disconnect(ev->fd);
+                    continue; // ..
+                }
+            } else {
+                ShowError("network_do: fd #%u has no onRecv proc set. - disconnecting\n", ev->fd);
+                network_disconnect(ev->fd);
+                continue;
+            }
+
+        }// endif event is IN (recv)
+
+
+        if (ev->events & EVDP_EVENT_OUT) {
+            if (s->onSend != NULL) {
+                if (false == s->onSend(ev->fd)) {
+                    network_disconnect(ev->fd);
+                    continue;
+                }
+            } else {
+                ShowError("network_do: fd #%u has no onSend proc set. - disconnecting\n", ev->fd);
+                network_disconnect(ev->fd);
+                continue;
+            }
+        }// endif event is OUT (send)
+
+    }//endfor
+
 }//end: network_do()
 
 
-static bool _setnonblock(int32 fd){
-	int flags = fcntl(fd, F_GETFL, 0);
-	if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0)
-		return false;
+static bool _setnonblock(int32 fd)
+{
+    int flags = fcntl(fd, F_GETFL, 0);
+    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0)
+        return false;
 
-	return true;
+    return true;
 }//end: _setnonblock()
 
 
-static bool _network_accept(int32 fd){
-	SESSION *listener = &g_Session[fd];
-	SESSION *s; 
-	union{
-		struct sockaddr_in v4;
+static bool _network_accept(int32 fd)
+{
+    SESSION *listener = &g_Session[fd];
+    SESSION *s;
+    union {
+        struct sockaddr_in v4;
 #ifdef ENABLE_IPV6
-		struct sockaddr_in6 v6;
+        struct sockaddr_in6 v6;
 #endif
-	} _addr;
-	int newfd;
-	socklen_t addrlen;
-	struct sockaddr *addr;
-
-	// Accept until OS returns - nothing to accept anymore
-	// - this is required due to our EVDP abstraction. (which handles on listening sockets similar to epoll's EPOLLET flag.)
-	while(1){
+    } _addr;
+    int newfd;
+    socklen_t addrlen;
+    struct sockaddr *addr;
+
+    // Accept until OS returns - nothing to accept anymore
+    // - this is required due to our EVDP abstraction. (which handles on listening sockets similar to epoll's EPOLLET flag.)
+    while (1) {
 #ifdef ENABLE_IPV6
-		if(listener->v6 == true){
-			addrlen = sizeof(_addr.v6);
-			addr = (struct sockaddr*)&_addr.v6;
-		}else{
+        if (listener->v6 == true) {
+            addrlen = sizeof(_addr.v6);
+            addr = (struct sockaddr *)&_addr.v6;
+        } else {
 #endif
-			addrlen = sizeof(_addr.v4);
-			addr = (struct sockaddr*)&_addr.v4;		
+            addrlen = sizeof(_addr.v4);
+            addr = (struct sockaddr *)&_addr.v4;
 #ifdef ENABLE_IPV6
-		}
+        }
 #endif
 
 #ifdef HAVE_ACCEPT4
-		newfd = accept4(fd, addr, &addrlen, SOCK_NONBLOCK);
+        newfd = accept4(fd, addr, &addrlen, SOCK_NONBLOCK);
 #else
-		newfd = accept(fd, addr, &addrlen);
+        newfd = accept(fd, addr, &addrlen);
 #endif
 
-		if(newfd == -1){
-			if(errno == EAGAIN || errno == EWOULDBLOCK)
-				break; // this is fully valid & whished., se explaination on top of while(1)
-			
-			// Otherwis .. we have serious problems :( seems tahat our listner has gone away..
-			// @TODO handle this .. 
-			ShowError("_network_accept: accept() returned error. closing listener. (errno: %u / %s)\n", errno, strerror(errno));
+        if (newfd == -1) {
+            if (errno == EAGAIN || errno == EWOULDBLOCK)
+                break; // this is fully valid & whished., se explaination on top of while(1)
+
+            // Otherwis .. we have serious problems :( seems tahat our listner has gone away..
+            // @TODO handle this ..
+            ShowError("_network_accept: accept() returned error. closing listener. (errno: %u / %s)\n", errno, strerror(errno));
 
-			return false; // will call disconnect after return.
-			//break;
-		}
+            return false; // will call disconnect after return.
+            //break;
+        }
 
 #ifndef HAVE_ACCEPT4 // no accept4 means, we have to set nonblock by ourself. ..
-		if(_setnonblock(newfd) == false){
-			ShowError("_network_accept: failed to set newly accepted connection nonblocking (errno: %u / %s). - disconnecting.\n", errno, strerror(errno));
-			close(newfd);
-			continue; 
-		}
+        if (_setnonblock(newfd) == false) {
+            ShowError("_network_accept: failed to set newly accepted connection nonblocking (errno: %u / %s). - disconnecting.\n", errno, strerror(errno));
+            close(newfd);
+            continue;
+        }
 #endif
 
-		// Check connection limits.
-		if(newfd >= MAXCONN){
-			ShowError("_network_accept: failed to accept connection - MAXCONN (%u) exceeded.\n", MAXCONN);
-			close(newfd);
-			continue; // we have to loop over the events (and disconnect them too ..) but otherwise we would leak event notifications.
-		}
-
-
-		// Create new Session.
-		s = &g_Session[newfd];
-		s->type = NST_CLIENT;
-		
-		// The new connection inherits listenr's handlers.
-		s->onDisconnect = listener->onDisconnect;
-		s->onConnect = listener->onConnect; // maybe useless but .. fear the future .. :~ 
-	
-		// Register the new connection @ EVDP
-		if( evdp_addclient(newfd, &s->evdp_data) == false){
-			ShowError("_network_accept: failed to accept connection - event subsystem returned an error.\n");
-			close(newfd);
-			s->type = NST_FREE;
-		}
-		
-		// Call the onConnect handler on the listener.
-		if( listener->onConnect(newfd) == false ){
-			// Resfused by onConnect handler..
-			evdp_remove(newfd, &s->evdp_data);
-			
-			close(newfd);
-			s->type = NST_FREE;
-			
-			s->data = NULL; // be on the safe side ~ !
-			continue;
-		}
-		
-		
-	}
-
-	return true;
+        // Check connection limits.
+        if (newfd >= MAXCONN) {
+            ShowError("_network_accept: failed to accept connection - MAXCONN (%u) exceeded.\n", MAXCONN);
+            close(newfd);
+            continue; // we have to loop over the events (and disconnect them too ..) but otherwise we would leak event notifications.
+        }
+
+
+        // Create new Session.
+        s = &g_Session[newfd];
+        s->type = NST_CLIENT;
+
+        // The new connection inherits listenr's handlers.
+        s->onDisconnect = listener->onDisconnect;
+        s->onConnect = listener->onConnect; // maybe useless but .. fear the future .. :~
+
+        // Register the new connection @ EVDP
+        if (evdp_addclient(newfd, &s->evdp_data) == false) {
+            ShowError("_network_accept: failed to accept connection - event subsystem returned an error.\n");
+            close(newfd);
+            s->type = NST_FREE;
+        }
+
+        // Call the onConnect handler on the listener.
+        if (listener->onConnect(newfd) == false) {
+            // Resfused by onConnect handler..
+            evdp_remove(newfd, &s->evdp_data);
+
+            close(newfd);
+            s->type = NST_FREE;
+
+            s->data = NULL; // be on the safe side ~ !
+            continue;
+        }
+
+
+    }
+
+    return true;
 }//end: _network_accept()
 
 
-void network_disconnect(int32 fd){
-	SESSION *s = &g_Session[fd];
-	netbuf b, bn;
-	
-	// Prevent recursive calls 
-	// by wrong implemented on disconnect handlers.. and such..
-	if(s->disconnect_in_progress == true)
-		return; 	
-		
-	s->disconnect_in_progress = true;
-	
-	
-	// Disconnect Todo:
-	//	- Call onDisconnect Handler
-	//	- Release all Assigned buffers.
-	//	- remove from event system (notifications)
-	//	- cleanup session structure
-	//	- close connection. 
-	//
-	
-	if(s->onDisconnect != NULL && 
-		s->type != NST_LISTENER){
-		
-		s->onDisconnect( fd );
-	}
-
-	// Read Buffer 
-	if(s->read.buf != NULL){
-		netbuffer_put(s->read.buf);
-		s->read.buf = NULL;
-	}
-
-	// Write Buffer(s)
-	b = s->write.buf;
-	while(1){
-		if(b == NULL) break;
-
-		bn = b->next;
-		
-		netbuffer_put(b);
-		
-		b = bn;
-	}
-	s->write.buf = NULL;
-	s->write.buf_last = NULL;
-	
-	s->write.n_outstanding = 0;
-	s->write.max_outstanding = 0;
-	
-		
-	// Remove from event system.
-	evdp_remove(fd, &s->evdp_data);
-	
-	// Cleanup Session Structure.
-	s->type = NST_FREE;
-	s->data = NULL; // no application level data assigned
-	s->disconnect_in_progress = false;
-
-
-	// Close connection	
-	close(fd);	
-	
+void network_disconnect(int32 fd)
+{
+    SESSION *s = &g_Session[fd];
+    netbuf b, bn;
+
+    // Prevent recursive calls
+    // by wrong implemented on disconnect handlers.. and such..
+    if (s->disconnect_in_progress == true)
+        return;
+
+    s->disconnect_in_progress = true;
+
+
+    // Disconnect Todo:
+    //  - Call onDisconnect Handler
+    //  - Release all Assigned buffers.
+    //  - remove from event system (notifications)
+    //  - cleanup session structure
+    //  - close connection.
+    //
+
+    if (s->onDisconnect != NULL &&
+        s->type != NST_LISTENER) {
+
+        s->onDisconnect(fd);
+    }
+
+    // Read Buffer
+    if (s->read.buf != NULL) {
+        netbuffer_put(s->read.buf);
+        s->read.buf = NULL;
+    }
+
+    // Write Buffer(s)
+    b = s->write.buf;
+    while (1) {
+        if (b == NULL) break;
+
+        bn = b->next;
+
+        netbuffer_put(b);
+
+        b = bn;
+    }
+    s->write.buf = NULL;
+    s->write.buf_last = NULL;
+
+    s->write.n_outstanding = 0;
+    s->write.max_outstanding = 0;
+
+
+    // Remove from event system.
+    evdp_remove(fd, &s->evdp_data);
+
+    // Cleanup Session Structure.
+    s->type = NST_FREE;
+    s->data = NULL; // no application level data assigned
+    s->disconnect_in_progress = false;
+
+
+    // Close connection
+    close(fd);
+
 }//end: network_disconnect()
 
 
-int32 network_addlistener(bool v6,  const char *addr,  uint16 port){
-	SESSION *s;
-	int optval, fd;
+int32 network_addlistener(bool v6,  const char *addr,  uint16 port)
+{
+    SESSION *s;
+    int optval, fd;
 
 #if !defined(ENABLE_IPV6)
-	if(v6 == true){
-		 ShowError("network_addlistener(%c, '%s', %u):  this release has no IPV6 support.\n",  (v6==true?'t':'f'),  addr, port);
-		 return -1;
-	}
+    if (v6 == true) {
+        ShowError("network_addlistener(%c, '%s', %u):  this release has no IPV6 support.\n", (v6==true?'t':'f'),  addr, port);
+        return -1;
+    }
 #endif
 
 
 #ifdef ENABLE_IPV6
-	if(v6 == true)
-		fd = socket(AF_INET6, SOCK_STREAM, 0);
-	else
+    if (v6 == true)
+        fd = socket(AF_INET6, SOCK_STREAM, 0);
+    else
 #endif
-		fd = socket(AF_INET, SOCK_STREAM, 0);
-
-	// Error?
-	if(fd == -1){
-		ShowError("network_addlistener(%c, '%s', %u):  socket() failed (errno: %u / %s)\n",  (v6==true?'t':'f'),  addr, port,    errno, strerror(errno));
-		return -1;
-	}
-	
-	// Too many connections?
-	if(fd >= MAXCONN){
-		ShowError("network_addlistener(%c, '%s', %u):  cannot create listener, exceeds more than supported connections (%u).\n", (v6==true?'t':'f'),  addr, port, MAXCONN);
-		close(fd);
-		return -1;
-	}
-	
-	
-	s = &g_Session[fd];
-	if(s->type != NST_FREE){ // additional checks.. :)
-			ShowError("network_addlistener(%c, '%s', %u): failed, got fd #%u which is already in use in local session table?!\n", (v6==true?'t':'f'),  addr, port, fd);
-			close(fd);
-			return -1;
-	}
-	
-	
-	// Fill ip addr structs
+        fd = socket(AF_INET, SOCK_STREAM, 0);
+
+    // Error?
+    if (fd == -1) {
+        ShowError("network_addlistener(%c, '%s', %u):  socket() failed (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port,    errno, strerror(errno));
+        return -1;
+    }
+
+    // Too many connections?
+    if (fd >= MAXCONN) {
+        ShowError("network_addlistener(%c, '%s', %u):  cannot create listener, exceeds more than supported connections (%u).\n", (v6==true?'t':'f'),  addr, port, MAXCONN);
+        close(fd);
+        return -1;
+    }
+
+
+    s = &g_Session[fd];
+    if (s->type != NST_FREE) { // additional checks.. :)
+        ShowError("network_addlistener(%c, '%s', %u): failed, got fd #%u which is already in use in local session table?!\n", (v6==true?'t':'f'),  addr, port, fd);
+        close(fd);
+        return -1;
+    }
+
+
+    // Fill ip addr structs
 #ifdef ENABLE_IPV6
-	if(v6 == true){
-		memset(&s->addr.v6, 0x00, sizeof(s->addr.v6));
-		s->addr.v6.sin6_family = AF_INET6;
-		s->addr.v6.sin6_port = htons(port);
-		if(inet_pton(AF_INET6, addr, &s->addr.v6.sin6_addr) != 1){
-			ShowError("network_addlistener(%c, '%s', %u): failed to parse the given IPV6 address.\n",  (v6==true?'t':'f'),  addr, port);
-			close(fd);
-			return -1;
-		}
-		
-	}else{
+    if (v6 == true) {
+        memset(&s->addr.v6, 0x00, sizeof(s->addr.v6));
+        s->addr.v6.sin6_family = AF_INET6;
+        s->addr.v6.sin6_port = htons(port);
+        if (inet_pton(AF_INET6, addr, &s->addr.v6.sin6_addr) != 1) {
+            ShowError("network_addlistener(%c, '%s', %u): failed to parse the given IPV6 address.\n", (v6==true?'t':'f'),  addr, port);
+            close(fd);
+            return -1;
+        }
+
+    } else {
 #endif
-		memset(&s->addr.v4, 0x00, sizeof(s->addr.v4));
-		s->addr.v4.sin_family = AF_INET;
-		s->addr.v4.sin_port = htons(port);
-		s->addr.v4.sin_addr.s_addr = inet_addr(addr);
+        memset(&s->addr.v4, 0x00, sizeof(s->addr.v4));
+        s->addr.v4.sin_family = AF_INET;
+        s->addr.v4.sin_port = htons(port);
+        s->addr.v4.sin_addr.s_addr = inet_addr(addr);
 #ifdef ENABLE_IPV6
-	}
+    }
 #endif
-		 
 
-	// if OS has support for SO_REUSEADDR, apply the flag
-	// so the address could be used when there're still time_wait sockets outstanding from previous application run.
+
+    // if OS has support for SO_REUSEADDR, apply the flag
+    // so the address could be used when there're still time_wait sockets outstanding from previous application run.
 #ifdef SO_REUSEADDR
-	optval=1;
-	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
+    optval=1;
+    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
 #endif
 
-	// Bind
+    // Bind
 #ifdef ENABLE_IPV6
-	if(v6 == true){
-		if( bind(fd, (struct sockaddr*)&s->addr.v6,  sizeof(s->addr.v6)) == -1) {
-			ShowError("network_addlistener(%c, '%s', %u): bind failed (errno: %u / %s)\n",  (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
-			close(fd);
-			return -1;
-		}
-	}else{
+    if (v6 == true) {
+        if (bind(fd, (struct sockaddr *)&s->addr.v6,  sizeof(s->addr.v6)) == -1) {
+            ShowError("network_addlistener(%c, '%s', %u): bind failed (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
+            close(fd);
+            return -1;
+        }
+    } else {
 #endif
-		if( bind(fd, (struct sockaddr*)&s->addr.v4,  sizeof(s->addr.v4)) == -1) {
-            ShowError("network_addlistener(%c, '%s', %u): bind failed (errno: %u / %s)\n",  (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
-			close(fd);
-			return -1;
-		}		
+        if (bind(fd, (struct sockaddr *)&s->addr.v4,  sizeof(s->addr.v4)) == -1) {
+            ShowError("network_addlistener(%c, '%s', %u): bind failed (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
+            close(fd);
+            return -1;
+        }
 #ifdef ENABLE_IPV6
-	}
+    }
 #endif
 
-	if( listen(fd, l_ListenBacklog) == -1){
-		ShowError("network_addlistener(%c, '%s', %u): listen failed (errno: %u / %s)\n",  (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
-		close(fd);
-		return -1;
-	}
-		
-
-	// Set to nonblock!
-	if(_setnonblock(fd) == false){
-		ShowError("network_addlistener(%c, '%s', %u): cannot set to nonblock (errno: %u / %s)\n",  (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
-		close(fd);
-		return -1;
-	}	
-
-
-	// Rgister @ evdp.
-	if( evdp_addlistener(fd, &s->evdp_data) != true){
-		ShowError("network_addlistener(%c, '%s', %u): eventdispatcher subsystem returned an error.\n",  (v6==true?'t':'f'),  addr, port);
-		close(fd);
-		return -1;
-	}
-	
-	
-	// Apply flags on Session array for this conneciton.
-	if(v6 == true)	s->v6 = true;
-	else			s->v6 = false;
-	
-	s->type = NST_LISTENER;
-	s->onRecv = _network_accept;
-
-	ShowStatus("Added Listener on '%s':%u\n", addr, port, (v6==true ? "(ipv6)":"(ipv4)") );
-
-	return fd;
+    if (listen(fd, l_ListenBacklog) == -1) {
+        ShowError("network_addlistener(%c, '%s', %u): listen failed (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
+        close(fd);
+        return -1;
+    }
+
+
+    // Set to nonblock!
+    if (_setnonblock(fd) == false) {
+        ShowError("network_addlistener(%c, '%s', %u): cannot set to nonblock (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
+        close(fd);
+        return -1;
+    }
+
+
+    // Rgister @ evdp.
+    if (evdp_addlistener(fd, &s->evdp_data) != true) {
+        ShowError("network_addlistener(%c, '%s', %u): eventdispatcher subsystem returned an error.\n", (v6==true?'t':'f'),  addr, port);
+        close(fd);
+        return -1;
+    }
+
+
+    // Apply flags on Session array for this conneciton.
+    if (v6 == true)  s->v6 = true;
+    else            s->v6 = false;
+
+    s->type = NST_LISTENER;
+    s->onRecv = _network_accept;
+
+    ShowStatus("Added Listener on '%s':%u\n", addr, port, (v6==true ? "(ipv6)":"(ipv4)"));
+
+    return fd;
 }//end: network_addlistener()
 
 
-static bool _network_connect_establishedHandler(int32 fd){
-	register SESSION *s = &g_Session[fd];
-	int val;
-	socklen_t val_len;
-	
-	if(s->type == NST_FREE)
-		return true;	// due to multiple non coalesced event notifications
-						// this can happen .. when a previous handled event has already disconnected the connection
-						// within the same cycle..
-	
-	val = -1;
-	val_len = sizeof(val);
-	getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &val_len);
-	
-	if(val != 0){
-		// :( .. cleanup session..
-		s->type = NST_FREE;
-		s->onSend = NULL;
-		s->onConnect = NULL;
-		s->onDisconnect = NULL;
-
-		evdp_remove(fd, &s->evdp_data);
-		close(fd);
-		
-		return true; // we CANT return false,
-					 // becuase the normal disconnect procedure would execute the ondisconnect handler, which we dont want .. in this case.
-	}else{
-		// ok 
-		if(s->onConnect(fd) == false) {
-			// onConnect handler has refused the connection .. 
-			// cleanup .. and ok
-			s->type = NST_FREE;
-			s->onSend = NULL;
-			s->onConnect = NULL;
-			s->onDisconnect = NULL;
-			
-			evdp_remove(fd, &s->evdp_data);
-			close(fd);
-			
-			return true; // we dnot want the ondisconnect handler to be executed, so its okay to handle this by ourself.
-		}
-		
-		// connection established ! 
-		// 
-		if( evdp_outgoingconnection_established(fd, &s->evdp_data) == false ){
-			return false; // we want the normal disconnect procedure.. with call to ondisconnect handler.
-		}
-		
-		s->onSend = NULL;
-		
-		ShowStatus("#%u connection successfull!\n", fd);	
-	}
-
-	return true;	
+static bool _network_connect_establishedHandler(int32 fd)
+{
+    register SESSION *s = &g_Session[fd];
+    int val;
+    socklen_t val_len;
+
+    if (s->type == NST_FREE)
+        return true;    // due to multiple non coalesced event notifications
+    // this can happen .. when a previous handled event has already disconnected the connection
+    // within the same cycle..
+
+    val = -1;
+    val_len = sizeof(val);
+    getsockopt(fd, SOL_SOCKET, SO_ERROR, &val, &val_len);
+
+    if (val != 0) {
+        // :( .. cleanup session..
+        s->type = NST_FREE;
+        s->onSend = NULL;
+        s->onConnect = NULL;
+        s->onDisconnect = NULL;
+
+        evdp_remove(fd, &s->evdp_data);
+        close(fd);
+
+        return true; // we CANT return false,
+        // becuase the normal disconnect procedure would execute the ondisconnect handler, which we dont want .. in this case.
+    } else {
+        // ok
+        if (s->onConnect(fd) == false) {
+            // onConnect handler has refused the connection ..
+            // cleanup .. and ok
+            s->type = NST_FREE;
+            s->onSend = NULL;
+            s->onConnect = NULL;
+            s->onDisconnect = NULL;
+
+            evdp_remove(fd, &s->evdp_data);
+            close(fd);
+
+            return true; // we dnot want the ondisconnect handler to be executed, so its okay to handle this by ourself.
+        }
+
+        // connection established !
+        //
+        if (evdp_outgoingconnection_established(fd, &s->evdp_data) == false) {
+            return false; // we want the normal disconnect procedure.. with call to ondisconnect handler.
+        }
+
+        s->onSend = NULL;
+
+        ShowStatus("#%u connection successfull!\n", fd);
+    }
+
+    return true;
 }//end: _network_connect_establishedHandler()
 
 
 int32 network_connect(bool v6,
-                        const char *addr,
-                        uint16 port,
-                        const char *from_addr,
-                        uint16 from_port,
-                        bool (*onConnectionEstablishedHandler)(int32 fd),
-                        void (*onConnectionLooseHandler)(int32 fd)
-){
-	register SESSION *s;
-	int32 fd, optval, ret;
-	struct sockaddr_in ip4;
+                      const char *addr,
+                      uint16 port,
+                      const char *from_addr,
+                      uint16 from_port,
+                      bool (*onConnectionEstablishedHandler)(int32 fd),
+                      void (*onConnectionLooseHandler)(int32 fd)
+                     )
+{
+    register SESSION *s;
+    int32 fd, optval, ret;
+    struct sockaddr_in ip4;
 #ifdef ENABLE_IPV6
-	struct sockaddr_in6 ip6;
+    struct sockaddr_in6 ip6;
 #endif
 
 #ifdef ENABLE_IPV6
-	if(v6 == true)
-		fd = socket(AF_INET6, SOCK_STREAM, 0);
-	else
+    if (v6 == true)
+        fd = socket(AF_INET6, SOCK_STREAM, 0);
+    else
 #endif
-		fd = socket(AF_INET, SOCK_STREAM, 0);
+        fd = socket(AF_INET, SOCK_STREAM, 0);
 
 #ifndef ENABLE_IPV6
-	// check..
-	if(v6 == true){
-		ShowError("network_connect(%c, '%s', %u...): tried to create an ipv6 connection, IPV6 is not supported in this release.\n", (v6==true?'t':'f'),  addr, port);
-		return -1;
-	}
+    // check..
+    if (v6 == true) {
+        ShowError("network_connect(%c, '%s', %u...): tried to create an ipv6 connection, IPV6 is not supported in this release.\n", (v6==true?'t':'f'),  addr, port);
+        return -1;
+    }
 #endif
 
-	// check connection limits.
-	if(fd >= MAXCONN){
-		ShowError("network_connect(%c, '%s', %u...): cannot create new connection, exceeeds more than supported connections (%u)\n", (v6==true?'t':'f'),  addr, port );
-		close(fd);
-		return -1;
-	}
-
-	
-	// Originating IP/Port pair given ?
-	if(from_addr != NULL && *from_addr != 0){
-		//.. 
-		#ifdef SO_REUSEADDR
-	    optval=1;
-	    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
-		#endif
-		
-		#ifdef ENABLE_IPV6
-		if(v6 == true){
-			memset(&ip6, 0x00, sizeof(ip6));
-			ip6.sin6_family = AF_INET6;
-			ip6.sin6_port = htons(from_port);
-			
-			if(inet_pton(AF_INET6, from_addr, &ip6.sin6_addr) != 1){
-				ShowError("network_connect(%c, '%s', %u...): cannot parse originating (from) IPV6 address (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
-				close(fd);
-				return -1;
- 			}
-		
- 			ret = bind(fd, (struct sockaddr*)&ip6, sizeof(ip6));
-		}else{
-		#endif
-			memset(&ip4, 0x00, sizeof(ip4));
-			
-			ip4.sin_family = AF_INET;
-			ip4.sin_port = htons(from_port);
-			ip4.sin_addr.s_addr = inet_addr(from_addr);
-			ret = bind(fd, (struct sockaddr*)&ip4, sizeof(ip4));
-		#ifdef ENABLE_IPV6
-		}
-		#endif
-		
-	}
-	
-
-	// Set non block
-	if(_setnonblock(fd) == false){
-		ShowError("network_connect(%c, '%s', %u...): cannot set socket to nonblocking (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
-		close(fd);
-		return -1;
-	}
-
-
-	// Create ip addr block to connect to .. 
+    // check connection limits.
+    if (fd >= MAXCONN) {
+        ShowError("network_connect(%c, '%s', %u...): cannot create new connection, exceeeds more than supported connections (%u)\n", (v6==true?'t':'f'),  addr, port);
+        close(fd);
+        return -1;
+    }
+
+
+    // Originating IP/Port pair given ?
+    if (from_addr != NULL && *from_addr != 0) {
+        //..
+#ifdef SO_REUSEADDR
+        optval=1;
+        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
+#endif
+
+#ifdef ENABLE_IPV6
+        if (v6 == true) {
+            memset(&ip6, 0x00, sizeof(ip6));
+            ip6.sin6_family = AF_INET6;
+            ip6.sin6_port = htons(from_port);
+
+            if (inet_pton(AF_INET6, from_addr, &ip6.sin6_addr) != 1) {
+                ShowError("network_connect(%c, '%s', %u...): cannot parse originating (from) IPV6 address (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
+                close(fd);
+                return -1;
+            }
+
+            ret = bind(fd, (struct sockaddr *)&ip6, sizeof(ip6));
+        } else {
+#endif
+            memset(&ip4, 0x00, sizeof(ip4));
+
+            ip4.sin_family = AF_INET;
+            ip4.sin_port = htons(from_port);
+            ip4.sin_addr.s_addr = inet_addr(from_addr);
+            ret = bind(fd, (struct sockaddr *)&ip4, sizeof(ip4));
 #ifdef ENABLE_IPV6
-	if(v6 == true){
-		memset(&ip6, 0x00, sizeof(ip6));
-		ip6.sin6_family = AF_INET6;
-		ip6.sin6_port = htons(port);
-		
-		if(inet_pton(AF_INET6, addr, &ip6.sin6_addr) != 1){
-			 ShowError("network_connect(%c, '%s', %u...): cannot parse destination IPV6 address (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
-			 close(fd);
-			 return -1;
-		}
-	
-	}else{
+        }
 #endif
-	memset(&ip4, 0x00, sizeof(ip4));
-	
-	ip4.sin_family = AF_INET;
-	ip4.sin_port = htons(port);
-	ip4.sin_addr.s_addr = inet_addr(addr);	
+
+    }
+
+
+    // Set non block
+    if (_setnonblock(fd) == false) {
+        ShowError("network_connect(%c, '%s', %u...): cannot set socket to nonblocking (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
+        close(fd);
+        return -1;
+    }
+
+
+    // Create ip addr block to connect to ..
+#ifdef ENABLE_IPV6
+    if (v6 == true) {
+        memset(&ip6, 0x00, sizeof(ip6));
+        ip6.sin6_family = AF_INET6;
+        ip6.sin6_port = htons(port);
+
+        if (inet_pton(AF_INET6, addr, &ip6.sin6_addr) != 1) {
+            ShowError("network_connect(%c, '%s', %u...): cannot parse destination IPV6 address (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
+            close(fd);
+            return -1;
+        }
+
+    } else {
+#endif
+        memset(&ip4, 0x00, sizeof(ip4));
+
+        ip4.sin_family = AF_INET;
+        ip4.sin_port = htons(port);
+        ip4.sin_addr.s_addr = inet_addr(addr);
 #ifdef ENABLE_IPV6
-	}
+    }
 #endif
 
 
-	// Assign Session..
-	s = &g_Session[fd];
-	s->type = NST_OUTGOING;
-	s->v6 = v6;
-	s->onConnect = onConnectionEstablishedHandler;
-	s->onDisconnect = onConnectionLooseHandler;
-	s->onRecv = NULL;
-	s->onSend = _network_connect_establishedHandler;
+    // Assign Session..
+    s = &g_Session[fd];
+    s->type = NST_OUTGOING;
+    s->v6 = v6;
+    s->onConnect = onConnectionEstablishedHandler;
+    s->onDisconnect = onConnectionLooseHandler;
+    s->onRecv = NULL;
+    s->onSend = _network_connect_establishedHandler;
 #ifdef ENABLE_IPV6
-	if(v6 == true)
-		memcpy(&s->addr.v6, &ip6, sizeof(ip6));
-	else
+    if (v6 == true)
+        memcpy(&s->addr.v6, &ip6, sizeof(ip6));
+    else
 #endif
-		memcpy(&s->addr.v4, &ip4, sizeof(ip4));
-	
-	// Register @ EVDP. as outgoing (see doc of the function)
-	if(evdp_addconnecting(fd, &s->evdp_data) == false){
-		ShowError("network_connect(%c, '%s', %u...): eventdispatcher subsystem returned an error.\n", (v6==true?'t':'f'),  addr, port);
-		
-		// cleanup session x.x.. 
-		s->type = NST_FREE;
-		s->onConnect = NULL;
-		s->onDisconnect = NULL;
-		s->onSend = NULL;
-		
-		// close, return error code.
-		close(fd);
-		return -1;
-	}
+        memcpy(&s->addr.v4, &ip4, sizeof(ip4));
+
+    // Register @ EVDP. as outgoing (see doc of the function)
+    if (evdp_addconnecting(fd, &s->evdp_data) == false) {
+        ShowError("network_connect(%c, '%s', %u...): eventdispatcher subsystem returned an error.\n", (v6==true?'t':'f'),  addr, port);
+
+        // cleanup session x.x..
+        s->type = NST_FREE;
+        s->onConnect = NULL;
+        s->onDisconnect = NULL;
+        s->onSend = NULL;
+
+        // close, return error code.
+        close(fd);
+        return -1;
+    }
 
 
 #ifdef ENABLE_IPV6
-	if(v6 == true)
-		ret = connect(fd, (struct sockaddr*)&ip6, sizeof(ip6));
-	else
+    if (v6 == true)
+        ret = connect(fd, (struct sockaddr *)&ip6, sizeof(ip6));
+    else
 #endif
-		ret = connect(fd, (struct sockaddr*)&ip4, sizeof(ip4));
-
-
-	// 
-	if(ret != 0 && errno != EINPROGRESS){
-		ShowWarning("network_connect(%c, '%s', %u...): connection failed (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
-		
-		// Cleanup session ..
-		s->type = NST_FREE;
-		s->onConnect = NULL;
-		s->onDisconnect = NULL;
-		s->onSend = NULL;
-		
-		// .. remove from evdp and close fd.	
-		evdp_remove(fd, &s->evdp_data);
-		close(fd);
-		return -1;
-	}
-
-
-	// ! The Info Message :~D
-	ShowStatus("network_connect fd#%u (%s:%u) in progress.. \n", fd, addr, port);
-
-return fd;	
+        ret = connect(fd, (struct sockaddr *)&ip4, sizeof(ip4));
+
+
+    //
+    if (ret != 0 && errno != EINPROGRESS) {
+        ShowWarning("network_connect(%c, '%s', %u...): connection failed (errno: %u / %s)\n", (v6==true?'t':'f'),  addr, port, errno, strerror(errno));
+
+        // Cleanup session ..
+        s->type = NST_FREE;
+        s->onConnect = NULL;
+        s->onDisconnect = NULL;
+        s->onSend = NULL;
+
+        // .. remove from evdp and close fd.
+        evdp_remove(fd, &s->evdp_data);
+        close(fd);
+        return -1;
+    }
+
+
+    // ! The Info Message :~D
+    ShowStatus("network_connect fd#%u (%s:%u) in progress.. \n", fd, addr, port);
+
+    return fd;
 }//end: network_connect()
 
 
-static bool _onSend(int32 fd){
-	register SESSION *s = &g_Session[fd];
-	register netbuf buf, buf_next;
-	register uint32 szNeeded;
-	register int wLen;
-
-	if(s->type == NST_FREE)
-		return true; 	// Possible due to multipl non coalsced event notifications 
-						// so onSend gets called after disconnect caused by an previous vent. 
-						// we can ignore the call to onSend, then. 
-	
-	buf = s->write.buf;
-	while(1){
-		if(buf == NULL)
-			break;
-		
-		buf_next = buf->next;
-		
-		
-		szNeeded = (buf->dataLen - s->write.dataPos);	// using th session-local .dataPos member, due to shared write buffer support.
-		
-		// try to write.
-		wLen = write(fd, &buf->buf[s->write.dataPos],  szNeeded);
-		if(wLen == 0){
-			return false; // eof.
-		}else if(wLen == -1){
-			if(errno == EAGAIN || errno == EWOULDBLOCK)
-				return true; // dont disconnect / try again later.
-			
-			// all other errors. . 
-			return false;
-		}
-		
-		// Wrote data.. =>
-		szNeeded -= wLen;
-		if(szNeeded > 0){
-			// still data left .. 
-			// 
-			s->write.dataPos += wLen; // fix offset.
-			return true;
-		}else{
-			// this buffer has been written successfully
-			// could be returned to pool.
-			netbuffer_put(buf);
-			s->write.n_outstanding--; // When threadsafe -> Interlocked here.
-			s->write.dataPos = 0; 
-		}
-			
-			
-		buf = buf_next;
-	}
-
-	// okay,
-	// reaching this part means:
-	// while interrupted by break - 
-	// which means all buffers are written, nothing left
-	//
-	
-	s->write.buf_last = NULL;
-	s->write.buf = NULL;
-	s->write.n_outstanding = 0;
-	s->write.dataPos = 0;
-	
-	// Remove from event dispatcher (write notification)
-	//
-	evdp_writable_remove(fd, &s->evdp_data);
-			
-	return true;	
+static bool _onSend(int32 fd)
+{
+    register SESSION *s = &g_Session[fd];
+    register netbuf buf, buf_next;
+    register uint32 szNeeded;
+    register int wLen;
+
+    if (s->type == NST_FREE)
+        return true;    // Possible due to multipl non coalsced event notifications
+    // so onSend gets called after disconnect caused by an previous vent.
+    // we can ignore the call to onSend, then.
+
+    buf = s->write.buf;
+    while (1) {
+        if (buf == NULL)
+            break;
+
+        buf_next = buf->next;
+
+
+        szNeeded = (buf->dataLen - s->write.dataPos);   // using th session-local .dataPos member, due to shared write buffer support.
+
+        // try to write.
+        wLen = write(fd, &buf->buf[s->write.dataPos],  szNeeded);
+        if (wLen == 0) {
+            return false; // eof.
+        } else if (wLen == -1) {
+            if (errno == EAGAIN || errno == EWOULDBLOCK)
+                return true; // dont disconnect / try again later.
+
+            // all other errors. .
+            return false;
+        }
+
+        // Wrote data.. =>
+        szNeeded -= wLen;
+        if (szNeeded > 0) {
+            // still data left ..
+            //
+            s->write.dataPos += wLen; // fix offset.
+            return true;
+        } else {
+            // this buffer has been written successfully
+            // could be returned to pool.
+            netbuffer_put(buf);
+            s->write.n_outstanding--; // When threadsafe -> Interlocked here.
+            s->write.dataPos = 0;
+        }
+
+
+        buf = buf_next;
+    }
+
+    // okay,
+    // reaching this part means:
+    // while interrupted by break -
+    // which means all buffers are written, nothing left
+    //
+
+    s->write.buf_last = NULL;
+    s->write.buf = NULL;
+    s->write.n_outstanding = 0;
+    s->write.dataPos = 0;
+
+    // Remove from event dispatcher (write notification)
+    //
+    evdp_writable_remove(fd, &s->evdp_data);
+
+    return true;
 }//end: _onSend()
 
 
-static bool _onRORecv(int32 fd){
-	register SESSION *s = &g_Session[fd];
-	register uint32	szNeeded;
-	register char *p;
-	register int rLen;
-	
-	if(s->type == NST_FREE)
-		return true;	// Possible due to multiple non coalesced events by evdp.
-						//  simply ignore this call returning positive result. 
-	
-	// Initialize p and szNeeded depending on change
-	// 
-	switch(s->read.state){
-		case NRS_WAITOP:
-			szNeeded = s->read.head_left;
-			p = ((char*)&s->read.head[0]) + (2-szNeeded);
-		break;
-
-		case NRS_WAITLEN:
-			szNeeded = s->read.head_left;
-			p = ((char*)&s->read.head[1]) + (2-szNeeded);
-		break;
-		
-		case NRS_WAITDATA:{
-			register netbuf buf = s->read.buf;
-			
-			szNeeded = (buf->dataLen - buf->dataPos);
-			p = (char*)&buf->buf[ buf->dataPos ];
-		}
-		break;	
-		
-		default: 
-			// .. the impossible gets possible .. 
-			ShowError("_onRORecv: fd #%u has unknown read.state (%d) - disconnecting\n", fd, s->read.state);
-			return false;
-		break;
-	}
-	
-	
-	// 
-	
-	rLen = read(fd, p, szNeeded);
-	if(rLen == 0){
-		// eof..
-		return false;
-	}else if(rLen == -1){
-		
-		if(errno == EAGAIN || errno == EWOULDBLOCK){
-			// try again later .. (this case shouldnt happen, because we're event trigered.. but .. sometimes it happens :)
-			return true;
-		}
-		
-		// an additional interesting case would be 
-		// EINTR, this 'could' be handled .. but:
-		//	posix says that its possible that data gets currupted during irq
-		//	or data gor read and not reported.., so we'd have a data loss..
-		//	(which shouldnt happen with stream based protocols such as tcp)
-		// its better to disonnect the client in that case.
-		
-		return false;
-	}
-	
-	//
-	// Got Data:
-	//  next action also depends on current state .. 
-	// 
-	szNeeded -= rLen;
-	switch(s->read.state){
-		case NRS_WAITOP:
-
-			if(szNeeded > 0){
-				// still data missing .. 
-				s->read.head_left = szNeeded;
-				return true; // wait for completion.
-			}else{
-				// complete .. 
-				//  next state depends on packet type.
-				
-				s->read.head[1] = ((uint16*)s->netparser_data)[ s->read.head[0] ];  // store lenght of packet by opcode head[0] to head[1]
-				
-				if(s->read.head[1] == ROPACKET_UNKNOWN){
-					// unknown packet - disconnect
-					ShowWarning("_onRORecv: fd #%u got unlnown packet 0x%04x - disconnecting.\n", fd, s->read.head[0]);
-					return false;
-				}
-				else if(s->read.head[1] == ROPACKET_DYNLEN){
-					// dynamic length
-					// next state: requrie len.
-					s->read.state = NRS_WAITLEN;
-					s->read.head_left = 2;
-					return true; //
-				}
-				else if(s->read.head[1] == 2){ 
-					// packet has no data (only opcode)
-					register netbuf buf = netbuffer_get(2); // :D whoohoo its giant! 
-					
-					NBUFW(buf, 0) = s->read.head[0]; // store opcode @ packet begin.
-					buf->dataPos = 2;
-					buf->dataLen = 2;
-					buf->next = NULL;
-					
-					// Back to initial state -> Need opcode.
-					s->read.state = NRS_WAITOP;
-					s->read.head_left = 2;
-					s->read.buf = NULL;
-					
-					// Call completion routine here.					
-					s->onPacketComplete(fd,  s->read.head[0],  2,  buf); 
-					
-					return true; // done :)
-				}
-				else{
-					// paket needs .. data ..
-					register netbuf buf = netbuffer_get( s->read.head[1] );
-					
-					NBUFW(buf, 0) = s->read.head[0]; // store opcode @ packet begin.
-					buf->dataPos = 2;
-					buf->dataLen = s->read.head[1];
-					buf->next = NULL;
-					
-					// attach buffer.
-					s->read.buf = buf;
-					
-					// set state:
-					s->read.state = NRS_WAITDATA;	
-					
-					return true;
-				}
-				
-			}//endif: szNeeded > 0 (opcode read completed?)
-			
-		break;
-		
-		
-		case NRS_WAITLEN:
-			
-			if(szNeeded > 0){
-				// incomplete .. 
-				s->read.head_left = szNeeded;
-				return true;
-			}else{
-				
-				if(s->read.head[1] == 4){
-					// packet has no data (only opcode + length)
-					register netbuf buf = netbuffer_get( 4 );
-					
-					NBUFL(buf, 0) = *((uint32*)&s->read.head[0]); // copy  Opcode + length to netbuffer using MOVL	
-					buf->dataPos = 4;
-					buf->dataLen = 4;
-					buf->next = NULL;
-					
-					// set initial state (need opcode)
-					s->read.state = NRS_WAITOP;
-					s->read.head_left = 2; 
-					s->read.buf = NULL;
-					
-					// call completion routine.
-					s->onPacketComplete(fd,  s->read.head[0],  4,  buf);
-
-					return true;					
-				}
-				else if(s->read.head[1] < 4){
-					// invalid header.
-					ShowWarning("_onRORecv: fd #%u invalid header - got packet 0x%04x, reported length < 4 - INVALID - disconnecting\n", fd, s->read.head[0]);
-					return false;
-				}
-				else{
-					// Data needed
-					// next state -> waitdata!
-					register netbuf buf = netbuffer_get( s->read.head[1] );
-					
-					NBUFL(buf, 0) = *((uint32*)&s->read.head[0]); // copy  Opcode + length to netbuffer using MOVL
-					buf->dataPos = 4;
-					buf->dataLen = s->read.head[1];
-					buf->next = NULL;
-					
-					// attach to session:
-					s->read.buf = buf;
-					s->read.state = NRS_WAITDATA;
-					
-					return true;
-				}
-				
-			}//endif: szNeeded > 0 (length read complete?)
-			
-		break;
-		
-		
-		case NRS_WAITDATA:
-
-			if(szNeeded == 0){
-				// Packet finished!
-				// compltion.
-				register netbuf buf = s->read.buf;
-				
-				// set initial state.
-				s->read.state = NRS_WAITOP;
-				s->read.head_left = 2;
-				s->read.buf = NULL;
-				
-				// Call completion routine.
-				s->onPacketComplete(fd,  NBUFW(buf, 0),  buf->dataLen,  buf);
-				
-				return true;
-			}else{
-				// still data needed 
-				s->read.buf->dataPos += rLen; 
-				
-				return true;				
-			}
-		break;
-		
-		
-		//
-		default:
-			ShowError("_onRORecv: fd #%u has unknown read.state (%d) [2] - disconnecting\n", fd, s->read.state);
-			return false;
-		break;
-	}
-	
-		
-	return false;
+static bool _onRORecv(int32 fd)
+{
+    register SESSION *s = &g_Session[fd];
+    register uint32 szNeeded;
+    register char *p;
+    register int rLen;
+
+    if (s->type == NST_FREE)
+        return true;    // Possible due to multiple non coalesced events by evdp.
+    //  simply ignore this call returning positive result.
+
+    // Initialize p and szNeeded depending on change
+    //
+    switch (s->read.state) {
+        case NRS_WAITOP:
+            szNeeded = s->read.head_left;
+            p = ((char *)&s->read.head[0]) + (2-szNeeded);
+            break;
+
+        case NRS_WAITLEN:
+            szNeeded = s->read.head_left;
+            p = ((char *)&s->read.head[1]) + (2-szNeeded);
+            break;
+
+        case NRS_WAITDATA: {
+                register netbuf buf = s->read.buf;
+
+                szNeeded = (buf->dataLen - buf->dataPos);
+                p = (char *)&buf->buf[ buf->dataPos ];
+            }
+            break;
+
+        default:
+            // .. the impossible gets possible ..
+            ShowError("_onRORecv: fd #%u has unknown read.state (%d) - disconnecting\n", fd, s->read.state);
+            return false;
+            break;
+    }
+
+
+    //
+
+    rLen = read(fd, p, szNeeded);
+    if (rLen == 0) {
+        // eof..
+        return false;
+    } else if (rLen == -1) {
+
+        if (errno == EAGAIN || errno == EWOULDBLOCK) {
+            // try again later .. (this case shouldnt happen, because we're event trigered.. but .. sometimes it happens :)
+            return true;
+        }
+
+        // an additional interesting case would be
+        // EINTR, this 'could' be handled .. but:
+        //  posix says that its possible that data gets currupted during irq
+        //  or data gor read and not reported.., so we'd have a data loss..
+        //  (which shouldnt happen with stream based protocols such as tcp)
+        // its better to disonnect the client in that case.
+
+        return false;
+    }
+
+    //
+    // Got Data:
+    //  next action also depends on current state ..
+    //
+    szNeeded -= rLen;
+    switch (s->read.state) {
+        case NRS_WAITOP:
+
+            if (szNeeded > 0) {
+                // still data missing ..
+                s->read.head_left = szNeeded;
+                return true; // wait for completion.
+            } else {
+                // complete ..
+                //  next state depends on packet type.
+
+                s->read.head[1] = ((uint16 *)s->netparser_data)[ s->read.head[0] ]; // store lenght of packet by opcode head[0] to head[1]
+
+                if (s->read.head[1] == ROPACKET_UNKNOWN) {
+                    // unknown packet - disconnect
+                    ShowWarning("_onRORecv: fd #%u got unlnown packet 0x%04x - disconnecting.\n", fd, s->read.head[0]);
+                    return false;
+                } else if (s->read.head[1] == ROPACKET_DYNLEN) {
+                    // dynamic length
+                    // next state: requrie len.
+                    s->read.state = NRS_WAITLEN;
+                    s->read.head_left = 2;
+                    return true; //
+                } else if (s->read.head[1] == 2) {
+                    // packet has no data (only opcode)
+                    register netbuf buf = netbuffer_get(2); // :D whoohoo its giant!
+
+                    NBUFW(buf, 0) = s->read.head[0]; // store opcode @ packet begin.
+                    buf->dataPos = 2;
+                    buf->dataLen = 2;
+                    buf->next = NULL;
+
+                    // Back to initial state -> Need opcode.
+                    s->read.state = NRS_WAITOP;
+                    s->read.head_left = 2;
+                    s->read.buf = NULL;
+
+                    // Call completion routine here.
+                    s->onPacketComplete(fd,  s->read.head[0],  2,  buf);
+
+                    return true; // done :)
+                } else {
+                    // paket needs .. data ..
+                    register netbuf buf = netbuffer_get(s->read.head[1]);
+
+                    NBUFW(buf, 0) = s->read.head[0]; // store opcode @ packet begin.
+                    buf->dataPos = 2;
+                    buf->dataLen = s->read.head[1];
+                    buf->next = NULL;
+
+                    // attach buffer.
+                    s->read.buf = buf;
+
+                    // set state:
+                    s->read.state = NRS_WAITDATA;
+
+                    return true;
+                }
+
+            }//endif: szNeeded > 0 (opcode read completed?)
+
+            break;
+
+
+        case NRS_WAITLEN:
+
+            if (szNeeded > 0) {
+                // incomplete ..
+                s->read.head_left = szNeeded;
+                return true;
+            } else {
+
+                if (s->read.head[1] == 4) {
+                    // packet has no data (only opcode + length)
+                    register netbuf buf = netbuffer_get(4);
+
+                    NBUFL(buf, 0) = *((uint32 *)&s->read.head[0]); // copy  Opcode + length to netbuffer using MOVL
+                    buf->dataPos = 4;
+                    buf->dataLen = 4;
+                    buf->next = NULL;
+
+                    // set initial state (need opcode)
+                    s->read.state = NRS_WAITOP;
+                    s->read.head_left = 2;
+                    s->read.buf = NULL;
+
+                    // call completion routine.
+                    s->onPacketComplete(fd,  s->read.head[0],  4,  buf);
+
+                    return true;
+                } else if (s->read.head[1] < 4) {
+                    // invalid header.
+                    ShowWarning("_onRORecv: fd #%u invalid header - got packet 0x%04x, reported length < 4 - INVALID - disconnecting\n", fd, s->read.head[0]);
+                    return false;
+                } else {
+                    // Data needed
+                    // next state -> waitdata!
+                    register netbuf buf = netbuffer_get(s->read.head[1]);
+
+                    NBUFL(buf, 0) = *((uint32 *)&s->read.head[0]); // copy  Opcode + length to netbuffer using MOVL
+                    buf->dataPos = 4;
+                    buf->dataLen = s->read.head[1];
+                    buf->next = NULL;
+
+                    // attach to session:
+                    s->read.buf = buf;
+                    s->read.state = NRS_WAITDATA;
+
+                    return true;
+                }
+
+            }//endif: szNeeded > 0 (length read complete?)
+
+            break;
+
+
+        case NRS_WAITDATA:
+
+            if (szNeeded == 0) {
+                // Packet finished!
+                // compltion.
+                register netbuf buf = s->read.buf;
+
+                // set initial state.
+                s->read.state = NRS_WAITOP;
+                s->read.head_left = 2;
+                s->read.buf = NULL;
+
+                // Call completion routine.
+                s->onPacketComplete(fd,  NBUFW(buf, 0),  buf->dataLen,  buf);
+
+                return true;
+            } else {
+                // still data needed
+                s->read.buf->dataPos += rLen;
+
+                return true;
+            }
+            break;
+
+
+            //
+        default:
+            ShowError("_onRORecv: fd #%u has unknown read.state (%d) [2] - disconnecting\n", fd, s->read.state);
+            return false;
+            break;
+    }
+
+
+    return false;
 }//end: _onRORecv()
 
 
-void network_send(int32 fd,  netbuf buf){
-	register SESSION *s = &g_Session[fd];
-	
+void network_send(int32 fd,  netbuf buf)
+{
+    register SESSION *s = &g_Session[fd];
+
 #ifdef PARANOID_CHECKS
-	if(fd >= MAXCONN){
-		ShowError("network_send: tried to attach buffer to connection idientifer #%u which is out of bounds.\n", fd);
-		_network_free_netbuf_async(buf);
-		return;
-	}
+    if (fd >= MAXCONN) {
+        ShowError("network_send: tried to attach buffer to connection idientifer #%u which is out of bounds.\n", fd);
+        _network_free_netbuf_async(buf);
+        return;
+    }
 #endif
 
 
-	if(s->type == NST_FREE)
-		return;
-	
-	// Check Max Outstanding buffers limit.
-	if( (s->write.max_outstanding > 0)	&&
-		(s->write.n_outstanding >= s->write.max_outstanding) ){
-		
-		ShowWarning("network_send: fd #%u max Outstanding buffers exceeded. - disconnecting.\n", fd);
-		network_disconnect(fd);
-		//
-		_network_free_netbuf_async(buf);
-		return;
-	}
-	
-
-	// Attach to the end:
-	buf->next = NULL;
-	if(s->write.buf_last != NULL){
-		s->write.buf_last->next = buf; 
-		s->write.buf_last = buf;
-
-	}else{
-		// currently no buffer attached.
-		s->write.buf = s->write.buf_last = buf;
-		
-		// register @ evdp for writable notification.
-		evdp_writable_add(fd, &s->evdp_data); // 
-	}
-	
-	
-	//
-	s->write.n_outstanding++;
-	
+    if (s->type == NST_FREE)
+        return;
+
+    // Check Max Outstanding buffers limit.
+    if ((s->write.max_outstanding > 0)   &&
+        (s->write.n_outstanding >= s->write.max_outstanding)) {
+
+        ShowWarning("network_send: fd #%u max Outstanding buffers exceeded. - disconnecting.\n", fd);
+        network_disconnect(fd);
+        //
+        _network_free_netbuf_async(buf);
+        return;
+    }
+
+
+    // Attach to the end:
+    buf->next = NULL;
+    if (s->write.buf_last != NULL) {
+        s->write.buf_last->next = buf;
+        s->write.buf_last = buf;
+
+    } else {
+        // currently no buffer attached.
+        s->write.buf = s->write.buf_last = buf;
+
+        // register @ evdp for writable notification.
+        evdp_writable_add(fd, &s->evdp_data); //
+    }
+
+
+    //
+    s->write.n_outstanding++;
+
 }//end: network_send()
 
 
 void network_parser_set_ro(int32 fd,
-							int16 *packetlentable,
-							void (*onPacketCompleteProc)(int32 fd,  uint16 op,  uint16 len,  netbuf buf) 
-							){
-	register SESSION *s = &g_Session[fd];
-	register netbuf b, nb; // used for potential free attached buffers.
-	
-	if(s->type == NST_FREE)
-		return;
-	
-	s->onPacketComplete = onPacketCompleteProc;
-	
-	s->onRecv = _onRORecv; // ..
-	s->onSend = _onSend; // Using the normal generic netbuf based send function.
-		
-	s->netparser_data = packetlentable;
-	
-	// Initial State -> Need Packet OPCode.
-	s->read.state = NRS_WAITOP;
-	s->read.head_left = 2; 
-
-	
-	// Detach (if..) all buffers.
-	if(s->read.buf != NULL){
-		_network_free_netbuf_async(s->read.buf); //
-		s->read.buf = NULL;	
-	}
-	
-	if(s->write.buf != NULL){
-		b = s->write.buf;
-		while(1){
-			nb = b->next;
-			
-			_network_free_netbuf_async(b);
-			
-			b = nb;
-		}
-	
-		s->write.buf = NULL;
-		s->write.buf_last = NULL;
-		s->write.n_outstanding = 0;
-	}
-	
-	// not changing any limits on outstanding ..
-	//
-	
+                           int16 *packetlentable,
+                           void (*onPacketCompleteProc)(int32 fd,  uint16 op,  uint16 len,  netbuf buf)
+                          )
+{
+    register SESSION *s = &g_Session[fd];
+    register netbuf b, nb; // used for potential free attached buffers.
+
+    if (s->type == NST_FREE)
+        return;
+
+    s->onPacketComplete = onPacketCompleteProc;
+
+    s->onRecv = _onRORecv; // ..
+    s->onSend = _onSend; // Using the normal generic netbuf based send function.
+
+    s->netparser_data = packetlentable;
+
+    // Initial State -> Need Packet OPCode.
+    s->read.state = NRS_WAITOP;
+    s->read.head_left = 2;
+
+
+    // Detach (if..) all buffers.
+    if (s->read.buf != NULL) {
+        _network_free_netbuf_async(s->read.buf); //
+        s->read.buf = NULL;
+    }
+
+    if (s->write.buf != NULL) {
+        b = s->write.buf;
+        while (1) {
+            nb = b->next;
+
+            _network_free_netbuf_async(b);
+
+            b = nb;
+        }
+
+        s->write.buf = NULL;
+        s->write.buf_last = NULL;
+        s->write.n_outstanding = 0;
+    }
+
+    // not changing any limits on outstanding ..
+    //
+
 }//end: network_parser_set_ro()

+ 110 - 110
src/common/network.h

@@ -3,7 +3,7 @@
 
 #include <netinet/in.h>
 #include "../common/cbasetypes.h"
-#include "../common/netbuffer.h" 
+#include "../common/netbuffer.h"
 #include "../common/evdp.h"
 
 #ifndef MAXCONN
@@ -11,79 +11,79 @@
 #endif
 
 
-typedef struct SESSION{
-	EVDP_DATA	evdp_data;	// Must be always the frist member! (some evdp's may rely on this fact)
-
-	// Connection Type	
-	enum{ NST_FREE=0, NST_LISTENER = 1, NST_CLIENT=2, NST_OUTGOING=3}	type;
-
-	// Flags / Settings.
-	bool v6; // is v6?
-	bool disconnect_in_progress;	// To prevent stack overflows / recursive calls.
-	
-	
-	union{ // union to save memory.
-		struct sockaddr_in	v4;
-		struct sockaddr_in6	v6;
-	}addr;
-	
-
-	// "lowlevel" Handlers
-	// (Implemented by the protocol specific parser)
-	//
-	bool (*onRecv)(int32 fd);	// return false = disconnect
-	bool (*onSend)(int32 fd);	// return false = disconnect
-
-	// Event Handlers for LISTENER type sockets 
-	//
-	// onConnect  gets Called when a connection has been 
-	//	successfully accepted.
-	//	Session entry is available in this Handler!
-	//	A returncode of false will reejct the connection (disconnect)
-	//	Note: When rejecting a connection in onConnect by returning false
-	//		  The onDisconnect handler wont get called!
-	//	Note: the onConnect Handler is also responsible for setting
-	//		  the appropriate netparser (which implements onRecv/onSend..) [protocol specific]
-	//	
-	// onDisconnect  gets called when a connection gets disconnected 
-	//				 (by peer as well as by core)
-	//
-	bool (*onConnect)(int32 fd);	// return false = disconnect (wont accept)
-	void (*onDisconnect)(int32 fd);
-
-
-	// 
-	// Parser specific data
-	//
-	void *netparser_data;	// incase of RO Packet Parser, pointer to packet len table (uint16array)
-	void (*onPacketComplete)(int32 fd, uint16 op, uint16 len, netbuf buf);
-	
-
-	//
-	// Buffers
-	// 
-	struct{
-		enum NETREADSTATE { NRS_WAITOP = 0,	NRS_WAITLEN = 1,	NRS_WAITDATA = 2}	state;
-		
-		uint32	head_left;
-		uint16	head[2];
-		
-		netbuf	buf;
-	} read;
-
-	struct{
-		uint32	max_outstanding;
-		uint32	n_outstanding;
-		
-		uint32	dataPos;
-				
-		netbuf	buf, buf_last;				
-	} write;
-	
-	// Application Level data Pointer
-	// (required for backward compatibility with previous athena socket system.)
-	void *data;
-				
+typedef struct SESSION {
+    EVDP_DATA   evdp_data;  // Must be always the frist member! (some evdp's may rely on this fact)
+
+    // Connection Type
+    enum { NST_FREE=0, NST_LISTENER = 1, NST_CLIENT=2, NST_OUTGOING=3}   type;
+
+    // Flags / Settings.
+    bool v6; // is v6?
+    bool disconnect_in_progress;    // To prevent stack overflows / recursive calls.
+
+
+    union { // union to save memory.
+        struct sockaddr_in  v4;
+        struct sockaddr_in6 v6;
+    } addr;
+
+
+    // "lowlevel" Handlers
+    // (Implemented by the protocol specific parser)
+    //
+    bool (*onRecv)(int32 fd);   // return false = disconnect
+    bool (*onSend)(int32 fd);   // return false = disconnect
+
+    // Event Handlers for LISTENER type sockets
+    //
+    // onConnect  gets Called when a connection has been
+    //  successfully accepted.
+    //  Session entry is available in this Handler!
+    //  A returncode of false will reejct the connection (disconnect)
+    //  Note: When rejecting a connection in onConnect by returning false
+    //        The onDisconnect handler wont get called!
+    //  Note: the onConnect Handler is also responsible for setting
+    //        the appropriate netparser (which implements onRecv/onSend..) [protocol specific]
+    //
+    // onDisconnect  gets called when a connection gets disconnected
+    //               (by peer as well as by core)
+    //
+    bool (*onConnect)(int32 fd);    // return false = disconnect (wont accept)
+    void (*onDisconnect)(int32 fd);
+
+
+    //
+    // Parser specific data
+    //
+    void *netparser_data;   // incase of RO Packet Parser, pointer to packet len table (uint16array)
+    void (*onPacketComplete)(int32 fd, uint16 op, uint16 len, netbuf buf);
+
+
+    //
+    // Buffers
+    //
+    struct {
+        enum NETREADSTATE { NRS_WAITOP = 0, NRS_WAITLEN = 1,    NRS_WAITDATA = 2}   state;
+
+        uint32  head_left;
+        uint16  head[2];
+
+        netbuf  buf;
+    } read;
+
+    struct {
+        uint32  max_outstanding;
+        uint32  n_outstanding;
+
+        uint32  dataPos;
+
+        netbuf  buf, buf_last;
+    } write;
+
+    // Application Level data Pointer
+    // (required for backward compatibility with previous athena socket system.)
+    void *data;
+
 } SESSION;
 
 
@@ -101,12 +101,12 @@ void network_final();
 void network_do();
 
 
-/** 
+/**
  * Adds a new listner.
  *
- * @param v6	v6 listner? 
- * @param *addr	the address to listen on.
- * @param port	port to listen on
+ * @param v6    v6 listner?
+ * @param *addr the address to listen on.
+ * @param port  port to listen on
  *
  * @return -1 on error  otherwise  the identifier of the new listener.
  */
@@ -116,26 +116,26 @@ int32 network_addlistener(bool v6,  const char *addr,  uint16 port);
 /**
  * Tries to establish an outgoing connection.
  *
- * @param v6		operate with IPv6 addresses?
- * @param addr		the address to connect to
- * @param port		the port to connect to
- * @param from_addr	the address to connect from (local source / optional if auto  -> NULL)
+ * @param v6        operate with IPv6 addresses?
+ * @param addr      the address to connect to
+ * @param port      the port to connect to
+ * @param from_addr the address to connect from (local source / optional if auto  -> NULL)
  * @param from_port the port to connect from (local source / optional if auto  -> 0)
- * @param onConnectionEstablishedHandler	callback that gets called when the connection is established.
- * @param onConnectionLooseHandler			callback that gets called when the connection gets disconnected (or the connection couldnt be established)
+ * @param onConnectionEstablishedHandler    callback that gets called when the connection is established.
+ * @param onConnectionLooseHandler          callback that gets called when the connection gets disconnected (or the connection couldnt be established)
  *
  * @return -1 on error  otherwise  the identifier of the new connection
  */
 int32 network_connect(bool v6,
-						const char *addr,
-						uint16 port,
-						const char *from_addr,
-						uint16 from_port,
-						bool (*onConnectionEstablishedHandler)(int32 fd),
-						void (*onConnectionLooseHandler)(int32 fd)
-);
+                      const char *addr,
+                      uint16 port,
+                      const char *from_addr,
+                      uint16 from_port,
+                      bool (*onConnectionEstablishedHandler)(int32 fd),
+                      void (*onConnectionLooseHandler)(int32 fd)
+                     );
+
 
-						
 
 /**
  * Disconnects the given connection
@@ -143,43 +143,43 @@ int32 network_connect(bool v6,
  * @param fd  connection identifier.
  *
  * @Note:
- * 	- onDisconnect callback gets called! 
- *	- cleares (returns) all assigned buffers
+ *  - onDisconnect callback gets called!
+ *  - cleares (returns) all assigned buffers
  *
  */
 void network_disconnect(int32 fd);
 
 
-/** 
+/**
  * Attach's a netbuffer at the end of sending queue to the given connection
  *
- * @param fd	connection identifier
- * @param buf	netbuffer to attach.
+ * @param fd    connection identifier
+ * @param buf   netbuffer to attach.
  */
 void network_send(int32 fd,  netbuf buf);
 
 
 /**
  * Sets the parser to RO Protocol like Packet Parser.
- * 
- * @param fd				connection identifier
- * @param *packetlentable	pointer to array of uint16 in size of UINT16_MAX,
- * @param onComplteProc		callback for packet completion.
+ *
+ * @param fd                connection identifier
+ * @param *packetlentable   pointer to array of uint16 in size of UINT16_MAX,
+ * @param onComplteProc     callback for packet completion.
  *
  * @note:
- * 	PacketLen Table Fromat:
- *	each element's offsets represents th ro opcode.
- *	value is length.
- *	a length of 0  means the packet is dynamic.
- *	a length of UINT16_MAX means the packet is unknown.
+ *  PacketLen Table Fromat:
+ *  each element's offsets represents th ro opcode.
+ *  value is length.
+ *  a length of 0  means the packet is dynamic.
+ *  a length of UINT16_MAX means the packet is unknown.
  *
- *	Static Packets must contain their hader in len so (0x64 ==  55 ..)
+ *  Static Packets must contain their hader in len so (0x64 ==  55 ..)
  *
  */
 void network_parser_set_ro(int32 fd,
-							int16 *packetlentable,
-							void (*onPacketCompleteProc)(int32 fd,  uint16 op,  uint16 len,  netbuf buf) 
-							);
+                           int16 *packetlentable,
+                           void (*onPacketCompleteProc)(int32 fd,  uint16 op,  uint16 len,  netbuf buf)
+                          );
 #define ROPACKET_UNKNOWN UINT16_MAX
 #define ROPACKET_DYNLEN 0
 

+ 47 - 49
src/common/nullpo.c

@@ -8,7 +8,7 @@
 #include "../common/showmsg.h"
 // #include "logs.h" // 布石してみる
 
-static void nullpo_info_core(const char *file, int line, const char *func, 
+static void nullpo_info_core(const char *file, int line, const char *func,
                              const char *fmt, va_list ap);
 
 /*======================================
@@ -17,75 +17,73 @@ static void nullpo_info_core(const char *file, int line, const char *func,
 int nullpo_chk_f(const char *file, int line, const char *func, const void *target,
                  const char *fmt, ...)
 {
-	va_list ap;
-	
-	if (target != NULL)
-		return 0;
-	
-	va_start(ap, fmt);
-	nullpo_info_core(file, line, func, fmt, ap);
-	va_end(ap);
-	return 1;
+    va_list ap;
+
+    if (target != NULL)
+        return 0;
+
+    va_start(ap, fmt);
+    nullpo_info_core(file, line, func, fmt, ap);
+    va_end(ap);
+    return 1;
 }
 
 int nullpo_chk(const char *file, int line, const char *func, const void *target)
 {
-	if (target != NULL)
-		return 0;
-	
-	nullpo_info_core(file, line, func, NULL, NULL);
-	return 1;
+    if (target != NULL)
+        return 0;
+
+    nullpo_info_core(file, line, func, NULL, NULL);
+    return 1;
 }
 
 
 /*======================================
  * nullpo情報出力(外部呼出し向けラッパ)
  *--------------------------------------*/
-void nullpo_info_f(const char *file, int line, const char *func, 
-                 const char *fmt, ...)
+void nullpo_info_f(const char *file, int line, const char *func,
+                   const char *fmt, ...)
 {
-	va_list ap;
-	
-	va_start(ap, fmt);
-	nullpo_info_core(file, line, func, fmt, ap);
-	va_end(ap);
+    va_list ap;
+
+    va_start(ap, fmt);
+    nullpo_info_core(file, line, func, fmt, ap);
+    va_end(ap);
 }
 
 void nullpo_info(const char *file, int line, const char *func)
 {
-	nullpo_info_core(file, line, func, NULL, NULL);
+    nullpo_info_core(file, line, func, NULL, NULL);
 }
 
 
 /*======================================
  * nullpo情報出力(Main)
  *--------------------------------------*/
-static void nullpo_info_core(const char *file, int line, const char *func, 
+static void nullpo_info_core(const char *file, int line, const char *func,
                              const char *fmt, va_list ap)
 {
-	if (file == NULL)
-		file = "??";
-	
-	func =
-		func == NULL    ? "unknown":
-		func[0] == '\0' ? "unknown":
-		                  func;
-	
-	ShowMessage("--- nullpo info --------------------------------------------\n");
-	ShowMessage("%s:%d: in func `%s'\n", file, line, func);
-	if (fmt != NULL)
-	{
-		if (fmt[0] != '\0')
-		{
-			vprintf(fmt, ap);
-			
-			// 最後に改行したか確認
-			if (fmt[strlen(fmt)-1] != '\n')
-				ShowMessage("\n");
-		}
-	}
-	ShowMessage("--- end nullpo info ----------------------------------------\n");
-	
-	// ここらでnullpoログをファイルに書き出せたら
-	// まとめて提出できるなと思っていたり。
+    if (file == NULL)
+        file = "??";
+
+    func =
+        func == NULL    ? "unknown":
+        func[0] == '\0' ? "unknown":
+        func;
+
+    ShowMessage("--- nullpo info --------------------------------------------\n");
+    ShowMessage("%s:%d: in func `%s'\n", file, line, func);
+    if (fmt != NULL) {
+        if (fmt[0] != '\0') {
+            vprintf(fmt, ap);
+
+            // 最後に改行したか確認
+            if (fmt[strlen(fmt)-1] != '\n')
+                ShowMessage("\n");
+        }
+    }
+    ShowMessage("--- end nullpo info ----------------------------------------\n");
+
+    // ここらでnullpoログをファイルに書き出せたら
+    // まとめて提出できるなと思っていたり。
 }

+ 15 - 15
src/common/nullpo.h

@@ -71,45 +71,45 @@
 #if defined(NULLPO_CHECK)
 
 #define nullpo_ret(t) \
-	if (nullpo_chk(NLP_MARK, (void *)(t))) {return(0);}
+    if (nullpo_chk(NLP_MARK, (void *)(t))) {return(0);}
 
 #define nullpo_retv(t) \
-	if (nullpo_chk(NLP_MARK, (void *)(t))) {return;}
+    if (nullpo_chk(NLP_MARK, (void *)(t))) {return;}
 
 #define nullpo_retr(ret, t) \
-	if (nullpo_chk(NLP_MARK, (void *)(t))) {return(ret);}
+    if (nullpo_chk(NLP_MARK, (void *)(t))) {return(ret);}
 
 #define nullpo_retb(t) \
-	if (nullpo_chk(NLP_MARK, (void *)(t))) {break;}
+    if (nullpo_chk(NLP_MARK, (void *)(t))) {break;}
 
 // 可変引数マクロに関する条件コンパイル
 #if __STDC_VERSION__ >= 199901L
 /* C99に対応 */
 #define nullpo_ret_f(t, fmt, ...) \
-	if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return(0);}
+    if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return(0);}
 
 #define nullpo_retv_f(t, fmt, ...) \
-	if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return;}
+    if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return;}
 
 #define nullpo_retr_f(ret, t, fmt, ...) \
-	if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return(ret);}
+    if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {return(ret);}
 
 #define nullpo_retb_f(t, fmt, ...) \
-	if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {break;}
+    if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), __VA_ARGS__)) {break;}
 
 #elif __GNUC__ >= 2
 /* GCC用 */
 #define nullpo_ret_f(t, fmt, args...) \
-	if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return(0);}
+    if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return(0);}
 
 #define nullpo_retv_f(t, fmt, args...) \
-	if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return;}
+    if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return;}
 
 #define nullpo_retr_f(ret, t, fmt, args...) \
-	if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return(ret);}
+    if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {return(ret);}
 
 #define nullpo_retb_f(t, fmt, args...) \
-	if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {break;}
+    if (nullpo_chk_f(NLP_MARK, (void *)(t), (fmt), ## args)) {break;}
 
 #else
 
@@ -189,7 +189,7 @@ int nullpo_chk(const char *file, int line, const char *func, const void *target)
  */
 int nullpo_chk_f(const char *file, int line, const char *func, const void *target,
                  const char *fmt, ...)
-                 __attribute__((format(printf,5,6)));
+__attribute__((format(printf,5,6)));
 
 
 /*======================================
@@ -217,9 +217,9 @@ void nullpo_info(const char *file, int line, const char *func);
  *    備考や関係変数の書き出しなどに
  *--------------------------------------
  */
-void nullpo_info_f(const char *file, int line, const char *func, 
+void nullpo_info_f(const char *file, int line, const char *func,
                    const char *fmt, ...)
-                   __attribute__((format(printf,4,5)));
+__attribute__((format(printf,4,5)));
 
 
 #endif /* _NULLPO_H_ */

+ 524 - 513
src/common/raconf.c

@@ -1,7 +1,7 @@
-// 
+//
 // Athena style config parser
-// (would be better to have "one" implementation instead of .. 4 :) 
-// 
+// (would be better to have "one" implementation instead of .. 4 :)
+//
 //
 // Author: Florian Wilkemeyer <fw@f-ws.de>
 //
@@ -25,560 +25,571 @@
 #define VARNAME_LEN 64
 
 struct raconf {
-	DBMap *db;
+    DBMap *db;
 };
 
 
-struct conf_value{
-	int64 intval;
-	bool bval;
-	double floatval;
-	size_t strval_len; // not includung \0 
-	char strval[16];
+struct conf_value {
+    int64 intval;
+    bool bval;
+    double floatval;
+    size_t strval_len; // not includung \0
+    char strval[16];
 };
 
 
 
-static struct conf_value *makeValue(const char *key, char *val, size_t val_len){
-	struct conf_value *v;
-	char *p;
-	size_t sz;
-		
-	sz = sizeof(struct conf_value);
-	if(val_len >=  sizeof(v->strval))
-		sz += (val_len - sizeof(v->strval) +  1);
-	
-	v = (struct conf_value*)aCalloc(1, sizeof(struct conf_value));
-	if(v == NULL){
-		ShowFatalError("raconf: makeValue => Out of Memory while allocating new node.\n");
-		return NULL;
-	}
-	
-	memcpy(v->strval, val, val_len);
-	v->strval[val_len+1] = '\0';
-	v->strval_len = val_len;
-	
-	
-	// Parse boolean value:
-	if((val_len == 4)  &&  (strncmpi("true", val, 4) == 0))
-		v->bval = true;
-	else if((val_len == 3) && (strncmpi("yes", val, 3) == 0))
-		v->bval = true;
-	else if((val_len == 3) && (strncmpi("oui", val, 3) == 0))
-		v->bval = true;
-	else if((val_len == 2) && (strncmpi("si", val, 2) == 0))
-		v->bval = true;
-	else if((val_len == 2) && (strncmpi("ja", val, 2) == 0))
-		v->bval = true;
-	else if((val_len == 1) && (*val == '1'))
-		v->bval = true;
-	else if((val_len == 5) && (strncmpi("false", val, 5) == 0))
-		v->bval = false;
-	else if((val_len == 2) && (strncmpi("no", val, 2) == 0))
-		v->bval = false;
-	else if((val_len == 3) && (strncmpi("non", val, 3) == 0))
-		v->bval = false;
-	else if((val_len == 2) && (strncmpi("no", val, 2) == 0))
-		v->bval = false;
-	else if((val_len == 4) && (strncmpi("nein", val, 4) == 0))
-		v->bval = false;
-	else if((val_len == 1) && (*val == '0'))
-		v->bval = false;		
-	else
-		v->bval = false; // assume false.
-		
-	// Parse number
-	// Supported formats:
-	// prefix: 0x hex . 
-	// postix: h for hex
-	//		   b for bin (dual)
-	if( (val_len >= 1 && (val[val_len] == 'h')) || (val_len >= 2 && (val[0] == '0' && val[1] == 'x')) ){//HEX!
-			if(val[val_len] == 'h'){
-				val[val_len]= '\0';
-				v->intval = strtoull(val, NULL, 16);
-				val[val_len] = 'h';
-			}else
-				v->intval = strtoull(&val[2], NULL, 16);
-	}else if( val_len >= 1 && (val[val_len] == 'b') ){	//BIN
-		val[val_len] = '\0';
-		v->intval = strtoull(val, NULL, 2);
-		val[val_len] = 'b';
-	}else if( *val >='0' && *val <= '9'){	// begins with normal digit, so assume its dec.
-		// is it float?
-		bool is_float = false;
-		
-		for(p = val; *p != '\0'; p++){
-			if(*p == '.'){
-				v->floatval = strtod(val, NULL);
-				v->intval = (int64) v->floatval;
-				is_float = true;
-				break;
-			}
-		}
-		
-		if(is_float == false){
-			v->intval = strtoull(val, NULL, 10);
-			v->floatval = (double) v->intval;
-		}
-	}else{
-		// Everything else: lets use boolean for fallback
-		if(v->bval == true)
-			v->intval = 1;
-		else
-			v->intval = 0;
-	}
-	
-	return v;	
+static struct conf_value *makeValue(const char *key, char *val, size_t val_len) {
+    struct conf_value *v;
+    char *p;
+    size_t sz;
+
+    sz = sizeof(struct conf_value);
+    if (val_len >=  sizeof(v->strval))
+        sz += (val_len - sizeof(v->strval) +  1);
+
+    v = (struct conf_value *)aCalloc(1, sizeof(struct conf_value));
+    if (v == NULL) {
+        ShowFatalError("raconf: makeValue => Out of Memory while allocating new node.\n");
+        return NULL;
+    }
+
+    memcpy(v->strval, val, val_len);
+    v->strval[val_len+1] = '\0';
+    v->strval_len = val_len;
+
+
+    // Parse boolean value:
+    if ((val_len == 4)  && (strncmpi("true", val, 4) == 0))
+        v->bval = true;
+    else if ((val_len == 3) && (strncmpi("yes", val, 3) == 0))
+        v->bval = true;
+    else if ((val_len == 3) && (strncmpi("oui", val, 3) == 0))
+        v->bval = true;
+    else if ((val_len == 2) && (strncmpi("si", val, 2) == 0))
+        v->bval = true;
+    else if ((val_len == 2) && (strncmpi("ja", val, 2) == 0))
+        v->bval = true;
+    else if ((val_len == 1) && (*val == '1'))
+        v->bval = true;
+    else if ((val_len == 5) && (strncmpi("false", val, 5) == 0))
+        v->bval = false;
+    else if ((val_len == 2) && (strncmpi("no", val, 2) == 0))
+        v->bval = false;
+    else if ((val_len == 3) && (strncmpi("non", val, 3) == 0))
+        v->bval = false;
+    else if ((val_len == 2) && (strncmpi("no", val, 2) == 0))
+        v->bval = false;
+    else if ((val_len == 4) && (strncmpi("nein", val, 4) == 0))
+        v->bval = false;
+    else if ((val_len == 1) && (*val == '0'))
+        v->bval = false;
+    else
+        v->bval = false; // assume false.
+
+    // Parse number
+    // Supported formats:
+    // prefix: 0x hex .
+    // postix: h for hex
+    //         b for bin (dual)
+    if ((val_len >= 1 && (val[val_len] == 'h')) || (val_len >= 2 && (val[0] == '0' && val[1] == 'x'))) {//HEX!
+        if (val[val_len] == 'h') {
+            val[val_len]= '\0';
+            v->intval = strtoull(val, NULL, 16);
+            val[val_len] = 'h';
+        } else
+            v->intval = strtoull(&val[2], NULL, 16);
+    } else if (val_len >= 1 && (val[val_len] == 'b')) {   //BIN
+        val[val_len] = '\0';
+        v->intval = strtoull(val, NULL, 2);
+        val[val_len] = 'b';
+    } else if (*val >='0' && *val <= '9') {   // begins with normal digit, so assume its dec.
+        // is it float?
+        bool is_float = false;
+
+        for (p = val; *p != '\0'; p++) {
+            if (*p == '.') {
+                v->floatval = strtod(val, NULL);
+                v->intval = (int64) v->floatval;
+                is_float = true;
+                break;
+            }
+        }
+
+        if (is_float == false) {
+            v->intval = strtoull(val, NULL, 10);
+            v->floatval = (double) v->intval;
+        }
+    } else {
+        // Everything else: lets use boolean for fallback
+        if (v->bval == true)
+            v->intval = 1;
+        else
+            v->intval = 0;
+    }
+
+    return v;
 }//end: makeValue()
 
 
-static bool configParse(raconf inst,  const char *fileName){
-	FILE *fp;
-	char line[4096];
-	char currentSection[SECTION_LEN];
-	char *p;
-	char c;
-	int linecnt;
-	size_t linelen;
-	size_t currentSection_len;
-	
-	fp = fopen(fileName, "r");
-	if(fp == NULL){
-		ShowError("configParse: cannot open '%s' for reading.\n", fileName);
-		return false;
-	}
-	
-
-	// Start with empty section:
-	currentSection[0] = '\0';
-	currentSection_len = 0;
-	
-	// 	
-	linecnt = 0;
-	while(1){
-		linecnt++;
-		
-		if(fgets(line, sizeof(line), fp) != line)
-			break;
-
-		linelen = strlen(line);
-		p = line;
-		
-		// Skip whitespaces from beginning (space and tab)
-		_line_begin_skip_whities:
-		c = *p;
-		if(c == ' ' || c == '\t'){
-			p++; 
-			linelen--;
-			goto _line_begin_skip_whities;
-		}
-		
-		// Remove linebreaks as (cr or lf) and whitespaces from line end!
-		_line_end_skip_whities_and_breaks:
-		c = p[linelen-1];
-		if(c == '\r' || c == '\n' || c == ' ' || c == '\t'){
-			p[--linelen] = '\0';
-			goto _line_end_skip_whities_and_breaks;
-		}
-		
-		// Empty line? 
-		// or line starts with comment (commented out)?
-		if(linelen == 0 || (p[0] == '/' && p[1] == '/') || p[0] == ';')
-			continue;
-		
-		// Variable names can contain:
-		// A-Za-z-_.0-9
-		//
-		// Sections start with [ .. ] (INI Style)
-		//
-		c = *p;
-		
-		// check what we have.. :)
-		if(c == '['){ // got section!
-			// Got Section!
-			// Search for ] 
-			char *start = (p+1);
-			
-			while(1){
-				++p;
-				c = *p;
-				
-				if(c == '\0'){
-					ShowError("Syntax Error: unterminated Section name in %s:%u (expected ']')\n", fileName, linecnt);
-					fclose(fp);
-					return false;
-				}else if(c == ']'){ // closing backet (section name termination)
-					if( (p - start + 1) > (sizeof(currentSection) ) ){
-						ShowError("Syntax Error: Section name in %s:%u is too large (max Supported length: %u chars)\n", fileName, linecnt, sizeof(currentSection)-1);
-						fclose(fp);
-						return false;
-					}
-					
-					// Set section!
-					*p = '\0'; // add termination here.
-					memcpy(currentSection, start, (p-start)+1 ); // we'll copy \0, too! (we replaced the ] backet with \0.)
-					currentSection_len = (p-start);
-					
-					break;
-					
-				}else if( (c >= '0' && c <= '9') || (c == '-') || (c == ' ') || (c == '_') || (c == '.') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ){
-					// skip .. (allowed char / specifier)
-					continue;
-				}else{
-					ShowError("Syntax Error: Invalid Character '%c' in %s:%u (offset %u) for Section name.\n", c, fileName, linecnt, (p-line));
-					fclose(fp);
-					return false;
-				}
-				
-			}//endwhile: parse section name 
-			
-		
-		}else if( (c >= '0' && c <= '9') || (c == '-') || (c == '_') || (c == '.') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ){
-			// Got variable! 
-			// Search for '=' or ':' wich termiantes the name 
-			char *start = p;
-			char *valuestart = NULL;
-			size_t start_len;
-						
-			while(1){
-				++p;
-				c = *p;
-				
-				if(c == '\0'){
-					ShowError("Syntax Error: unterminated Variable name in %s:%u\n", fileName, linecnt);
-					fclose(fp);
-					return false;
-				}else if( (c == '=') || (c == ':') ){
-					// got name termination
-					
-					*p = '\0'; // Terminate it so  (start) will hold the pointer to the name.
-					
-					break;
-					
-				}else if( (c >= '0' && c <= '9') || (c == '-') || (c == '_') || (c == '.') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ){
-					// skip .. allowed char 
-					continue;
-				}else{
-					ShowError("Syntax Error: Invalid Character '%c' in %s:%u (offset %u) for Variable name.\n", c, fileName, linecnt, (p-line));
-					fclose(fp);
-					return false;
-				}
-				
-			}//endwhile: parse var name			
-			
-			start_len = (p-start);
-			if(start_len >= VARNAME_LEN){
-				ShowError("%s:%u Variable length exceeds limit of %u Characters.\n", fileName, linecnt, VARNAME_LEN-1);
-				fclose(fp);
-				return false;
-			}else if(start_len == 0){
-				ShowError("%s:%u Empty Variable name is not allowed.\n", fileName, linecnt);
-				fclose(fp);
-				return false;
-			}
-			
-			
-			valuestart = (p+1); 
-			
-			
-			// Skip whitespace from begin of value (tab and space)
-			_skip_value_begin_whities:
-			c = *valuestart; 
-			if(c == ' ' || c == '\t'){
-				valuestart++;
-				goto _skip_value_begin_whities;
-			}
-			
-			// Scan for value termination, 
-			// wich can be \0  or  comment start (// or ; (INI) )
-			//
-			p = valuestart;
-			while(1){
-				c = *p;
-				if(c == '\0'){
-					// Terminated by line end.
-					break;
-				}else if(c == '/' && p[1] == '/'){
-					// terminated by c++ style comment.
-					*p = '\0';
-					break;
-				}else if(c == ';'){
-					// terminated by ini style comment.
-					*p = '\0';
-					break;
-				}
-				
-				p++;
-			}//endwhile: search var value end.
-						
-			
-			// Strip whitespaces from end of value.
-			if(valuestart != p){ // not empty!
-				p--;
-				_strip_value_end_whities: 
-				c = *p;
-				if(c == ' ' || c == '\t'){
-					*p = '\0';
-					p--;
-					goto _strip_value_end_whities;
-				}
-				p++;
-			}					
-			
-			
-			// Buildin Hook:
-			if( stricmp(start, "import") == 0){
-				if( configParse(inst, valuestart) != true){
-					ShowError("%s:%u - Import of '%s' failed!\n", fileName, linecnt, valuestart);
-				}
-			}else{
-				// put it to db.
-				struct conf_value *v, *o;
-				char key[ (SECTION_LEN+VARNAME_LEN+1+1) ]; //+1 for delimiter, +1 for termination.
-				size_t section_len;
-				
-				if(*currentSection == '\0'){ // empty / none
-					strncpy(key, "<unnamed>",9);
-					section_len = 9;
-				}else{
-					strncpy(key, currentSection, currentSection_len);
-					section_len = currentSection_len;
-				}
-				
-				key[section_len] = '.'; // Delim
-				
-				strncpy(&key[section_len+1],  start, start_len);
-				
-				key[section_len + start_len + 1] = '\0'; 
-
-				
-				v = makeValue(key, valuestart, (p-valuestart) );				
-				
-				// Try to get the old one before
-				o = strdb_get(inst->db, key);
-				if(o != NULL){
-					strdb_remove(inst->db, key);
-					aFree(o); //			
-				}
-				
-				strdb_put( inst->db, key,  v);
-			}								
-			
-			
-		}else{
-			ShowError("Syntax Error: unexpected Character '%c' in %s:%u (offset %u)\n", c, fileName, linecnt, (p-line) );
-			fclose(fp);
-			return false;
-		}
-		
-		
-		
-	}
-	
-	
-	
-	fclose(fp);
-	return true;
+static bool configParse(raconf inst,  const char *fileName)
+{
+    FILE *fp;
+    char line[4096];
+    char currentSection[SECTION_LEN];
+    char *p;
+    char c;
+    int linecnt;
+    size_t linelen;
+    size_t currentSection_len;
+
+    fp = fopen(fileName, "r");
+    if (fp == NULL) {
+        ShowError("configParse: cannot open '%s' for reading.\n", fileName);
+        return false;
+    }
+
+
+    // Start with empty section:
+    currentSection[0] = '\0';
+    currentSection_len = 0;
+
+    //
+    linecnt = 0;
+    while (1) {
+        linecnt++;
+
+        if (fgets(line, sizeof(line), fp) != line)
+            break;
+
+        linelen = strlen(line);
+        p = line;
+
+        // Skip whitespaces from beginning (space and tab)
+    _line_begin_skip_whities:
+        c = *p;
+        if (c == ' ' || c == '\t') {
+            p++;
+            linelen--;
+            goto _line_begin_skip_whities;
+        }
+
+        // Remove linebreaks as (cr or lf) and whitespaces from line end!
+    _line_end_skip_whities_and_breaks:
+        c = p[linelen-1];
+        if (c == '\r' || c == '\n' || c == ' ' || c == '\t') {
+            p[--linelen] = '\0';
+            goto _line_end_skip_whities_and_breaks;
+        }
+
+        // Empty line?
+        // or line starts with comment (commented out)?
+        if (linelen == 0 || (p[0] == '/' && p[1] == '/') || p[0] == ';')
+            continue;
+
+        // Variable names can contain:
+        // A-Za-z-_.0-9
+        //
+        // Sections start with [ .. ] (INI Style)
+        //
+        c = *p;
+
+        // check what we have.. :)
+        if (c == '[') { // got section!
+            // Got Section!
+            // Search for ]
+            char *start = (p+1);
+
+            while (1) {
+                ++p;
+                c = *p;
+
+                if (c == '\0') {
+                    ShowError("Syntax Error: unterminated Section name in %s:%u (expected ']')\n", fileName, linecnt);
+                    fclose(fp);
+                    return false;
+                } else if (c == ']') { // closing backet (section name termination)
+                    if ((p - start + 1) > (sizeof(currentSection))) {
+                        ShowError("Syntax Error: Section name in %s:%u is too large (max Supported length: %u chars)\n", fileName, linecnt, sizeof(currentSection)-1);
+                        fclose(fp);
+                        return false;
+                    }
+
+                    // Set section!
+                    *p = '\0'; // add termination here.
+                    memcpy(currentSection, start, (p-start)+1);  // we'll copy \0, too! (we replaced the ] backet with \0.)
+                    currentSection_len = (p-start);
+
+                    break;
+
+                } else if ((c >= '0' && c <= '9') || (c == '-') || (c == ' ') || (c == '_') || (c == '.') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+                    // skip .. (allowed char / specifier)
+                    continue;
+                } else {
+                    ShowError("Syntax Error: Invalid Character '%c' in %s:%u (offset %u) for Section name.\n", c, fileName, linecnt, (p-line));
+                    fclose(fp);
+                    return false;
+                }
+
+            }//endwhile: parse section name
+
+
+        } else if ((c >= '0' && c <= '9') || (c == '-') || (c == '_') || (c == '.') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+            // Got variable!
+            // Search for '=' or ':' wich termiantes the name
+            char *start = p;
+            char *valuestart = NULL;
+            size_t start_len;
+
+            while (1) {
+                ++p;
+                c = *p;
+
+                if (c == '\0') {
+                    ShowError("Syntax Error: unterminated Variable name in %s:%u\n", fileName, linecnt);
+                    fclose(fp);
+                    return false;
+                } else if ((c == '=') || (c == ':')) {
+                    // got name termination
+
+                    *p = '\0'; // Terminate it so  (start) will hold the pointer to the name.
+
+                    break;
+
+                } else if ((c >= '0' && c <= '9') || (c == '-') || (c == '_') || (c == '.') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+                    // skip .. allowed char
+                    continue;
+                } else {
+                    ShowError("Syntax Error: Invalid Character '%c' in %s:%u (offset %u) for Variable name.\n", c, fileName, linecnt, (p-line));
+                    fclose(fp);
+                    return false;
+                }
+
+            }//endwhile: parse var name
+
+            start_len = (p-start);
+            if (start_len >= VARNAME_LEN) {
+                ShowError("%s:%u Variable length exceeds limit of %u Characters.\n", fileName, linecnt, VARNAME_LEN-1);
+                fclose(fp);
+                return false;
+            } else if (start_len == 0) {
+                ShowError("%s:%u Empty Variable name is not allowed.\n", fileName, linecnt);
+                fclose(fp);
+                return false;
+            }
+
+
+            valuestart = (p+1);
+
+
+            // Skip whitespace from begin of value (tab and space)
+        _skip_value_begin_whities:
+            c = *valuestart;
+            if (c == ' ' || c == '\t') {
+                valuestart++;
+                goto _skip_value_begin_whities;
+            }
+
+            // Scan for value termination,
+            // wich can be \0  or  comment start (// or ; (INI) )
+            //
+            p = valuestart;
+            while (1) {
+                c = *p;
+                if (c == '\0') {
+                    // Terminated by line end.
+                    break;
+                } else if (c == '/' && p[1] == '/') {
+                    // terminated by c++ style comment.
+                    *p = '\0';
+                    break;
+                } else if (c == ';') {
+                    // terminated by ini style comment.
+                    *p = '\0';
+                    break;
+                }
+
+                p++;
+            }//endwhile: search var value end.
+
+
+            // Strip whitespaces from end of value.
+            if (valuestart != p) { // not empty!
+                p--;
+            _strip_value_end_whities:
+                c = *p;
+                if (c == ' ' || c == '\t') {
+                    *p = '\0';
+                    p--;
+                    goto _strip_value_end_whities;
+                }
+                p++;
+            }
+
+
+            // Buildin Hook:
+            if (stricmp(start, "import") == 0) {
+                if (configParse(inst, valuestart) != true) {
+                    ShowError("%s:%u - Import of '%s' failed!\n", fileName, linecnt, valuestart);
+                }
+            } else {
+                // put it to db.
+                struct conf_value *v, *o;
+                char key[(SECTION_LEN+VARNAME_LEN+1+1) ];  //+1 for delimiter, +1 for termination.
+                size_t section_len;
+
+                if (*currentSection == '\0') { // empty / none
+                    strncpy(key, "<unnamed>",9);
+                    section_len = 9;
+                } else {
+                    strncpy(key, currentSection, currentSection_len);
+                    section_len = currentSection_len;
+                }
+
+                key[section_len] = '.'; // Delim
+
+                strncpy(&key[section_len+1],  start, start_len);
+
+                key[section_len + start_len + 1] = '\0';
+
+
+                v = makeValue(key, valuestart, (p-valuestart));
+
+                // Try to get the old one before
+                o = strdb_get(inst->db, key);
+                if (o != NULL) {
+                    strdb_remove(inst->db, key);
+                    aFree(o); //
+                }
+
+                strdb_put(inst->db, key,  v);
+            }
+
+
+        } else {
+            ShowError("Syntax Error: unexpected Character '%c' in %s:%u (offset %u)\n", c, fileName, linecnt, (p-line));
+            fclose(fp);
+            return false;
+        }
+
+
+
+    }
+
+
+
+    fclose(fp);
+    return true;
 }//end: configParse()
 
 
 #define MAKEKEY(dest, section, key) { size_t section_len, key_len; \
-										if(section == NULL || *section == '\0'){ \
-											strncpy(dest, "<unnamed>", 9); \
-											section_len = 9; \
-										}else{ \
-											section_len = strlen(section); \
-											strncpy(dest, section, section_len); \
-										} \
-										\
-										dest[section_len] = '.'; \
-										\
-										key_len = strlen(key); \
-										strncpy(&dest[section_len+1],  key,  key_len); \
-										dest[section_len + key_len + 1] = '\0'; \
-									}
-										
-
-raconf  raconf_parse(const char *file_name){
-	struct raconf *rc;
-	
-	rc = aCalloc(1, sizeof(struct raconf) );
-	if(rc == NULL){
-		ShowFatalError("raconf_parse: failed to allocate memory for new handle\n");
-		return NULL;
-	}
-
-	rc->db = strdb_alloc(DB_OPT_BASE | DB_OPT_DUP_KEY, 98);	
-	//
-	
-	if(configParse(rc, file_name) != true){
-		ShowError("Failed to Parse Configuration file '%s'\n", file_name);
-	}
-	
-	return rc;
+        if(section == NULL || *section == '\0'){ \
+            strncpy(dest, "<unnamed>", 9); \
+            section_len = 9; \
+        }else{ \
+            section_len = strlen(section); \
+            strncpy(dest, section, section_len); \
+        } \
+        \
+        dest[section_len] = '.'; \
+        \
+        key_len = strlen(key); \
+        strncpy(&dest[section_len+1],  key,  key_len); \
+        dest[section_len + key_len + 1] = '\0'; \
+    }
+
+
+raconf  raconf_parse(const char *file_name)
+{
+    struct raconf *rc;
+
+    rc = aCalloc(1, sizeof(struct raconf));
+    if (rc == NULL) {
+        ShowFatalError("raconf_parse: failed to allocate memory for new handle\n");
+        return NULL;
+    }
+
+    rc->db = strdb_alloc(DB_OPT_BASE | DB_OPT_DUP_KEY, 98);
+    //
+
+    if (configParse(rc, file_name) != true) {
+        ShowError("Failed to Parse Configuration file '%s'\n", file_name);
+    }
+
+    return rc;
 }//end: raconf_parse()
 
 
-void raconf_destroy(raconf rc){
-	DBIterator *iter;
-	struct conf_value *v;
-	
-	// Clear all entrys in db.
-	iter = db_iterator(rc->db);
-	for( v = (struct conf_value*)dbi_first(iter);  dbi_exists(iter);  v = (struct conf_value*)dbi_next(iter) ){
-		aFree(v);
-	}
-	dbi_destroy(iter);
-
-	db_destroy(rc->db);
-	
-	aFree(rc);	
-	
+void raconf_destroy(raconf rc)
+{
+    DBIterator *iter;
+    struct conf_value *v;
+
+    // Clear all entrys in db.
+    iter = db_iterator(rc->db);
+    for (v = (struct conf_value *)dbi_first(iter);  dbi_exists(iter);  v = (struct conf_value *)dbi_next(iter)) {
+        aFree(v);
+    }
+    dbi_destroy(iter);
+
+    db_destroy(rc->db);
+
+    aFree(rc);
+
 }//end: raconf_destroy()
 
-bool raconf_getbool(raconf rc, const char *section, const char *key,  bool _default){
-	char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
-	struct conf_value *v;
-	
-	MAKEKEY(keystr, section, key);
-
-	v = strdb_get(rc->db, keystr);
-	if(v == NULL)
-		return _default;
-	else
-		return v->bval;
+bool raconf_getbool(raconf rc, const char *section, const char *key,  bool _default)
+{
+    char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
+    struct conf_value *v;
+
+    MAKEKEY(keystr, section, key);
+
+    v = strdb_get(rc->db, keystr);
+    if (v == NULL)
+        return _default;
+    else
+        return v->bval;
 }//end: raconf_getbool()
 
 
-float raconf_getfloat(raconf rc,const char *section, const char *key, float _default){
-	char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
-	struct conf_value *v;
-	
-	MAKEKEY(keystr, section, key);
+float raconf_getfloat(raconf rc,const char *section, const char *key, float _default)
+{
+    char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
+    struct conf_value *v;
+
+    MAKEKEY(keystr, section, key);
 
-	v = strdb_get(rc->db, keystr);
-	if(v == NULL)
-		return _default;
-	else
-		return (float)v->floatval;
+    v = strdb_get(rc->db, keystr);
+    if (v == NULL)
+        return _default;
+    else
+        return (float)v->floatval;
 }//end: raconf_getfloat()
 
 
-int64 raconf_getint(raconf rc,  const char *section, const char *key, int64 _default){
-	char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
-	struct conf_value *v;
-	
-	MAKEKEY(keystr, section, key);
-	
-	v = strdb_get(rc->db, keystr);
-	if(v == NULL)
-		return _default;
-	else
-		return v->intval;
+int64 raconf_getint(raconf rc,  const char *section, const char *key, int64 _default)
+{
+    char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
+    struct conf_value *v;
+
+    MAKEKEY(keystr, section, key);
+
+    v = strdb_get(rc->db, keystr);
+    if (v == NULL)
+        return _default;
+    else
+        return v->intval;
 
 }//end: raconf_getint()
 
 
-const char* raconf_getstr(raconf rc,  const char *section, const char *key, const char *_default){
-	char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
-	struct conf_value *v;
+const char *raconf_getstr(raconf rc,  const char *section, const char *key, const char *_default)
+{
+    char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
+    struct conf_value *v;
 
-	MAKEKEY(keystr, section, key);	
+    MAKEKEY(keystr, section, key);
 
-	v = strdb_get(rc->db, keystr);
-	if(v == NULL)
-		return _default;
-	else
-		return v->strval;
+    v = strdb_get(rc->db, keystr);
+    if (v == NULL)
+        return _default;
+    else
+        return v->strval;
 }//end: raconf_getstr()
 
 
-bool raconf_getboolEx(raconf rc, const char *section, const char *fallback_section, const char *key, bool _default){
-	char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
-	struct conf_value *v;
-	
-	MAKEKEY(keystr, section, key);
-	v = strdb_get(rc->db, keystr);
-	if(v == NULL){
-		
-		MAKEKEY(keystr, fallback_section, key);
-		v = strdb_get(rc->db, keystr);
-		if(v == NULL){
-			return _default;
-		}else{
-			return v->bval;
-		}
-		
-	}else{
-		return v->bval;
-	}
+bool raconf_getboolEx(raconf rc, const char *section, const char *fallback_section, const char *key, bool _default)
+{
+    char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
+    struct conf_value *v;
+
+    MAKEKEY(keystr, section, key);
+    v = strdb_get(rc->db, keystr);
+    if (v == NULL) {
+
+        MAKEKEY(keystr, fallback_section, key);
+        v = strdb_get(rc->db, keystr);
+        if (v == NULL) {
+            return _default;
+        } else {
+            return v->bval;
+        }
+
+    } else {
+        return v->bval;
+    }
 }//end: raconf_getboolEx()
 
 
-float raconf_getfloatEx(raconf rc,const char *section, const char *fallback_section, const char *key, float _default){
-	char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
-	struct conf_value *v;
-	
-	MAKEKEY(keystr, section, key);
-	v = strdb_get(rc->db, keystr);
-	if(v == NULL){
-		
-		MAKEKEY(keystr, fallback_section, key);
-		v = strdb_get(rc->db, keystr);
-		if(v == NULL){
-			return _default;
-		}else{
-			return (float)v->floatval;
-		}
-		
-	}else{
-		return (float)v->floatval;
-	}
-	
+float raconf_getfloatEx(raconf rc,const char *section, const char *fallback_section, const char *key, float _default)
+{
+    char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
+    struct conf_value *v;
+
+    MAKEKEY(keystr, section, key);
+    v = strdb_get(rc->db, keystr);
+    if (v == NULL) {
+
+        MAKEKEY(keystr, fallback_section, key);
+        v = strdb_get(rc->db, keystr);
+        if (v == NULL) {
+            return _default;
+        } else {
+            return (float)v->floatval;
+        }
+
+    } else {
+        return (float)v->floatval;
+    }
+
 }//end: raconf_getfloatEx()
 
 
-int64 raconf_getintEx(raconf rc,  const char *section, const char *fallback_section, const char *key, int64 _default){
-	char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
-	struct conf_value *v;
-	
-	MAKEKEY(keystr, section, key);
-	v = strdb_get(rc->db, keystr);
-	if(v == NULL){
-		
-		MAKEKEY(keystr, fallback_section, key);
-		v = strdb_get(rc->db, keystr);
-		if(v == NULL){
-			return _default;
-		}else{
-			return v->intval;
-		}
-		
-	}else{
-		return v->intval;
-	}
+int64 raconf_getintEx(raconf rc,  const char *section, const char *fallback_section, const char *key, int64 _default)
+{
+    char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
+    struct conf_value *v;
+
+    MAKEKEY(keystr, section, key);
+    v = strdb_get(rc->db, keystr);
+    if (v == NULL) {
+
+        MAKEKEY(keystr, fallback_section, key);
+        v = strdb_get(rc->db, keystr);
+        if (v == NULL) {
+            return _default;
+        } else {
+            return v->intval;
+        }
+
+    } else {
+        return v->intval;
+    }
 
 }//end: raconf_getintEx()
 
 
-const char* raconf_getstrEx(raconf rc,  const char *section, const char *fallback_section, const char *key, const char *_default){
-	char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
-	struct conf_value *v;
-	
-	MAKEKEY(keystr, section, key);
-	v = strdb_get(rc->db, keystr);
-	if(v == NULL){
-		
-		MAKEKEY(keystr, fallback_section, key);
-		v = strdb_get(rc->db, keystr);
-		if(v == NULL){
-			return _default;
-		}else{
-			return v->strval;
-		}
-		
-	}else{
-		return v->strval;
-	}
+const char *raconf_getstrEx(raconf rc,  const char *section, const char *fallback_section, const char *key, const char *_default)
+{
+    char keystr[SECTION_LEN + VARNAME_LEN + 1 + 1];
+    struct conf_value *v;
+
+    MAKEKEY(keystr, section, key);
+    v = strdb_get(rc->db, keystr);
+    if (v == NULL) {
+
+        MAKEKEY(keystr, fallback_section, key);
+        v = strdb_get(rc->db, keystr);
+        if (v == NULL) {
+            return _default;
+        } else {
+            return v->strval;
+        }
+
+    } else {
+        return v->strval;
+    }
 
 }//end: raconf_getstrEx()

+ 17 - 17
src/common/raconf.h

@@ -7,52 +7,52 @@
 #include "../common/cbasetypes.h"
 
 // rAthena generic configuration file parser
-// 
-//  Config file Syntax is athena style 
-//	extended with ini style support (including sections)
 //
-//	Comments are started with // or ; (ini style)
+//  Config file Syntax is athena style
+//  extended with ini style support (including sections)
+//
+//  Comments are started with // or ; (ini style)
 //
 
 typedef struct raconf *raconf;
 
 
-/** 
+/**
  * Parses a rAthna Configuration file
- * 
+ *
  * @param file_name path to the file to parse
  *
  * @returns not NULL incase of success
  */
-raconf	raconf_parse(const char *file_name);
+raconf  raconf_parse(const char *file_name);
 
 
-/** 
+/**
  * Frees a Handle received from raconf_parse
  *
  * @param rc - the handle to free
  */
-void	raconf_destroy(raconf rc);
+void    raconf_destroy(raconf rc);
 
 
-/** 
- * Gets the value for Section / Key pair, if key not exists returns _default! 
+/**
+ * Gets the value for Section / Key pair, if key not exists returns _default!
  *
  */
-bool 		raconf_getbool(raconf rc, const char *section, const char *key,	bool _default);
-float		raconf_getfloat(raconf rc,const char *section, const char *key, float _default);
-int64		raconf_getint(raconf rc,  const char *section, const char *key, int64 _default);  
-const char*	raconf_getstr(raconf rc,  const char *section, const char *key, const char *_default);
+bool        raconf_getbool(raconf rc, const char *section, const char *key, bool _default);
+float       raconf_getfloat(raconf rc,const char *section, const char *key, float _default);
+int64       raconf_getint(raconf rc,  const char *section, const char *key, int64 _default);
+const char *raconf_getstr(raconf rc,  const char *section, const char *key, const char *_default);
 
 /**
- * Gets the value for Section / Key pair, but has fallback section option if not found in section, 
+ * Gets the value for Section / Key pair, but has fallback section option if not found in section,
  * if not found in both - default gets returned.
  *
  */
 bool        raconf_getboolEx(raconf rc, const char *section, const char *fallback_section, const char *key, bool _default);
 float       raconf_getfloatEx(raconf rc,const char *section, const char *fallback_section, const char *key, float _default);
 int64       raconf_getintEx(raconf rc,  const char *section, const char *fallback_section, const char *key, int64 _default);
-const char* raconf_getstrEx(raconf rc,  const char *section, const char *fallback_section, const char *key, const char *_default);
+const char *raconf_getstrEx(raconf rc,  const char *section, const char *fallback_section, const char *key, const char *_default);
 
 
 

+ 18 - 18
src/common/random.c

@@ -5,10 +5,10 @@
 #include "../common/timer.h" // gettick
 #include "random.h"
 #if defined(WIN32)
-	#include "../common/winapi.h"
+#include "../common/winapi.h"
 #elif defined(HAVE_GETPID) || defined(HAVE_GETTID)
-	#include <sys/types.h>
-	#include <unistd.h>
+#include <sys/types.h>
+#include <unistd.h>
 #endif
 #include <time.h> // time
 #include <mt19937ar.h> // init_genrand, genrand_int32, genrand_res53
@@ -17,34 +17,34 @@
 /// Initializes the random number generator with an appropriate seed.
 void rnd_init(void)
 {
-	uint32 seed = gettick();
-	seed += (uint32)time(NULL);
+    uint32 seed = gettick();
+    seed += (uint32)time(NULL);
 #if defined(WIN32)
-	seed += GetCurrentProcessId();
-	seed += GetCurrentThreadId();
+    seed += GetCurrentProcessId();
+    seed += GetCurrentThreadId();
 #else
 #if defined(HAVE_GETPID)
-	seed += (uint32)getpid();
+    seed += (uint32)getpid();
 #endif // HAVE_GETPID
 #if defined(HAVE_GETTID)
-	seed += (uint32)gettid();
+    seed += (uint32)gettid();
 #endif // HAVE_GETTID
 #endif
-	init_genrand(seed);
+    init_genrand(seed);
 }
 
 
 /// Initializes the random number generator.
 void rnd_seed(uint32 seed)
 {
-	init_genrand(seed);
+    init_genrand(seed);
 }
 
 
 /// Generates a random number in the interval [0, SINT32_MAX]
 int32 rnd(void)
 {
-	return (int32)genrand_int31();
+    return (int32)genrand_int31();
 }
 
 
@@ -52,7 +52,7 @@ int32 rnd(void)
 /// NOTE: interval is open ended, so dice_faces is excluded (unless it's 0)
 uint32 rnd_roll(uint32 dice_faces)
 {
-	return (uint32)(rnd_uniform()*dice_faces);
+    return (uint32)(rnd_uniform()*dice_faces);
 }
 
 
@@ -60,9 +60,9 @@ uint32 rnd_roll(uint32 dice_faces)
 /// Returns min if range is invalid.
 int32 rnd_value(int32 min, int32 max)
 {
-	if( min >= max )
-		return min;
-	return min + (int32)(rnd_uniform()*(max-min+1));
+    if (min >= max)
+        return min;
+    return min + (int32)(rnd_uniform()*(max-min+1));
 }
 
 
@@ -70,7 +70,7 @@ int32 rnd_value(int32 min, int32 max)
 /// NOTE: interval is open ended, so 1.0 is excluded
 double rnd_uniform(void)
 {
-	return ((uint32)genrand_int32())*(1.0/4294967296.0);// divided by 2^32
+    return ((uint32)genrand_int32())*(1.0/4294967296.0);// divided by 2^32
 }
 
 
@@ -79,5 +79,5 @@ double rnd_uniform(void)
 /// NOTE: 53 bits is the maximum precision of a double
 double rnd_uniform53(void)
 {
-	return genrand_res53();
+    return genrand_res53();
 }

File diff suppressed because it is too large
+ 462 - 518
src/common/showmsg.c


+ 52 - 52
src/common/showmsg.h

@@ -14,58 +14,58 @@
 // \033[0m : reset color parameter
 // \033[1m : use bold for font
 
-#define CL_RESET	"\033[0m"
-#define CL_CLS		"\033[2J"
-#define CL_CLL		"\033[K"
+#define CL_RESET    "\033[0m"
+#define CL_CLS      "\033[2J"
+#define CL_CLL      "\033[K"
 
 // font settings
-#define CL_BOLD		"\033[1m"
-#define CL_NORM		CL_RESET
-#define CL_NORMAL	CL_RESET
-#define CL_NONE		CL_RESET
+#define CL_BOLD     "\033[1m"
+#define CL_NORM     CL_RESET
+#define CL_NORMAL   CL_RESET
+#define CL_NONE     CL_RESET
 // foreground color and bold font (bright color on windows)
-#define CL_WHITE	"\033[1;37m"
-#define CL_GRAY		"\033[1;30m"
-#define CL_RED		"\033[1;31m"
-#define CL_GREEN	"\033[1;32m"
-#define CL_YELLOW	"\033[1;33m"
-#define CL_BLUE		"\033[1;34m"
-#define CL_MAGENTA	"\033[1;35m"
-#define CL_CYAN		"\033[1;36m"
+#define CL_WHITE    "\033[1;37m"
+#define CL_GRAY     "\033[1;30m"
+#define CL_RED      "\033[1;31m"
+#define CL_GREEN    "\033[1;32m"
+#define CL_YELLOW   "\033[1;33m"
+#define CL_BLUE     "\033[1;34m"
+#define CL_MAGENTA  "\033[1;35m"
+#define CL_CYAN     "\033[1;36m"
 
 // background color
-#define CL_BG_BLACK		"\033[40m"
-#define CL_BG_RED		"\033[41m"
-#define CL_BG_GREEN		"\033[42m"
-#define CL_BG_YELLOW	"\033[43m"
-#define CL_BG_BLUE		"\033[44m"
-#define CL_BG_MAGENTA	"\033[45m"
-#define CL_BG_CYAN		"\033[46m"
-#define CL_BG_WHITE		"\033[47m"
+#define CL_BG_BLACK     "\033[40m"
+#define CL_BG_RED       "\033[41m"
+#define CL_BG_GREEN     "\033[42m"
+#define CL_BG_YELLOW    "\033[43m"
+#define CL_BG_BLUE      "\033[44m"
+#define CL_BG_MAGENTA   "\033[45m"
+#define CL_BG_CYAN      "\033[46m"
+#define CL_BG_WHITE     "\033[47m"
 // foreground color and normal font (normal color on windows)
-#define CL_LT_BLACK		"\033[0;30m"
-#define CL_LT_RED		"\033[0;31m"
-#define CL_LT_GREEN		"\033[0;32m"
-#define CL_LT_YELLOW	"\033[0;33m"
-#define CL_LT_BLUE		"\033[0;34m"
-#define CL_LT_MAGENTA	"\033[0;35m"
-#define CL_LT_CYAN		"\033[0;36m"
-#define CL_LT_WHITE		"\033[0;37m"
+#define CL_LT_BLACK     "\033[0;30m"
+#define CL_LT_RED       "\033[0;31m"
+#define CL_LT_GREEN     "\033[0;32m"
+#define CL_LT_YELLOW    "\033[0;33m"
+#define CL_LT_BLUE      "\033[0;34m"
+#define CL_LT_MAGENTA   "\033[0;35m"
+#define CL_LT_CYAN      "\033[0;36m"
+#define CL_LT_WHITE     "\033[0;37m"
 // foreground color and bold font (bright color on windows)
-#define CL_BT_BLACK		"\033[1;30m"
-#define CL_BT_RED		"\033[1;31m"
-#define CL_BT_GREEN		"\033[1;32m"
-#define CL_BT_YELLOW	"\033[1;33m"
-#define CL_BT_BLUE		"\033[1;34m"
-#define CL_BT_MAGENTA	"\033[1;35m"
-#define CL_BT_CYAN		"\033[1;36m"
-#define CL_BT_WHITE		"\033[1;37m"
+#define CL_BT_BLACK     "\033[1;30m"
+#define CL_BT_RED       "\033[1;31m"
+#define CL_BT_GREEN     "\033[1;32m"
+#define CL_BT_YELLOW    "\033[1;33m"
+#define CL_BT_BLUE      "\033[1;34m"
+#define CL_BT_MAGENTA   "\033[1;35m"
+#define CL_BT_CYAN      "\033[1;36m"
+#define CL_BT_WHITE     "\033[1;37m"
 
-#define CL_WTBL			"\033[37;44m"	// white on blue
-#define CL_XXBL			"\033[0;44m"	// default on blue
-#define CL_PASS			"\033[0;32;42m"	// green on green
+#define CL_WTBL         "\033[37;44m"   // white on blue
+#define CL_XXBL         "\033[0;44m"    // default on blue
+#define CL_PASS         "\033[0;32;42m" // green on green
 
-#define CL_SPACE		"           "	// space aquivalent of the print messages
+#define CL_SPACE        "           "   // space aquivalent of the print messages
 
 extern int stdout_with_ansisequence; //If the color ansi sequences are to be used. [flaviojs]
 extern int msg_silent; //Specifies how silent the console is. [Skotlex]
@@ -73,15 +73,15 @@ extern int console_msg_log; //Specifies what error messages to log. [Ind]
 extern char timestamp_format[20]; //For displaying Timestamps [Skotlex]
 
 enum msg_type {
-	MSG_NONE,
-	MSG_STATUS,
-	MSG_SQL,
-	MSG_INFORMATION,
-	MSG_NOTICE,
-	MSG_WARNING,
-	MSG_DEBUG,
-	MSG_ERROR,
-	MSG_FATALERROR
+    MSG_NONE,
+    MSG_STATUS,
+    MSG_SQL,
+    MSG_INFORMATION,
+    MSG_NOTICE,
+    MSG_WARNING,
+    MSG_DEBUG,
+    MSG_ERROR,
+    MSG_FATALERROR
 };
 
 extern void ClearScreen(void);

File diff suppressed because it is too large
+ 511 - 519
src/common/socket.c


+ 37 - 38
src/common/socket.h

@@ -1,18 +1,18 @@
 // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
 // For more information, see LICENCE in the main folder
 
-#ifndef	_SOCKET_H_
+#ifndef _SOCKET_H_
 #define _SOCKET_H_
 
 #include "../common/cbasetypes.h"
 
 #ifdef WIN32
-	#include "../common/winapi.h"
-	typedef long in_addr_t;
+#include "../common/winapi.h"
+typedef long in_addr_t;
 #else
-	#include <sys/types.h>
-	#include <sys/socket.h>
-	#include <netinet/in.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
 #endif
 
 #include <time.h>
@@ -38,15 +38,15 @@
 
 #define RFIFOREST(fd)  (session[fd]->flag.eof ? 0 : session[fd]->rdata_size - session[fd]->rdata_pos)
 #define RFIFOFLUSH(fd) \
-	do { \
-		if(session[fd]->rdata_size == session[fd]->rdata_pos){ \
-			session[fd]->rdata_size = session[fd]->rdata_pos = 0; \
-		} else { \
-			session[fd]->rdata_size -= session[fd]->rdata_pos; \
-			memmove(session[fd]->rdata, session[fd]->rdata+session[fd]->rdata_pos, session[fd]->rdata_size); \
-			session[fd]->rdata_pos = 0; \
-		} \
-	} while(0)
+    do { \
+        if(session[fd]->rdata_size == session[fd]->rdata_pos){ \
+            session[fd]->rdata_size = session[fd]->rdata_pos = 0; \
+        } else { \
+            session[fd]->rdata_size -= session[fd]->rdata_pos; \
+            memmove(session[fd]->rdata, session[fd]->rdata+session[fd]->rdata_pos, session[fd]->rdata_size); \
+            session[fd]->rdata_pos = 0; \
+        } \
+    } while(0)
 
 // buffer I/O macros
 #define RBUFP(p,pos) (((uint8*)(p)) + (pos))
@@ -71,33 +71,32 @@ typedef int (*RecvFunc)(int fd);
 typedef int (*SendFunc)(int fd);
 typedef int (*ParseFunc)(int fd);
 
-struct socket_data
-{
-	struct {
-		unsigned char eof : 1;
-		unsigned char server : 1;
-		unsigned char ping : 2;
-	} flag;
+struct socket_data {
+    struct {
+        unsigned char eof : 1;
+        unsigned char server : 1;
+        unsigned char ping : 2;
+    } flag;
 
-	uint32 client_addr; // remote client address
+    uint32 client_addr; // remote client address
 
-	uint8 *rdata, *wdata;
-	size_t max_rdata, max_wdata;
-	size_t rdata_size, wdata_size;
-	size_t rdata_pos;
-	time_t rdata_tick; // time of last recv (for detecting timeouts); zero when timeout is disabled
+    uint8 *rdata, *wdata;
+    size_t max_rdata, max_wdata;
+    size_t rdata_size, wdata_size;
+    size_t rdata_pos;
+    time_t rdata_tick; // time of last recv (for detecting timeouts); zero when timeout is disabled
 
-	RecvFunc func_recv;
-	SendFunc func_send;
-	ParseFunc func_parse;
+    RecvFunc func_recv;
+    SendFunc func_send;
+    ParseFunc func_parse;
 
-	void* session_data; // stores application-specific data related to the session
+    void *session_data; // stores application-specific data related to the session
 };
 
 
 // Data prototype declaration
 
-extern struct socket_data* session[FD_SETSIZE];
+extern struct socket_data *session[FD_SETSIZE];
 
 extern int fd_max;
 
@@ -131,21 +130,21 @@ extern void set_nonblocking(int fd, unsigned long yes);
 void set_defaultparse(ParseFunc defaultparse);
 
 // hostname/ip conversion functions
-uint32 host2ip(const char* hostname);
-const char* ip2str(uint32 ip, char ip_str[16]);
-uint32 str2ip(const char* ip_str);
+uint32 host2ip(const char *hostname);
+const char *ip2str(uint32 ip, char ip_str[16]);
+uint32 str2ip(const char *ip_str);
 #define CONVIP(ip) ((ip)>>24)&0xFF,((ip)>>16)&0xFF,((ip)>>8)&0xFF,((ip)>>0)&0xFF
 #define MAKEIP(a,b,c,d) (uint32)( ( ( (a)&0xFF ) << 24 ) | ( ( (b)&0xFF ) << 16 ) | ( ( (c)&0xFF ) << 8 ) | ( ( (d)&0xFF ) << 0 ) )
 uint16 ntows(uint16 netshort);
 
-int socket_getips(uint32* ips, int max);
+int socket_getips(uint32 *ips, int max);
 
 extern uint32 addr_[16];   // ip addresses of local host (host byte order)
 extern int naddr_;   // # of ip addresses
 
 void set_eof(int fd);
 
-/// Use a shortlist of sockets instead of iterating all sessions for sockets 
+/// Use a shortlist of sockets instead of iterating all sessions for sockets
 /// that have data to send or need eof handling.
 /// Adapted to use a static array instead of a linked list.
 ///

+ 56 - 52
src/common/spinlock.h

@@ -14,7 +14,7 @@
 // For more information, see LICENCE in the main folder
 //
 //
- 
+
 #ifdef WIN32
 #include "../common/winapi.h"
 #endif
@@ -25,77 +25,81 @@
 
 #ifdef WIN32
 
-typedef struct __declspec( align(64) ) SPIN_LOCK{
-	volatile LONG lock;
-	volatile LONG nest;
-	volatile LONG sync_lock;
+typedef struct __declspec(align(64)) SPIN_LOCK {
+    volatile LONG lock;
+    volatile LONG nest;
+    volatile LONG sync_lock;
 }  SPIN_LOCK, *PSPIN_LOCK;
 #else
-typedef struct SPIN_LOCK{
-		volatile int32 lock;
-		volatile int32 nest; // nesting level.
-		
-		volatile int32 sync_lock;
+typedef struct SPIN_LOCK {
+    volatile int32 lock;
+    volatile int32 nest; // nesting level.
+
+    volatile int32 sync_lock;
 } __attribute__((aligned(64))) SPIN_LOCK, *PSPIN_LOCK;
 #endif
 
 
 
-static forceinline void InitializeSpinLock(PSPIN_LOCK lck){
-		lck->lock = 0;
-		lck->nest = 0;
-		lck->sync_lock = 0;
+static forceinline void InitializeSpinLock(PSPIN_LOCK lck)
+{
+    lck->lock = 0;
+    lck->nest = 0;
+    lck->sync_lock = 0;
 }
 
-static forceinline void FinalizeSpinLock(PSPIN_LOCK lck){
-		return;
+static forceinline void FinalizeSpinLock(PSPIN_LOCK lck)
+{
+    return;
 }
 
 
 #define getsynclock(l) { while(1){ if(InterlockedCompareExchange(l, 1, 0) == 0) break; rathread_yield(); } }
 #define dropsynclock(l) { InterlockedExchange(l, 0); }
 
-static forceinline void EnterSpinLock(PSPIN_LOCK lck){
-		int tid = rathread_get_tid();
-		
-		// Get Sync Lock && Check if the requester thread already owns the lock. 
-		// if it owns, increase nesting level
-		getsynclock(&lck->sync_lock);
-		if(InterlockedCompareExchange(&lck->lock, tid, tid) == tid){
-				InterlockedIncrement(&lck->nest);
-				dropsynclock(&lck->sync_lock);
-				return; // Got Lock
-		}
-		// drop sync lock
-		dropsynclock(&lck->sync_lock);
-		
-		
-		// Spin until we've got it ! 
-		while(1){
-				
-				if(InterlockedCompareExchange(&lck->lock, tid, 0) == 0){
-						
-						InterlockedIncrement(&lck->nest);
-						return; // Got Lock
-				}
-				
-				rathread_yield(); // Force ctxswitch to another thread.
-		}
+static forceinline void EnterSpinLock(PSPIN_LOCK lck)
+{
+    int tid = rathread_get_tid();
+
+    // Get Sync Lock && Check if the requester thread already owns the lock.
+    // if it owns, increase nesting level
+    getsynclock(&lck->sync_lock);
+    if (InterlockedCompareExchange(&lck->lock, tid, tid) == tid) {
+        InterlockedIncrement(&lck->nest);
+        dropsynclock(&lck->sync_lock);
+        return; // Got Lock
+    }
+    // drop sync lock
+    dropsynclock(&lck->sync_lock);
+
+
+    // Spin until we've got it !
+    while (1) {
+
+        if (InterlockedCompareExchange(&lck->lock, tid, 0) == 0) {
+
+            InterlockedIncrement(&lck->nest);
+            return; // Got Lock
+        }
+
+        rathread_yield(); // Force ctxswitch to another thread.
+    }
 
 }
 
 
-static forceinline void LeaveSpinLock(PSPIN_LOCK lck){
-		int tid = rathread_get_tid();
+static forceinline void LeaveSpinLock(PSPIN_LOCK lck)
+{
+    int tid = rathread_get_tid();
+
+    getsynclock(&lck->sync_lock);
+
+    if (InterlockedCompareExchange(&lck->lock, tid, tid) == tid) { // this thread owns the lock.
+        if (InterlockedDecrement(&lck->nest) == 0)
+            InterlockedExchange(&lck->lock, 0); // Unlock!
+    }
 
-		getsynclock(&lck->sync_lock);
-		
-		if(InterlockedCompareExchange(&lck->lock, tid, tid) == tid){ // this thread owns the lock.
-			if(InterlockedDecrement(&lck->nest) == 0)
-					InterlockedExchange(&lck->lock, 0); // Unlock!
-		}
-		
-		dropsynclock(&lck->sync_lock);
+    dropsynclock(&lck->sync_lock);
 }
 
 

+ 600 - 616
src/common/sql.c

@@ -18,41 +18,38 @@
 
 
 /// Sql handle
-struct Sql
-{
-	StringBuf buf;
-	MYSQL handle;
-	MYSQL_RES* result;
-	MYSQL_ROW row;
-	unsigned long* lengths;
-	int keepalive;
+struct Sql {
+    StringBuf buf;
+    MYSQL handle;
+    MYSQL_RES *result;
+    MYSQL_ROW row;
+    unsigned long *lengths;
+    int keepalive;
 };
 
 
 
 // Column length receiver.
 // Takes care of the possible size missmatch between uint32 and unsigned long.
-struct s_column_length
-{
-	uint32* out_length;
-	unsigned long length;
+struct s_column_length {
+    uint32 *out_length;
+    unsigned long length;
 };
 typedef struct s_column_length s_column_length;
 
 
 
 /// Sql statement
-struct SqlStmt
-{
-	StringBuf buf;
-	MYSQL_STMT* stmt;
-	MYSQL_BIND* params;
-	MYSQL_BIND* columns;
-	s_column_length* column_lengths;
-	size_t max_params;
-	size_t max_columns;
-	bool bind_params;
-	bool bind_columns;
+struct SqlStmt {
+    StringBuf buf;
+    MYSQL_STMT *stmt;
+    MYSQL_BIND *params;
+    MYSQL_BIND *columns;
+    s_column_length *column_lengths;
+    size_t max_params;
+    size_t max_columns;
+    bool bind_params;
+    bool bind_columns;
 };
 
 
@@ -64,117 +61,111 @@ struct SqlStmt
 
 
 /// Allocates and initializes a new Sql handle.
-Sql* Sql_Malloc(void)
+Sql *Sql_Malloc(void)
 {
-	Sql* self;
+    Sql *self;
 
-	CREATE(self, Sql, 1);
-	mysql_init(&self->handle);
-	StringBuf_Init(&self->buf);
-	self->lengths = NULL;
-	self->result = NULL;
-	self->keepalive = INVALID_TIMER;
+    CREATE(self, Sql, 1);
+    mysql_init(&self->handle);
+    StringBuf_Init(&self->buf);
+    self->lengths = NULL;
+    self->result = NULL;
+    self->keepalive = INVALID_TIMER;
 
-	return self;
+    return self;
 }
 
 
 
-static int Sql_P_Keepalive(Sql* self);
+static int Sql_P_Keepalive(Sql *self);
 
 /// Establishes a connection.
-int Sql_Connect(Sql* self, const char* user, const char* passwd, const char* host, uint16 port, const char* db)
+int Sql_Connect(Sql *self, const char *user, const char *passwd, const char *host, uint16 port, const char *db)
 {
-	if( self == NULL )
-		return SQL_ERROR;
+    if (self == NULL)
+        return SQL_ERROR;
 
-	StringBuf_Clear(&self->buf);
-	if( !mysql_real_connect(&self->handle, host, user, passwd, db, (unsigned int)port, NULL/*unix_socket*/, 0/*clientflag*/) )
-	{
-		ShowSQL("%s\n", mysql_error(&self->handle));
-		return SQL_ERROR;
-	}
+    StringBuf_Clear(&self->buf);
+    if (!mysql_real_connect(&self->handle, host, user, passwd, db, (unsigned int)port, NULL/*unix_socket*/, 0/*clientflag*/)) {
+        ShowSQL("%s\n", mysql_error(&self->handle));
+        return SQL_ERROR;
+    }
 
-	self->keepalive = Sql_P_Keepalive(self);
-	if( self->keepalive == INVALID_TIMER )
-	{
-		ShowSQL("Failed to establish keepalive for DB connection!\n");
-		return SQL_ERROR;
-	}
+    self->keepalive = Sql_P_Keepalive(self);
+    if (self->keepalive == INVALID_TIMER) {
+        ShowSQL("Failed to establish keepalive for DB connection!\n");
+        return SQL_ERROR;
+    }
 
-	return SQL_SUCCESS;
+    return SQL_SUCCESS;
 }
 
 
 
 /// Retrieves the timeout of the connection.
-int Sql_GetTimeout(Sql* self, uint32* out_timeout)
+int Sql_GetTimeout(Sql *self, uint32 *out_timeout)
 {
-	if( self && out_timeout && SQL_SUCCESS == Sql_Query(self, "SHOW VARIABLES LIKE 'wait_timeout'") )
-	{
-		char* data;
-		size_t len;
-		if( SQL_SUCCESS == Sql_NextRow(self) &&
-			SQL_SUCCESS == Sql_GetData(self, 1, &data, &len) )
-		{
-			*out_timeout = (uint32)strtoul(data, NULL, 10);
-			Sql_FreeResult(self);
-			return SQL_SUCCESS;
-		}
-		Sql_FreeResult(self);
-	}
-	return SQL_ERROR;
+    if (self && out_timeout && SQL_SUCCESS == Sql_Query(self, "SHOW VARIABLES LIKE 'wait_timeout'")) {
+        char *data;
+        size_t len;
+        if (SQL_SUCCESS == Sql_NextRow(self) &&
+            SQL_SUCCESS == Sql_GetData(self, 1, &data, &len)) {
+            *out_timeout = (uint32)strtoul(data, NULL, 10);
+            Sql_FreeResult(self);
+            return SQL_SUCCESS;
+        }
+        Sql_FreeResult(self);
+    }
+    return SQL_ERROR;
 }
 
 
 
 /// Retrieves the name of the columns of a table into out_buf, with the separator after each name.
-int Sql_GetColumnNames(Sql* self, const char* table, char* out_buf, size_t buf_len, char sep)
+int Sql_GetColumnNames(Sql *self, const char *table, char *out_buf, size_t buf_len, char sep)
 {
-	char* data;
-	size_t len;
-	size_t off = 0;
+    char *data;
+    size_t len;
+    size_t off = 0;
 
-	if( self == NULL || SQL_ERROR == Sql_Query(self, "EXPLAIN `%s`", table) )
-		return SQL_ERROR;
+    if (self == NULL || SQL_ERROR == Sql_Query(self, "EXPLAIN `%s`", table))
+        return SQL_ERROR;
 
-	out_buf[off] = '\0';
-	while( SQL_SUCCESS == Sql_NextRow(self) && SQL_SUCCESS == Sql_GetData(self, 0, &data, &len) )
-	{
-		len = strnlen(data, len);
-		if( off + len + 2 > buf_len )
-		{
-			ShowDebug("Sql_GetColumns: output buffer is too small\n");
-			*out_buf = '\0';
-			return SQL_ERROR;
-		}
-		memcpy(out_buf+off, data, len);
-		off += len;
-		out_buf[off++] = sep;
-	}
-	out_buf[off] = '\0';
-	Sql_FreeResult(self);
-	return SQL_SUCCESS;
+    out_buf[off] = '\0';
+    while (SQL_SUCCESS == Sql_NextRow(self) && SQL_SUCCESS == Sql_GetData(self, 0, &data, &len)) {
+        len = strnlen(data, len);
+        if (off + len + 2 > buf_len) {
+            ShowDebug("Sql_GetColumns: output buffer is too small\n");
+            *out_buf = '\0';
+            return SQL_ERROR;
+        }
+        memcpy(out_buf+off, data, len);
+        off += len;
+        out_buf[off++] = sep;
+    }
+    out_buf[off] = '\0';
+    Sql_FreeResult(self);
+    return SQL_SUCCESS;
 }
 
 
 
 /// Changes the encoding of the connection.
-int Sql_SetEncoding(Sql* self, const char* encoding)
+int Sql_SetEncoding(Sql *self, const char *encoding)
 {
-	if( self && mysql_set_character_set(&self->handle, encoding) == 0 )
-		return SQL_SUCCESS;
-	return SQL_ERROR;
+    if (self && mysql_set_character_set(&self->handle, encoding) == 0)
+        return SQL_SUCCESS;
+    return SQL_ERROR;
 }
 
 
 
 /// Pings the connection.
-int Sql_Ping(Sql* self)
+int Sql_Ping(Sql *self)
 {
-	if( self && mysql_ping(&self->handle) == 0 )
-		return SQL_SUCCESS;
-	return SQL_ERROR;
+    if (self && mysql_ping(&self->handle) == 0)
+        return SQL_SUCCESS;
+    return SQL_ERROR;
 }
 
 
@@ -184,10 +175,10 @@ int Sql_Ping(Sql* self)
 /// @private
 static int Sql_P_KeepaliveTimer(int tid, unsigned int tick, int id, intptr_t data)
 {
-	Sql* self = (Sql*)data;
-	ShowInfo("Pinging SQL server to keep connection alive...\n");
-	Sql_Ping(self);
-	return 0;
+    Sql *self = (Sql *)data;
+    ShowInfo("Pinging SQL server to keep connection alive...\n");
+    Sql_Ping(self);
+    return 0;
 }
 
 
@@ -196,224 +187,213 @@ static int Sql_P_KeepaliveTimer(int tid, unsigned int tick, int id, intptr_t dat
 ///
 /// @return the keepalive timer id, or INVALID_TIMER
 /// @private
-static int Sql_P_Keepalive(Sql* self)
+static int Sql_P_Keepalive(Sql *self)
 {
-	uint32 timeout, ping_interval;
+    uint32 timeout, ping_interval;
 
-	// set a default value first
-	timeout = 28800; // 8 hours
+    // set a default value first
+    timeout = 28800; // 8 hours
 
-	// request the timeout value from the mysql server
-	Sql_GetTimeout(self, &timeout);
+    // request the timeout value from the mysql server
+    Sql_GetTimeout(self, &timeout);
 
-	if( timeout < 60 )
-		timeout = 60;
+    if (timeout < 60)
+        timeout = 60;
 
-	// establish keepalive
-	ping_interval = timeout - 30; // 30-second reserve
-	//add_timer_func_list(Sql_P_KeepaliveTimer, "Sql_P_KeepaliveTimer");
-	return add_timer_interval(gettick() + ping_interval*1000, Sql_P_KeepaliveTimer, 0, (intptr_t)self, ping_interval*1000);
+    // establish keepalive
+    ping_interval = timeout - 30; // 30-second reserve
+    //add_timer_func_list(Sql_P_KeepaliveTimer, "Sql_P_KeepaliveTimer");
+    return add_timer_interval(gettick() + ping_interval*1000, Sql_P_KeepaliveTimer, 0, (intptr_t)self, ping_interval*1000);
 }
 
 
 
 /// Escapes a string.
-size_t Sql_EscapeString(Sql* self, char *out_to, const char *from)
+size_t Sql_EscapeString(Sql *self, char *out_to, const char *from)
 {
-	if( self )
-		return (size_t)mysql_real_escape_string(&self->handle, out_to, from, (unsigned long)strlen(from));
-	else
-		return (size_t)mysql_escape_string(out_to, from, (unsigned long)strlen(from));
+    if (self)
+        return (size_t)mysql_real_escape_string(&self->handle, out_to, from, (unsigned long)strlen(from));
+    else
+        return (size_t)mysql_escape_string(out_to, from, (unsigned long)strlen(from));
 }
 
 
 
 /// Escapes a string.
-size_t Sql_EscapeStringLen(Sql* self, char *out_to, const char *from, size_t from_len)
+size_t Sql_EscapeStringLen(Sql *self, char *out_to, const char *from, size_t from_len)
 {
-	if( self )
-		return (size_t)mysql_real_escape_string(&self->handle, out_to, from, (unsigned long)from_len);
-	else
-		return (size_t)mysql_escape_string(out_to, from, (unsigned long)from_len);
+    if (self)
+        return (size_t)mysql_real_escape_string(&self->handle, out_to, from, (unsigned long)from_len);
+    else
+        return (size_t)mysql_escape_string(out_to, from, (unsigned long)from_len);
 }
 
 
 
 /// Executes a query.
-int Sql_Query(Sql* self, const char* query, ...)
+int Sql_Query(Sql *self, const char *query, ...)
 {
-	int res;
-	va_list args;
+    int res;
+    va_list args;
 
-	va_start(args, query);
-	res = Sql_QueryV(self, query, args);
-	va_end(args);
+    va_start(args, query);
+    res = Sql_QueryV(self, query, args);
+    va_end(args);
 
-	return res;
+    return res;
 }
 
 
 
 /// Executes a query.
-int Sql_QueryV(Sql* self, const char* query, va_list args)
+int Sql_QueryV(Sql *self, const char *query, va_list args)
 {
-	if( self == NULL )
-		return SQL_ERROR;
+    if (self == NULL)
+        return SQL_ERROR;
 
-	Sql_FreeResult(self);
-	StringBuf_Clear(&self->buf);
-	StringBuf_Vprintf(&self->buf, query, args);
-	if( mysql_real_query(&self->handle, StringBuf_Value(&self->buf), (unsigned long)StringBuf_Length(&self->buf)) )
-	{
-		ShowSQL("DB error - %s\n", mysql_error(&self->handle));
-		return SQL_ERROR;
-	}
-	self->result = mysql_store_result(&self->handle);
-	if( mysql_errno(&self->handle) != 0 )
-	{
-		ShowSQL("DB error - %s\n", mysql_error(&self->handle));
-		return SQL_ERROR;
-	}
-	return SQL_SUCCESS;
+    Sql_FreeResult(self);
+    StringBuf_Clear(&self->buf);
+    StringBuf_Vprintf(&self->buf, query, args);
+    if (mysql_real_query(&self->handle, StringBuf_Value(&self->buf), (unsigned long)StringBuf_Length(&self->buf))) {
+        ShowSQL("DB error - %s\n", mysql_error(&self->handle));
+        return SQL_ERROR;
+    }
+    self->result = mysql_store_result(&self->handle);
+    if (mysql_errno(&self->handle) != 0) {
+        ShowSQL("DB error - %s\n", mysql_error(&self->handle));
+        return SQL_ERROR;
+    }
+    return SQL_SUCCESS;
 }
 
 
 
 /// Executes a query.
-int Sql_QueryStr(Sql* self, const char* query)
+int Sql_QueryStr(Sql *self, const char *query)
 {
-	if( self == NULL )
-		return SQL_ERROR;
+    if (self == NULL)
+        return SQL_ERROR;
 
-	Sql_FreeResult(self);
-	StringBuf_Clear(&self->buf);
-	StringBuf_AppendStr(&self->buf, query);
-	if( mysql_real_query(&self->handle, StringBuf_Value(&self->buf), (unsigned long)StringBuf_Length(&self->buf)) )
-	{
-		ShowSQL("DB error - %s\n", mysql_error(&self->handle));
-		return SQL_ERROR;
-	}
-	self->result = mysql_store_result(&self->handle);
-	if( mysql_errno(&self->handle) != 0 )
-	{
-		ShowSQL("DB error - %s\n", mysql_error(&self->handle));
-		return SQL_ERROR;
-	}
-	return SQL_SUCCESS;
+    Sql_FreeResult(self);
+    StringBuf_Clear(&self->buf);
+    StringBuf_AppendStr(&self->buf, query);
+    if (mysql_real_query(&self->handle, StringBuf_Value(&self->buf), (unsigned long)StringBuf_Length(&self->buf))) {
+        ShowSQL("DB error - %s\n", mysql_error(&self->handle));
+        return SQL_ERROR;
+    }
+    self->result = mysql_store_result(&self->handle);
+    if (mysql_errno(&self->handle) != 0) {
+        ShowSQL("DB error - %s\n", mysql_error(&self->handle));
+        return SQL_ERROR;
+    }
+    return SQL_SUCCESS;
 }
 
 
 
 /// Returns the number of the AUTO_INCREMENT column of the last INSERT/UPDATE query.
-uint64 Sql_LastInsertId(Sql* self)
+uint64 Sql_LastInsertId(Sql *self)
 {
-	if( self )
-		return (uint64)mysql_insert_id(&self->handle);
-	else
-		return 0;
+    if (self)
+        return (uint64)mysql_insert_id(&self->handle);
+    else
+        return 0;
 }
 
 
 
 /// Returns the number of columns in each row of the result.
-uint32 Sql_NumColumns(Sql* self)
+uint32 Sql_NumColumns(Sql *self)
 {
-	if( self && self->result )
-		return (uint32)mysql_num_fields(self->result);
-	return 0;
+    if (self && self->result)
+        return (uint32)mysql_num_fields(self->result);
+    return 0;
 }
 
 
 
 /// Returns the number of rows in the result.
-uint64 Sql_NumRows(Sql* self)
+uint64 Sql_NumRows(Sql *self)
 {
-	if( self && self->result )
-		return (uint64)mysql_num_rows(self->result);
-	return 0;
+    if (self && self->result)
+        return (uint64)mysql_num_rows(self->result);
+    return 0;
 }
 
 
 
 /// Fetches the next row.
-int Sql_NextRow(Sql* self)
+int Sql_NextRow(Sql *self)
 {
-	if( self && self->result )
-	{
-		self->row = mysql_fetch_row(self->result);
-		if( self->row )
-		{
-			self->lengths = mysql_fetch_lengths(self->result);
-			return SQL_SUCCESS;
-		}
-		self->lengths = NULL;
-		if( mysql_errno(&self->handle) == 0 )
-			return SQL_NO_DATA;
-	}
-	return SQL_ERROR;
+    if (self && self->result) {
+        self->row = mysql_fetch_row(self->result);
+        if (self->row) {
+            self->lengths = mysql_fetch_lengths(self->result);
+            return SQL_SUCCESS;
+        }
+        self->lengths = NULL;
+        if (mysql_errno(&self->handle) == 0)
+            return SQL_NO_DATA;
+    }
+    return SQL_ERROR;
 }
 
 
 
 /// Gets the data of a column.
-int Sql_GetData(Sql* self, size_t col, char** out_buf, size_t* out_len)
+int Sql_GetData(Sql *self, size_t col, char **out_buf, size_t *out_len)
 {
-	if( self && self->row )
-	{
-		if( col < Sql_NumColumns(self) )
-		{
-			if( out_buf ) *out_buf = self->row[col];
-			if( out_len ) *out_len = (size_t)self->lengths[col];
-		}
-		else
-		{// out of range - ignore
-			if( out_buf ) *out_buf = NULL;
-			if( out_len ) *out_len = 0;
-		}
-		return SQL_SUCCESS;
-	}
-	return SQL_ERROR;
+    if (self && self->row) {
+        if (col < Sql_NumColumns(self)) {
+            if (out_buf) *out_buf = self->row[col];
+            if (out_len) *out_len = (size_t)self->lengths[col];
+        } else {
+            // out of range - ignore
+            if (out_buf) *out_buf = NULL;
+            if (out_len) *out_len = 0;
+        }
+        return SQL_SUCCESS;
+    }
+    return SQL_ERROR;
 }
 
 
 
 /// Frees the result of the query.
-void Sql_FreeResult(Sql* self)
+void Sql_FreeResult(Sql *self)
 {
-	if( self && self->result )
-	{
-		mysql_free_result(self->result);
-		self->result = NULL;
-		self->row = NULL;
-		self->lengths = NULL;
-	}
+    if (self && self->result) {
+        mysql_free_result(self->result);
+        self->result = NULL;
+        self->row = NULL;
+        self->lengths = NULL;
+    }
 }
 
 
 
 /// Shows debug information (last query).
-void Sql_ShowDebug_(Sql* self, const char* debug_file, const unsigned long debug_line)
+void Sql_ShowDebug_(Sql *self, const char *debug_file, const unsigned long debug_line)
 {
-	if( self == NULL )
-		ShowDebug("at %s:%lu - self is NULL\n", debug_file, debug_line);
-	else if( StringBuf_Length(&self->buf) > 0 )
-		ShowDebug("at %s:%lu - %s\n", debug_file, debug_line, StringBuf_Value(&self->buf));
-	else
-		ShowDebug("at %s:%lu\n", debug_file, debug_line);
+    if (self == NULL)
+        ShowDebug("at %s:%lu - self is NULL\n", debug_file, debug_line);
+    else if (StringBuf_Length(&self->buf) > 0)
+        ShowDebug("at %s:%lu - %s\n", debug_file, debug_line, StringBuf_Value(&self->buf));
+    else
+        ShowDebug("at %s:%lu\n", debug_file, debug_line);
 }
 
 
 
 /// Frees a Sql handle returned by Sql_Malloc.
-void Sql_Free(Sql* self) 
+void Sql_Free(Sql *self)
 {
-	if( self )
-	{
-		Sql_FreeResult(self);
-		StringBuf_Destroy(&self->buf);
-		if( self->keepalive != INVALID_TIMER ) delete_timer(self->keepalive, Sql_P_KeepaliveTimer);
-		aFree(self);
-	}
+    if (self) {
+        Sql_FreeResult(self);
+        StringBuf_Destroy(&self->buf);
+        if (self->keepalive != INVALID_TIMER) delete_timer(self->keepalive, Sql_P_KeepaliveTimer);
+        aFree(self);
+    }
 }
 
 
@@ -429,16 +409,19 @@ void Sql_Free(Sql* self)
 /// @private
 static enum enum_field_types Sql_P_SizeToMysqlIntType(int sz)
 {
-	switch( sz )
-	{
-	case 1: return MYSQL_TYPE_TINY;
-	case 2: return MYSQL_TYPE_SHORT;
-	case 4: return MYSQL_TYPE_LONG;
-	case 8: return MYSQL_TYPE_LONGLONG;
-	default:
-		ShowDebug("SizeToMysqlIntType: unsupported size (%d)\n", sz);
-		return MYSQL_TYPE_NULL;
-	}
+    switch (sz) {
+        case 1:
+            return MYSQL_TYPE_TINY;
+        case 2:
+            return MYSQL_TYPE_SHORT;
+        case 4:
+            return MYSQL_TYPE_LONG;
+        case 8:
+            return MYSQL_TYPE_LONGLONG;
+        default:
+            ShowDebug("SizeToMysqlIntType: unsupported size (%d)\n", sz);
+            return MYSQL_TYPE_NULL;
+    }
 }
 
 
@@ -446,74 +429,96 @@ static enum enum_field_types Sql_P_SizeToMysqlIntType(int sz)
 /// Binds a parameter/result.
 ///
 /// @private
-static int Sql_P_BindSqlDataType(MYSQL_BIND* bind, enum SqlDataType buffer_type, void* buffer, size_t buffer_len, unsigned long* out_length, int8* out_is_null)
-{
-	memset(bind, 0, sizeof(MYSQL_BIND));
-	switch( buffer_type )
-	{
-	case SQLDT_NULL: bind->buffer_type = MYSQL_TYPE_NULL;
-		buffer_len = 0;// FIXME length = ? [FlavioJS]
-		break;
-	// fixed size
-	case SQLDT_UINT8: bind->is_unsigned = 1;
-	case SQLDT_INT8: bind->buffer_type = MYSQL_TYPE_TINY;
-		buffer_len = 1;
-		break;
-	case SQLDT_UINT16: bind->is_unsigned = 1;
-	case SQLDT_INT16: bind->buffer_type = MYSQL_TYPE_SHORT;
-		buffer_len = 2;
-		break;
-	case SQLDT_UINT32: bind->is_unsigned = 1;
-	case SQLDT_INT32: bind->buffer_type = MYSQL_TYPE_LONG;
-		buffer_len = 4;
-		break;
-	case SQLDT_UINT64: bind->is_unsigned = 1;
-	case SQLDT_INT64: bind->buffer_type = MYSQL_TYPE_LONGLONG;
-		buffer_len = 8;
-		break;
-	// platform dependent size
-	case SQLDT_UCHAR: bind->is_unsigned = 1;
-	case SQLDT_CHAR: bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(char));
-		buffer_len = sizeof(char);
-		break;
-	case SQLDT_USHORT: bind->is_unsigned = 1;
-	case SQLDT_SHORT: bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(short));
-		buffer_len = sizeof(short);
-		break;
-	case SQLDT_UINT: bind->is_unsigned = 1;
-	case SQLDT_INT: bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(int));
-		buffer_len = sizeof(int);
-		break;
-	case SQLDT_ULONG: bind->is_unsigned = 1;
-	case SQLDT_LONG: bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(long));
-		buffer_len = sizeof(long);
-		break;
-	case SQLDT_ULONGLONG: bind->is_unsigned = 1;
-	case SQLDT_LONGLONG: bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(int64));
-		buffer_len = sizeof(int64);
-		break;
-	// floating point
-	case SQLDT_FLOAT: bind->buffer_type = MYSQL_TYPE_FLOAT;
-		buffer_len = 4;
-		break;
-	case SQLDT_DOUBLE: bind->buffer_type = MYSQL_TYPE_DOUBLE;
-		buffer_len = 8;
-		break;
-	// other
-	case SQLDT_STRING:
-	case SQLDT_ENUM: bind->buffer_type = MYSQL_TYPE_STRING;
-		break;
-	case SQLDT_BLOB: bind->buffer_type = MYSQL_TYPE_BLOB;
-		break;
-	default:
-		ShowDebug("Sql_P_BindSqlDataType: unsupported buffer type (%d)\n", buffer_type);
-		return SQL_ERROR;
-	}
-	bind->buffer = buffer;
-	bind->buffer_length = (unsigned long)buffer_len;
-	bind->length = out_length;
-	bind->is_null = (my_bool*)out_is_null;
-	return SQL_SUCCESS;
+static int Sql_P_BindSqlDataType(MYSQL_BIND *bind, enum SqlDataType buffer_type, void *buffer, size_t buffer_len, unsigned long *out_length, int8 *out_is_null)
+{
+    memset(bind, 0, sizeof(MYSQL_BIND));
+    switch (buffer_type) {
+        case SQLDT_NULL:
+            bind->buffer_type = MYSQL_TYPE_NULL;
+            buffer_len = 0;// FIXME length = ? [FlavioJS]
+            break;
+            // fixed size
+        case SQLDT_UINT8:
+            bind->is_unsigned = 1;
+        case SQLDT_INT8:
+            bind->buffer_type = MYSQL_TYPE_TINY;
+            buffer_len = 1;
+            break;
+        case SQLDT_UINT16:
+            bind->is_unsigned = 1;
+        case SQLDT_INT16:
+            bind->buffer_type = MYSQL_TYPE_SHORT;
+            buffer_len = 2;
+            break;
+        case SQLDT_UINT32:
+            bind->is_unsigned = 1;
+        case SQLDT_INT32:
+            bind->buffer_type = MYSQL_TYPE_LONG;
+            buffer_len = 4;
+            break;
+        case SQLDT_UINT64:
+            bind->is_unsigned = 1;
+        case SQLDT_INT64:
+            bind->buffer_type = MYSQL_TYPE_LONGLONG;
+            buffer_len = 8;
+            break;
+            // platform dependent size
+        case SQLDT_UCHAR:
+            bind->is_unsigned = 1;
+        case SQLDT_CHAR:
+            bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(char));
+            buffer_len = sizeof(char);
+            break;
+        case SQLDT_USHORT:
+            bind->is_unsigned = 1;
+        case SQLDT_SHORT:
+            bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(short));
+            buffer_len = sizeof(short);
+            break;
+        case SQLDT_UINT:
+            bind->is_unsigned = 1;
+        case SQLDT_INT:
+            bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(int));
+            buffer_len = sizeof(int);
+            break;
+        case SQLDT_ULONG:
+            bind->is_unsigned = 1;
+        case SQLDT_LONG:
+            bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(long));
+            buffer_len = sizeof(long);
+            break;
+        case SQLDT_ULONGLONG:
+            bind->is_unsigned = 1;
+        case SQLDT_LONGLONG:
+            bind->buffer_type = Sql_P_SizeToMysqlIntType(sizeof(int64));
+            buffer_len = sizeof(int64);
+            break;
+            // floating point
+        case SQLDT_FLOAT:
+            bind->buffer_type = MYSQL_TYPE_FLOAT;
+            buffer_len = 4;
+            break;
+        case SQLDT_DOUBLE:
+            bind->buffer_type = MYSQL_TYPE_DOUBLE;
+            buffer_len = 8;
+            break;
+            // other
+        case SQLDT_STRING:
+        case SQLDT_ENUM:
+            bind->buffer_type = MYSQL_TYPE_STRING;
+            break;
+        case SQLDT_BLOB:
+            bind->buffer_type = MYSQL_TYPE_BLOB;
+            break;
+        default:
+            ShowDebug("Sql_P_BindSqlDataType: unsupported buffer type (%d)\n", buffer_type);
+            return SQL_ERROR;
+    }
+    bind->buffer = buffer;
+    bind->buffer_length = (unsigned long)buffer_len;
+    bind->length = out_length;
+    bind->is_null = (my_bool *)out_is_null;
+    return SQL_SUCCESS;
 }
 
 
@@ -521,38 +526,37 @@ static int Sql_P_BindSqlDataType(MYSQL_BIND* bind, enum SqlDataType buffer_type,
 /// Prints debug information about a field (type and length).
 ///
 /// @private
-static void Sql_P_ShowDebugMysqlFieldInfo(const char* prefix, enum enum_field_types type, int is_unsigned, unsigned long length, const char* length_postfix)
-{
-	const char* sign = (is_unsigned ? "UNSIGNED " : "");
-	const char* type_string;
-	switch( type )
-	{
-	default:
-		ShowDebug("%stype=%s%u, length=%d\n", prefix, sign, type, length);
-		return;
+static void Sql_P_ShowDebugMysqlFieldInfo(const char *prefix, enum enum_field_types type, int is_unsigned, unsigned long length, const char *length_postfix)
+{
+    const char *sign = (is_unsigned ? "UNSIGNED " : "");
+    const char *type_string;
+    switch (type) {
+        default:
+            ShowDebug("%stype=%s%u, length=%d\n", prefix, sign, type, length);
+            return;
 #define SHOW_DEBUG_OF(x) case x: type_string = #x; break
-	SHOW_DEBUG_OF(MYSQL_TYPE_TINY);
-	SHOW_DEBUG_OF(MYSQL_TYPE_SHORT);
-	SHOW_DEBUG_OF(MYSQL_TYPE_LONG);
-	SHOW_DEBUG_OF(MYSQL_TYPE_INT24);
-	SHOW_DEBUG_OF(MYSQL_TYPE_LONGLONG);
-	SHOW_DEBUG_OF(MYSQL_TYPE_DECIMAL);
-	SHOW_DEBUG_OF(MYSQL_TYPE_FLOAT);
-	SHOW_DEBUG_OF(MYSQL_TYPE_DOUBLE);
-	SHOW_DEBUG_OF(MYSQL_TYPE_TIMESTAMP);
-	SHOW_DEBUG_OF(MYSQL_TYPE_DATE);
-	SHOW_DEBUG_OF(MYSQL_TYPE_TIME);
-	SHOW_DEBUG_OF(MYSQL_TYPE_DATETIME);
-	SHOW_DEBUG_OF(MYSQL_TYPE_YEAR);
-	SHOW_DEBUG_OF(MYSQL_TYPE_STRING);
-	SHOW_DEBUG_OF(MYSQL_TYPE_VAR_STRING);
-	SHOW_DEBUG_OF(MYSQL_TYPE_BLOB);
-	SHOW_DEBUG_OF(MYSQL_TYPE_SET);
-	SHOW_DEBUG_OF(MYSQL_TYPE_ENUM);
-	SHOW_DEBUG_OF(MYSQL_TYPE_NULL);
+            SHOW_DEBUG_OF(MYSQL_TYPE_TINY);
+            SHOW_DEBUG_OF(MYSQL_TYPE_SHORT);
+            SHOW_DEBUG_OF(MYSQL_TYPE_LONG);
+            SHOW_DEBUG_OF(MYSQL_TYPE_INT24);
+            SHOW_DEBUG_OF(MYSQL_TYPE_LONGLONG);
+            SHOW_DEBUG_OF(MYSQL_TYPE_DECIMAL);
+            SHOW_DEBUG_OF(MYSQL_TYPE_FLOAT);
+            SHOW_DEBUG_OF(MYSQL_TYPE_DOUBLE);
+            SHOW_DEBUG_OF(MYSQL_TYPE_TIMESTAMP);
+            SHOW_DEBUG_OF(MYSQL_TYPE_DATE);
+            SHOW_DEBUG_OF(MYSQL_TYPE_TIME);
+            SHOW_DEBUG_OF(MYSQL_TYPE_DATETIME);
+            SHOW_DEBUG_OF(MYSQL_TYPE_YEAR);
+            SHOW_DEBUG_OF(MYSQL_TYPE_STRING);
+            SHOW_DEBUG_OF(MYSQL_TYPE_VAR_STRING);
+            SHOW_DEBUG_OF(MYSQL_TYPE_BLOB);
+            SHOW_DEBUG_OF(MYSQL_TYPE_SET);
+            SHOW_DEBUG_OF(MYSQL_TYPE_ENUM);
+            SHOW_DEBUG_OF(MYSQL_TYPE_NULL);
 #undef SHOW_DEBUG_TYPE_OF
-	}
-	ShowDebug("%stype=%s%s, length=%d%s\n", prefix, sign, type_string, length, length_postfix); 
+    }
+    ShowDebug("%stype=%s%s, length=%d%s\n", prefix, sign, type_string, length, length_postfix);
 }
 
 
@@ -560,389 +564,369 @@ static void Sql_P_ShowDebugMysqlFieldInfo(const char* prefix, enum enum_field_ty
 /// Reports debug information about a truncated column.
 ///
 /// @private
-static void SqlStmt_P_ShowDebugTruncatedColumn(SqlStmt* self, size_t i)
+static void SqlStmt_P_ShowDebugTruncatedColumn(SqlStmt *self, size_t i)
 {
-	MYSQL_RES* meta;
-	MYSQL_FIELD* field;
-	MYSQL_BIND* column;
+    MYSQL_RES *meta;
+    MYSQL_FIELD *field;
+    MYSQL_BIND *column;
 
-	meta = mysql_stmt_result_metadata(self->stmt);
-	field = mysql_fetch_field_direct(meta, (unsigned int)i);
-	ShowSQL("DB error - data of field '%s' was truncated.\n", field->name);
-	ShowDebug("column - %lu\n", (unsigned long)i);
-	Sql_P_ShowDebugMysqlFieldInfo("data   - ", field->type, field->flags&UNSIGNED_FLAG, self->column_lengths[i].length, "");
-	column = &self->columns[i];
-	if( column->buffer_type == MYSQL_TYPE_STRING )
-		Sql_P_ShowDebugMysqlFieldInfo("buffer - ", column->buffer_type, column->is_unsigned, column->buffer_length, "+1(nul-terminator)");
-	else
-		Sql_P_ShowDebugMysqlFieldInfo("buffer - ", column->buffer_type, column->is_unsigned, column->buffer_length, "");
-	mysql_free_result(meta);
+    meta = mysql_stmt_result_metadata(self->stmt);
+    field = mysql_fetch_field_direct(meta, (unsigned int)i);
+    ShowSQL("DB error - data of field '%s' was truncated.\n", field->name);
+    ShowDebug("column - %lu\n", (unsigned long)i);
+    Sql_P_ShowDebugMysqlFieldInfo("data   - ", field->type, field->flags&UNSIGNED_FLAG, self->column_lengths[i].length, "");
+    column = &self->columns[i];
+    if (column->buffer_type == MYSQL_TYPE_STRING)
+        Sql_P_ShowDebugMysqlFieldInfo("buffer - ", column->buffer_type, column->is_unsigned, column->buffer_length, "+1(nul-terminator)");
+    else
+        Sql_P_ShowDebugMysqlFieldInfo("buffer - ", column->buffer_type, column->is_unsigned, column->buffer_length, "");
+    mysql_free_result(meta);
 }
 
 
 
 /// Allocates and initializes a new SqlStmt handle.
-SqlStmt* SqlStmt_Malloc(Sql* sql)
+SqlStmt *SqlStmt_Malloc(Sql *sql)
 {
-	SqlStmt* self;
-	MYSQL_STMT* stmt;
+    SqlStmt *self;
+    MYSQL_STMT *stmt;
 
-	if( sql == NULL )
-		return NULL;
+    if (sql == NULL)
+        return NULL;
 
-	stmt = mysql_stmt_init(&sql->handle);
-	if( stmt == NULL )
-	{
-		ShowSQL("DB error - %s\n", mysql_error(&sql->handle));
-		return NULL;
-	}
-	CREATE(self, SqlStmt, 1);
-	StringBuf_Init(&self->buf);
-	self->stmt = stmt;
-	self->params = NULL;
-	self->columns = NULL;
-	self->column_lengths = NULL;
-	self->max_params = 0;
-	self->max_columns = 0;
-	self->bind_params = false;
-	self->bind_columns = false;
+    stmt = mysql_stmt_init(&sql->handle);
+    if (stmt == NULL) {
+        ShowSQL("DB error - %s\n", mysql_error(&sql->handle));
+        return NULL;
+    }
+    CREATE(self, SqlStmt, 1);
+    StringBuf_Init(&self->buf);
+    self->stmt = stmt;
+    self->params = NULL;
+    self->columns = NULL;
+    self->column_lengths = NULL;
+    self->max_params = 0;
+    self->max_columns = 0;
+    self->bind_params = false;
+    self->bind_columns = false;
 
-	return self;
+    return self;
 }
 
 
 
 /// Prepares the statement.
-int SqlStmt_Prepare(SqlStmt* self, const char* query, ...)
+int SqlStmt_Prepare(SqlStmt *self, const char *query, ...)
 {
-	int res;
-	va_list args;
+    int res;
+    va_list args;
 
-	va_start(args, query);
-	res = SqlStmt_PrepareV(self, query, args);
-	va_end(args);
+    va_start(args, query);
+    res = SqlStmt_PrepareV(self, query, args);
+    va_end(args);
 
-	return res;
+    return res;
 }
 
 
 
 /// Prepares the statement.
-int SqlStmt_PrepareV(SqlStmt* self, const char* query, va_list args)
+int SqlStmt_PrepareV(SqlStmt *self, const char *query, va_list args)
 {
-	if( self == NULL )
-		return SQL_ERROR;
+    if (self == NULL)
+        return SQL_ERROR;
 
-	SqlStmt_FreeResult(self);
-	StringBuf_Clear(&self->buf);
-	StringBuf_Vprintf(&self->buf, query, args);
-	if( mysql_stmt_prepare(self->stmt, StringBuf_Value(&self->buf), (unsigned long)StringBuf_Length(&self->buf)) )
-	{
-		ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
-		return SQL_ERROR;
-	}
-	self->bind_params = false;
+    SqlStmt_FreeResult(self);
+    StringBuf_Clear(&self->buf);
+    StringBuf_Vprintf(&self->buf, query, args);
+    if (mysql_stmt_prepare(self->stmt, StringBuf_Value(&self->buf), (unsigned long)StringBuf_Length(&self->buf))) {
+        ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
+        return SQL_ERROR;
+    }
+    self->bind_params = false;
 
-	return SQL_SUCCESS;
+    return SQL_SUCCESS;
 }
 
 
 
 /// Prepares the statement.
-int SqlStmt_PrepareStr(SqlStmt* self, const char* query)
+int SqlStmt_PrepareStr(SqlStmt *self, const char *query)
 {
-	if( self == NULL )
-		return SQL_ERROR;
+    if (self == NULL)
+        return SQL_ERROR;
 
-	SqlStmt_FreeResult(self);
-	StringBuf_Clear(&self->buf);
-	StringBuf_AppendStr(&self->buf, query);
-	if( mysql_stmt_prepare(self->stmt, StringBuf_Value(&self->buf), (unsigned long)StringBuf_Length(&self->buf)) )
-	{
-		ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
-		return SQL_ERROR;
-	}
-	self->bind_params = false;
+    SqlStmt_FreeResult(self);
+    StringBuf_Clear(&self->buf);
+    StringBuf_AppendStr(&self->buf, query);
+    if (mysql_stmt_prepare(self->stmt, StringBuf_Value(&self->buf), (unsigned long)StringBuf_Length(&self->buf))) {
+        ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
+        return SQL_ERROR;
+    }
+    self->bind_params = false;
 
-	return SQL_SUCCESS;
+    return SQL_SUCCESS;
 }
 
 
 
 /// Returns the number of parameters in the prepared statement.
-size_t SqlStmt_NumParams(SqlStmt* self)
+size_t SqlStmt_NumParams(SqlStmt *self)
 {
-	if( self )
-		return (size_t)mysql_stmt_param_count(self->stmt);
-	else
-		return 0;
+    if (self)
+        return (size_t)mysql_stmt_param_count(self->stmt);
+    else
+        return 0;
 }
 
 
 
 /// Binds a parameter to a buffer.
-int SqlStmt_BindParam(SqlStmt* self, size_t idx, enum SqlDataType buffer_type, void* buffer, size_t buffer_len)
+int SqlStmt_BindParam(SqlStmt *self, size_t idx, enum SqlDataType buffer_type, void *buffer, size_t buffer_len)
 {
-	if( self == NULL )
-		return SQL_ERROR;
+    if (self == NULL)
+        return SQL_ERROR;
 
-	if( !self->bind_params )
-	{// initialize the bindings
-		size_t i;
-		size_t count;
+    if (!self->bind_params) {
+        // initialize the bindings
+        size_t i;
+        size_t count;
 
-		count = SqlStmt_NumParams(self);
-		if( self->max_params < count )
-		{
-			self->max_params = count;
-			RECREATE(self->params, MYSQL_BIND, count);
-		}
-		memset(self->params, 0, count*sizeof(MYSQL_BIND));
-		for( i = 0; i < count; ++i )
-			self->params[i].buffer_type = MYSQL_TYPE_NULL;
-		self->bind_params = true;
-	}
-	if( idx < self->max_params )
-		return Sql_P_BindSqlDataType(self->params+idx, buffer_type, buffer, buffer_len, NULL, NULL);
-	else
-		return SQL_SUCCESS;// out of range - ignore
+        count = SqlStmt_NumParams(self);
+        if (self->max_params < count) {
+            self->max_params = count;
+            RECREATE(self->params, MYSQL_BIND, count);
+        }
+        memset(self->params, 0, count*sizeof(MYSQL_BIND));
+        for (i = 0; i < count; ++i)
+            self->params[i].buffer_type = MYSQL_TYPE_NULL;
+        self->bind_params = true;
+    }
+    if (idx < self->max_params)
+        return Sql_P_BindSqlDataType(self->params+idx, buffer_type, buffer, buffer_len, NULL, NULL);
+    else
+        return SQL_SUCCESS;// out of range - ignore
 }
 
 
 
 /// Executes the prepared statement.
-int SqlStmt_Execute(SqlStmt* self)
+int SqlStmt_Execute(SqlStmt *self)
 {
-	if( self == NULL )
-		return SQL_ERROR;
+    if (self == NULL)
+        return SQL_ERROR;
 
-	SqlStmt_FreeResult(self);
-	if( (self->bind_params && mysql_stmt_bind_param(self->stmt, self->params)) ||
-		mysql_stmt_execute(self->stmt) )
-	{
-		ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
-		return SQL_ERROR;
-	}
-	self->bind_columns = false;
-	if( mysql_stmt_store_result(self->stmt) )// store all the data
-	{
-		ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
-		return SQL_ERROR;
-	}
+    SqlStmt_FreeResult(self);
+    if ((self->bind_params && mysql_stmt_bind_param(self->stmt, self->params)) ||
+        mysql_stmt_execute(self->stmt)) {
+        ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
+        return SQL_ERROR;
+    }
+    self->bind_columns = false;
+    if (mysql_stmt_store_result(self->stmt)) { // store all the data
+        ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
+        return SQL_ERROR;
+    }
 
-	return SQL_SUCCESS;
+    return SQL_SUCCESS;
 }
 
 
 
 /// Returns the number of the AUTO_INCREMENT column of the last INSERT/UPDATE statement.
-uint64 SqlStmt_LastInsertId(SqlStmt* self)
+uint64 SqlStmt_LastInsertId(SqlStmt *self)
 {
-	if( self )
-		return (uint64)mysql_stmt_insert_id(self->stmt);
-	else
-		return 0;
+    if (self)
+        return (uint64)mysql_stmt_insert_id(self->stmt);
+    else
+        return 0;
 }
 
 
 
 /// Returns the number of columns in each row of the result.
-size_t SqlStmt_NumColumns(SqlStmt* self)
+size_t SqlStmt_NumColumns(SqlStmt *self)
 {
-	if( self )
-		return (size_t)mysql_stmt_field_count(self->stmt);
-	else
-		return 0;
+    if (self)
+        return (size_t)mysql_stmt_field_count(self->stmt);
+    else
+        return 0;
 }
 
 
 
 /// Binds the result of a column to a buffer.
-int SqlStmt_BindColumn(SqlStmt* self, size_t idx, enum SqlDataType buffer_type, void* buffer, size_t buffer_len, uint32* out_length, int8* out_is_null)
-{
-	if( self == NULL )
-		return SQL_ERROR;
-
-	if( buffer_type == SQLDT_STRING || buffer_type == SQLDT_ENUM )
-	{
-		if( buffer_len < 1 )
-		{
-			ShowDebug("SqlStmt_BindColumn: buffer_len(%d) is too small, no room for the nul-terminator\n", buffer_len);
-			return SQL_ERROR;
-		}
-		--buffer_len;// nul-terminator
-	}
-	if( !self->bind_columns )
-	{// initialize the bindings
-		size_t i;
-		size_t cols;
-
-		cols = SqlStmt_NumColumns(self);
-		if( self->max_columns < cols )
-		{
-			self->max_columns = cols;
-			RECREATE(self->columns, MYSQL_BIND, cols);
-			RECREATE(self->column_lengths, s_column_length, cols);
-		}
-		memset(self->columns, 0, cols*sizeof(MYSQL_BIND));
-		memset(self->column_lengths, 0, cols*sizeof(s_column_length));
-		for( i = 0; i < cols; ++i )
-			self->columns[i].buffer_type = MYSQL_TYPE_NULL;
-		self->bind_columns = true;
-	}
-	if( idx < self->max_columns )
-	{
-		self->column_lengths[idx].out_length = out_length;
-		return Sql_P_BindSqlDataType(self->columns+idx, buffer_type, buffer, buffer_len, &self->column_lengths[idx].length, out_is_null);
-	}
-	else
-	{
-		return SQL_SUCCESS;// out of range - ignore
-	}
+int SqlStmt_BindColumn(SqlStmt *self, size_t idx, enum SqlDataType buffer_type, void *buffer, size_t buffer_len, uint32 *out_length, int8 *out_is_null)
+{
+    if (self == NULL)
+        return SQL_ERROR;
+
+    if (buffer_type == SQLDT_STRING || buffer_type == SQLDT_ENUM) {
+        if (buffer_len < 1) {
+            ShowDebug("SqlStmt_BindColumn: buffer_len(%d) is too small, no room for the nul-terminator\n", buffer_len);
+            return SQL_ERROR;
+        }
+        --buffer_len;// nul-terminator
+    }
+    if (!self->bind_columns) {
+        // initialize the bindings
+        size_t i;
+        size_t cols;
+
+        cols = SqlStmt_NumColumns(self);
+        if (self->max_columns < cols) {
+            self->max_columns = cols;
+            RECREATE(self->columns, MYSQL_BIND, cols);
+            RECREATE(self->column_lengths, s_column_length, cols);
+        }
+        memset(self->columns, 0, cols*sizeof(MYSQL_BIND));
+        memset(self->column_lengths, 0, cols*sizeof(s_column_length));
+        for (i = 0; i < cols; ++i)
+            self->columns[i].buffer_type = MYSQL_TYPE_NULL;
+        self->bind_columns = true;
+    }
+    if (idx < self->max_columns) {
+        self->column_lengths[idx].out_length = out_length;
+        return Sql_P_BindSqlDataType(self->columns+idx, buffer_type, buffer, buffer_len, &self->column_lengths[idx].length, out_is_null);
+    } else {
+        return SQL_SUCCESS;// out of range - ignore
+    }
 }
 
 
 
 /// Returns the number of rows in the result.
-uint64 SqlStmt_NumRows(SqlStmt* self)
+uint64 SqlStmt_NumRows(SqlStmt *self)
 {
-	if( self )
-		return (uint64)mysql_stmt_num_rows(self->stmt);
-	else
-		return 0;
+    if (self)
+        return (uint64)mysql_stmt_num_rows(self->stmt);
+    else
+        return 0;
 }
 
 
 
 /// Fetches the next row.
-int SqlStmt_NextRow(SqlStmt* self)
-{
-	int err;
-	size_t i;
-	size_t cols;
-	MYSQL_BIND* column;
-	unsigned long length;
-
-	if( self == NULL )
-		return SQL_ERROR;
-
-	// bind columns
-	if( self->bind_columns && mysql_stmt_bind_result(self->stmt, self->columns) )
-		err = 1;// error binding columns
-	else
-		err = mysql_stmt_fetch(self->stmt);// fetch row
-
-	// check for errors
-	if( err == MYSQL_NO_DATA )
-		return SQL_NO_DATA;
+int SqlStmt_NextRow(SqlStmt *self)
+{
+    int err;
+    size_t i;
+    size_t cols;
+    MYSQL_BIND *column;
+    unsigned long length;
+
+    if (self == NULL)
+        return SQL_ERROR;
+
+    // bind columns
+    if (self->bind_columns && mysql_stmt_bind_result(self->stmt, self->columns))
+        err = 1;// error binding columns
+    else
+        err = mysql_stmt_fetch(self->stmt);// fetch row
+
+    // check for errors
+    if (err == MYSQL_NO_DATA)
+        return SQL_NO_DATA;
 #if defined(MYSQL_DATA_TRUNCATED)
-	// MySQL 5.0/5.1 defines and returns MYSQL_DATA_TRUNCATED [FlavioJS]
-	if( err == MYSQL_DATA_TRUNCATED )
-	{
-		my_bool truncated;
-
-		if( !self->bind_columns )
-		{
-			ShowSQL("DB error - data truncated (unknown source, columns are not bound)\n");
-			return SQL_ERROR;
-		}
-
-		// find truncated column
-		cols = SqlStmt_NumColumns(self);
-		for( i = 0; i < cols; ++i )
-		{
-			column = &self->columns[i];
-			column->error = &truncated;
-			mysql_stmt_fetch_column(self->stmt, column, (unsigned int)i, 0);
-			column->error = NULL;
-			if( truncated )
-			{// report truncated column
-				SqlStmt_P_ShowDebugTruncatedColumn(self, i);
-				return SQL_ERROR;
-			}
-		}
-		ShowSQL("DB error - data truncated (unknown source)\n");
-		return SQL_ERROR;
-	}
+    // MySQL 5.0/5.1 defines and returns MYSQL_DATA_TRUNCATED [FlavioJS]
+    if (err == MYSQL_DATA_TRUNCATED) {
+        my_bool truncated;
+
+        if (!self->bind_columns) {
+            ShowSQL("DB error - data truncated (unknown source, columns are not bound)\n");
+            return SQL_ERROR;
+        }
+
+        // find truncated column
+        cols = SqlStmt_NumColumns(self);
+        for (i = 0; i < cols; ++i) {
+            column = &self->columns[i];
+            column->error = &truncated;
+            mysql_stmt_fetch_column(self->stmt, column, (unsigned int)i, 0);
+            column->error = NULL;
+            if (truncated) {
+                // report truncated column
+                SqlStmt_P_ShowDebugTruncatedColumn(self, i);
+                return SQL_ERROR;
+            }
+        }
+        ShowSQL("DB error - data truncated (unknown source)\n");
+        return SQL_ERROR;
+    }
 #endif
-	if( err )
-	{
-		ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
-		return SQL_ERROR;
-	}
-
-	// propagate column lengths and clear unused parts of string/enum/blob buffers
-	cols = SqlStmt_NumColumns(self);
-	for( i = 0; i < cols; ++i )
-	{
-		length = self->column_lengths[i].length;
-		column = &self->columns[i];
+    if (err) {
+        ShowSQL("DB error - %s\n", mysql_stmt_error(self->stmt));
+        return SQL_ERROR;
+    }
+
+    // propagate column lengths and clear unused parts of string/enum/blob buffers
+    cols = SqlStmt_NumColumns(self);
+    for (i = 0; i < cols; ++i) {
+        length = self->column_lengths[i].length;
+        column = &self->columns[i];
 #if !defined(MYSQL_DATA_TRUNCATED)
-		// MySQL 4.1/(below?) returns success even if data is truncated, so we test truncation manually [FlavioJS]
-		if( column->buffer_length < length )
-		{// report truncated column
-			if( column->buffer_type == MYSQL_TYPE_STRING || column->buffer_type == MYSQL_TYPE_BLOB )
-			{// string/enum/blob column
-				SqlStmt_P_ShowDebugTruncatedColumn(self, i);
-				return SQL_ERROR;
-			}
-			// FIXME numeric types and null [FlavioJS]
-		}
+        // MySQL 4.1/(below?) returns success even if data is truncated, so we test truncation manually [FlavioJS]
+        if (column->buffer_length < length) {
+            // report truncated column
+            if (column->buffer_type == MYSQL_TYPE_STRING || column->buffer_type == MYSQL_TYPE_BLOB) {
+                // string/enum/blob column
+                SqlStmt_P_ShowDebugTruncatedColumn(self, i);
+                return SQL_ERROR;
+            }
+            // FIXME numeric types and null [FlavioJS]
+        }
 #endif
-		if( self->column_lengths[i].out_length )
-			*self->column_lengths[i].out_length = (uint32)length;
-		if( column->buffer_type == MYSQL_TYPE_STRING )
-		{// clear unused part of the string/enum buffer (and nul-terminate)
-			memset((char*)column->buffer + length, 0, column->buffer_length - length + 1);
-		}
-		else if( column->buffer_type == MYSQL_TYPE_BLOB && length < column->buffer_length )
-		{// clear unused part of the blob buffer
-			memset((char*)column->buffer + length, 0, column->buffer_length - length);
-		}
-	}
+        if (self->column_lengths[i].out_length)
+            *self->column_lengths[i].out_length = (uint32)length;
+        if (column->buffer_type == MYSQL_TYPE_STRING) {
+            // clear unused part of the string/enum buffer (and nul-terminate)
+            memset((char *)column->buffer + length, 0, column->buffer_length - length + 1);
+        } else if (column->buffer_type == MYSQL_TYPE_BLOB && length < column->buffer_length) {
+            // clear unused part of the blob buffer
+            memset((char *)column->buffer + length, 0, column->buffer_length - length);
+        }
+    }
 
-	return SQL_SUCCESS;
+    return SQL_SUCCESS;
 }
 
 
 
 /// Frees the result of the statement execution.
-void SqlStmt_FreeResult(SqlStmt* self)
+void SqlStmt_FreeResult(SqlStmt *self)
 {
-	if( self )
-		mysql_stmt_free_result(self->stmt);
+    if (self)
+        mysql_stmt_free_result(self->stmt);
 }
 
 
 
 /// Shows debug information (with statement).
-void SqlStmt_ShowDebug_(SqlStmt* self, const char* debug_file, const unsigned long debug_line)
+void SqlStmt_ShowDebug_(SqlStmt *self, const char *debug_file, const unsigned long debug_line)
 {
-	if( self == NULL )
-		ShowDebug("at %s:%lu -  self is NULL\n", debug_file, debug_line);
-	else if( StringBuf_Length(&self->buf) > 0 )
-		ShowDebug("at %s:%lu - %s\n", debug_file, debug_line, StringBuf_Value(&self->buf));
-	else
-		ShowDebug("at %s:%lu\n", debug_file, debug_line);
+    if (self == NULL)
+        ShowDebug("at %s:%lu -  self is NULL\n", debug_file, debug_line);
+    else if (StringBuf_Length(&self->buf) > 0)
+        ShowDebug("at %s:%lu - %s\n", debug_file, debug_line, StringBuf_Value(&self->buf));
+    else
+        ShowDebug("at %s:%lu\n", debug_file, debug_line);
 }
 
 
 
 /// Frees a SqlStmt returned by SqlStmt_Malloc.
-void SqlStmt_Free(SqlStmt* self)
-{
-	if( self )
-	{
-		SqlStmt_FreeResult(self);
-		StringBuf_Destroy(&self->buf);
-		mysql_stmt_close(self->stmt);
-		if( self->params )
-			aFree(self->params);
-		if( self->columns )
-		{
-			aFree(self->columns);
-			aFree(self->column_lengths);
-		}
-		aFree(self);
-	}
+void SqlStmt_Free(SqlStmt *self)
+{
+    if (self) {
+        SqlStmt_FreeResult(self);
+        StringBuf_Destroy(&self->buf);
+        mysql_stmt_close(self->stmt);
+        if (self->params)
+            aFree(self->params);
+        if (self->columns) {
+            aFree(self->columns);
+            aFree(self->column_lengths);
+        }
+        aFree(self);
+    }
 }

+ 69 - 70
src/common/sql.h

@@ -21,39 +21,38 @@
 
 /// Data type identifier.
 /// String, enum and blob data types need the buffer length specified.
-enum SqlDataType
-{
-	SQLDT_NULL,
-	// fixed size
-	SQLDT_INT8,
-	SQLDT_INT16,
-	SQLDT_INT32,
-	SQLDT_INT64,
-	SQLDT_UINT8,
-	SQLDT_UINT16,
-	SQLDT_UINT32,
-	SQLDT_UINT64,
-	// platform dependent size
-	SQLDT_CHAR,
-	SQLDT_SHORT,
-	SQLDT_INT,
-	SQLDT_LONG,
-	SQLDT_LONGLONG,
-	SQLDT_UCHAR,
-	SQLDT_USHORT,
-	SQLDT_UINT,
-	SQLDT_ULONG,
-	SQLDT_ULONGLONG,
-	// floating point
-	SQLDT_FLOAT,
-	SQLDT_DOUBLE,
-	// other
-	SQLDT_STRING,
-	SQLDT_ENUM,
-	// Note: An ENUM is a string with restricted values. When an invalid value
-	//       is inserted, it is saved as an empty string (numerical value 0).
-	SQLDT_BLOB,
-	SQLDT_LASTID
+enum SqlDataType {
+    SQLDT_NULL,
+    // fixed size
+    SQLDT_INT8,
+    SQLDT_INT16,
+    SQLDT_INT32,
+    SQLDT_INT64,
+    SQLDT_UINT8,
+    SQLDT_UINT16,
+    SQLDT_UINT32,
+    SQLDT_UINT64,
+    // platform dependent size
+    SQLDT_CHAR,
+    SQLDT_SHORT,
+    SQLDT_INT,
+    SQLDT_LONG,
+    SQLDT_LONGLONG,
+    SQLDT_UCHAR,
+    SQLDT_USHORT,
+    SQLDT_UINT,
+    SQLDT_ULONG,
+    SQLDT_ULONGLONG,
+    // floating point
+    SQLDT_FLOAT,
+    SQLDT_DOUBLE,
+    // other
+    SQLDT_STRING,
+    SQLDT_ENUM,
+    // Note: An ENUM is a string with restricted values. When an invalid value
+    //       is inserted, it is saved as an empty string (numerical value 0).
+    SQLDT_BLOB,
+    SQLDT_LASTID
 };
 
 struct Sql;// Sql handle (private access)
@@ -65,14 +64,14 @@ typedef struct SqlStmt SqlStmt;
 
 
 /// Allocates and initializes a new Sql handle.
-struct Sql* Sql_Malloc(void);
+struct Sql *Sql_Malloc(void);
 
 
 
 /// Establishes a connection.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_Connect(Sql* self, const char* user, const char* passwd, const char* host, uint16 port, const char* db);
+int Sql_Connect(Sql *self, const char *user, const char *passwd, const char *host, uint16 port, const char *db);
 
 
 
@@ -80,7 +79,7 @@ int Sql_Connect(Sql* self, const char* user, const char* passwd, const char* hos
 /// Retrieves the timeout of the connection.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_GetTimeout(Sql* self, uint32* out_timeout);
+int Sql_GetTimeout(Sql *self, uint32 *out_timeout);
 
 
 
@@ -88,7 +87,7 @@ int Sql_GetTimeout(Sql* self, uint32* out_timeout);
 /// Retrieves the name of the columns of a table into out_buf, with the separator after each name.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_GetColumnNames(Sql* self, const char* table, char* out_buf, size_t buf_len, char sep);
+int Sql_GetColumnNames(Sql *self, const char *table, char *out_buf, size_t buf_len, char sep);
 
 
 
@@ -96,14 +95,14 @@ int Sql_GetColumnNames(Sql* self, const char* table, char* out_buf, size_t buf_l
 /// Changes the encoding of the connection.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_SetEncoding(Sql* self, const char* encoding);
+int Sql_SetEncoding(Sql *self, const char *encoding);
 
 
 
 /// Pings the connection.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_Ping(Sql* self);
+int Sql_Ping(Sql *self);
 
 
 
@@ -111,7 +110,7 @@ int Sql_Ping(Sql* self);
 /// The output buffer must be at least strlen(from)*2+1 in size.
 ///
 /// @return The size of the escaped string
-size_t Sql_EscapeString(Sql* self, char* out_to, const char* from);
+size_t Sql_EscapeString(Sql *self, char *out_to, const char *from);
 
 
 
@@ -119,7 +118,7 @@ size_t Sql_EscapeString(Sql* self, char* out_to, const char* from);
 /// The output buffer must be at least from_len*2+1 in size.
 ///
 /// @return The size of the escaped string
-size_t Sql_EscapeStringLen(Sql* self, char* out_to, const char* from, size_t from_len);
+size_t Sql_EscapeStringLen(Sql *self, char *out_to, const char *from, size_t from_len);
 
 
 
@@ -128,7 +127,7 @@ size_t Sql_EscapeStringLen(Sql* self, char* out_to, const char* from, size_t fro
 /// The query is constructed as if it was sprintf.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_Query(Sql* self, const char* query, ...);
+int Sql_Query(Sql *self, const char *query, ...);
 
 
 
@@ -137,7 +136,7 @@ int Sql_Query(Sql* self, const char* query, ...);
 /// The query is constructed as if it was svprintf.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_QueryV(Sql* self, const char* query, va_list args);
+int Sql_QueryV(Sql *self, const char *query, va_list args);
 
 
 
@@ -146,28 +145,28 @@ int Sql_QueryV(Sql* self, const char* query, va_list args);
 /// The query is used directly.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_QueryStr(Sql* self, const char* query);
+int Sql_QueryStr(Sql *self, const char *query);
 
 
 
 /// Returns the number of the AUTO_INCREMENT column of the last INSERT/UPDATE query.
 ///
 /// @return Value of the auto-increment column
-uint64 Sql_LastInsertId(Sql* self);
+uint64 Sql_LastInsertId(Sql *self);
 
 
 
 /// Returns the number of columns in each row of the result.
 ///
 /// @return Number of columns
-uint32 Sql_NumColumns(Sql* self);
+uint32 Sql_NumColumns(Sql *self);
 
 
 
 /// Returns the number of rows in the result.
 ///
 /// @return Number of rows
-uint64 Sql_NumRows(Sql* self);
+uint64 Sql_NumRows(Sql *self);
 
 
 
@@ -175,7 +174,7 @@ uint64 Sql_NumRows(Sql* self);
 /// The data of the previous row is no longer valid.
 ///
 /// @return SQL_SUCCESS, SQL_ERROR or SQL_NO_DATA
-int Sql_NextRow(Sql* self);
+int Sql_NextRow(Sql *self);
 
 
 
@@ -183,12 +182,12 @@ int Sql_NextRow(Sql* self);
 /// The data remains valid until the next row is fetched or the result is freed.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int Sql_GetData(Sql* self, size_t col, char** out_buf, size_t* out_len);
+int Sql_GetData(Sql *self, size_t col, char **out_buf, size_t *out_len);
 
 
 
 /// Frees the result of the query.
-void Sql_FreeResult(Sql* self);
+void Sql_FreeResult(Sql *self);
 
 
 
@@ -198,22 +197,22 @@ void Sql_FreeResult(Sql* self);
 #define Sql_ShowDebug(self) Sql_ShowDebug_(self, __FILE__, __LINE__)
 #endif
 /// Shows debug information (last query).
-void Sql_ShowDebug_(Sql* self, const char* debug_file, const unsigned long debug_line);
+void Sql_ShowDebug_(Sql *self, const char *debug_file, const unsigned long debug_line);
 
 
 
 /// Frees a Sql handle returned by Sql_Malloc.
-void Sql_Free(Sql* self);
+void Sql_Free(Sql *self);
 
 
 
 ///////////////////////////////////////////////////////////////////////////////
 // Prepared Statements
 ///////////////////////////////////////////////////////////////////////////////
-// Parameters are placed in the statement by embedding question mark ('?') 
+// Parameters are placed in the statement by embedding question mark ('?')
 // characters into the query at the appropriate positions.
 // The markers are legal only in places where they represent data.
-// The markers cannot be inside quotes. Quotes will be added automatically 
+// The markers cannot be inside quotes. Quotes will be added automatically
 // when they are required.
 //
 // example queries with parameters:
@@ -227,7 +226,7 @@ void Sql_Free(Sql* self);
 /// Queries in Sql and SqlStmt are independent and don't affect each other.
 ///
 /// @return SqlStmt handle or NULL if an error occured
-struct SqlStmt* SqlStmt_Malloc(Sql* sql);
+struct SqlStmt *SqlStmt_Malloc(Sql *sql);
 
 
 
@@ -236,7 +235,7 @@ struct SqlStmt* SqlStmt_Malloc(Sql* sql);
 /// The query is constructed as if it was sprintf.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int SqlStmt_Prepare(SqlStmt* self, const char* query, ...);
+int SqlStmt_Prepare(SqlStmt *self, const char *query, ...);
 
 
 
@@ -245,7 +244,7 @@ int SqlStmt_Prepare(SqlStmt* self, const char* query, ...);
 /// The query is constructed as if it was svprintf.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int SqlStmt_PrepareV(SqlStmt* self, const char* query, va_list args);
+int SqlStmt_PrepareV(SqlStmt *self, const char *query, va_list args);
 
 
 
@@ -254,14 +253,14 @@ int SqlStmt_PrepareV(SqlStmt* self, const char* query, va_list args);
 /// The query is used directly.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int SqlStmt_PrepareStr(SqlStmt* self, const char* query);
+int SqlStmt_PrepareStr(SqlStmt *self, const char *query);
 
 
 
 /// Returns the number of parameters in the prepared statement.
 ///
 /// @return Number or paramenters
-size_t SqlStmt_NumParams(SqlStmt* self);
+size_t SqlStmt_NumParams(SqlStmt *self);
 
 
 
@@ -270,7 +269,7 @@ size_t SqlStmt_NumParams(SqlStmt* self);
 /// All parameters should have bindings.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int SqlStmt_BindParam(SqlStmt* self, size_t idx, SqlDataType buffer_type, void* buffer, size_t buffer_len);
+int SqlStmt_BindParam(SqlStmt *self, size_t idx, SqlDataType buffer_type, void *buffer, size_t buffer_len);
 
 
 
@@ -278,38 +277,38 @@ int SqlStmt_BindParam(SqlStmt* self, size_t idx, SqlDataType buffer_type, void*
 /// Any previous result is freed and all column bindings are removed.
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int SqlStmt_Execute(SqlStmt* self);
+int SqlStmt_Execute(SqlStmt *self);
 
 
 
 /// Returns the number of the AUTO_INCREMENT column of the last INSERT/UPDATE statement.
 ///
 /// @return Value of the auto-increment column
-uint64 SqlStmt_LastInsertId(SqlStmt* self);
+uint64 SqlStmt_LastInsertId(SqlStmt *self);
 
 
 
 /// Returns the number of columns in each row of the result.
 ///
 /// @return Number of columns
-size_t SqlStmt_NumColumns(SqlStmt* self);
+size_t SqlStmt_NumColumns(SqlStmt *self);
 
 
 
 /// Binds the result of a column to a buffer.
 /// The buffer will be filled with data when the next row is fetched.
-/// For string/enum buffer types there has to be enough space for the data 
+/// For string/enum buffer types there has to be enough space for the data
 /// and the nul-terminator (an extra byte).
 ///
 /// @return SQL_SUCCESS or SQL_ERROR
-int SqlStmt_BindColumn(SqlStmt* self, size_t idx, SqlDataType buffer_type, void* buffer, size_t buffer_len, uint32* out_length, int8* out_is_null);
+int SqlStmt_BindColumn(SqlStmt *self, size_t idx, SqlDataType buffer_type, void *buffer, size_t buffer_len, uint32 *out_length, int8 *out_is_null);
 
 
 
 /// Returns the number of rows in the result.
 ///
 /// @return Number of rows
-uint64 SqlStmt_NumRows(SqlStmt* self);
+uint64 SqlStmt_NumRows(SqlStmt *self);
 
 
 
@@ -317,12 +316,12 @@ uint64 SqlStmt_NumRows(SqlStmt* self);
 /// All column bindings will be filled with data.
 ///
 /// @return SQL_SUCCESS, SQL_ERROR or SQL_NO_DATA
-int SqlStmt_NextRow(SqlStmt* self);
+int SqlStmt_NextRow(SqlStmt *self);
 
 
 
 /// Frees the result of the statement execution.
-void SqlStmt_FreeResult(SqlStmt* self);
+void SqlStmt_FreeResult(SqlStmt *self);
 
 
 
@@ -332,12 +331,12 @@ void SqlStmt_FreeResult(SqlStmt* self);
 #define SqlStmt_ShowDebug(self) SqlStmt_ShowDebug_(self, __FILE__, __LINE__)
 #endif
 /// Shows debug information (with statement).
-void SqlStmt_ShowDebug_(SqlStmt* self, const char* debug_file, const unsigned long debug_line);
+void SqlStmt_ShowDebug_(SqlStmt *self, const char *debug_file, const unsigned long debug_line);
 
 
 
 /// Frees a SqlStmt returned by SqlStmt_Malloc.
-void SqlStmt_Free(SqlStmt* self);
+void SqlStmt_Free(SqlStmt *self);
 
 
 

File diff suppressed because it is too large
+ 424 - 450
src/common/strlib.c


+ 58 - 61
src/common/strlib.h

@@ -11,66 +11,65 @@
 #include <string.h>
 #undef __USE_GNU
 
-char* jstrescape (char* pt);
-char* jstrescapecpy (char* pt, const char* spt);
-int jmemescapecpy (char* pt, const char* spt, int size);
+char *jstrescape(char *pt);
+char *jstrescapecpy(char *pt, const char *spt);
+int jmemescapecpy(char *pt, const char *spt, int size);
 
-int remove_control_chars(char* str);
-char* trim(char* str);
-char* normalize_name(char* str,const char* delims);
+int remove_control_chars(char *str);
+char *trim(char *str);
+char *normalize_name(char *str,const char *delims);
 const char *stristr(const char *haystack, const char *needle);
 
 #ifdef WIN32
 #define HAVE_STRTOK_R
 #define strtok_r(s,delim,save_ptr) _strtok_r((s),(delim),(save_ptr))
-char* _strtok_r(char* s1, const char* s2, char** lasts);
+char *_strtok_r(char *s1, const char *s2, char **lasts);
 #endif
 
 #if !(defined(WIN32) && defined(_MSC_VER) && _MSC_VER >= 1400) && !defined(HAVE_STRNLEN)
-size_t strnlen (const char* string, size_t maxlen);
+size_t strnlen(const char *string, size_t maxlen);
 #endif
 
 #if defined(WIN32) && defined(_MSC_VER) && _MSC_VER <= 1200
-uint64 strtoull(const char* str, char** endptr, int base);
+uint64 strtoull(const char *str, char **endptr, int base);
 #endif
 
-int e_mail_check(char* email);
-int config_switch(const char* str);
+int e_mail_check(char *email);
+int config_switch(const char *str);
 
 /// strncpy that always nul-terminates the string
-char* safestrncpy(char* dst, const char* src, size_t n);
+char *safestrncpy(char *dst, const char *src, size_t n);
 
 /// doesn't crash on null pointer
-size_t safestrnlen(const char* string, size_t maxlen);
+size_t safestrnlen(const char *string, size_t maxlen);
 
 /// Works like snprintf, but always nul-terminates the buffer.
 /// Returns the size of the string (without nul-terminator)
 /// or -1 if the buffer is too small.
-int safesnprintf(char* buf, size_t sz, const char* fmt, ...);
+int safesnprintf(char *buf, size_t sz, const char *fmt, ...);
 
 /// Returns the line of the target position in the string.
 /// Lines start at 1.
-int strline(const char* str, size_t pos);
+int strline(const char *str, size_t pos);
 
 /// Produces the hexadecimal representation of the given input.
 /// The output buffer must be at least count*2+1 in size.
 /// Returns true on success, false on failure.
-bool bin2hex(char* output, unsigned char* input, size_t count);
+bool bin2hex(char *output, unsigned char *input, size_t count);
 
 
 /// Bitfield determining the behaviour of sv_parse and sv_split.
-typedef enum e_svopt
-{
-	// default: no escapes and no line terminator
-	SV_NOESCAPE_NOTERMINATE = 0,
-	// Escapes according to the C compiler.
-	SV_ESCAPE_C = 1,
-	// Line terminators
-	SV_TERMINATE_LF = 2,
-	SV_TERMINATE_CRLF = 4,
-	SV_TERMINATE_CR = 8,
-	// If sv_split keeps the end of line terminator, instead of replacing with '\0'
-	SV_KEEP_TERMINATOR = 16
+typedef enum e_svopt {
+    // default: no escapes and no line terminator
+    SV_NOESCAPE_NOTERMINATE = 0,
+    // Escapes according to the C compiler.
+    SV_ESCAPE_C = 1,
+    // Line terminators
+    SV_TERMINATE_LF = 2,
+    SV_TERMINATE_CRLF = 4,
+    SV_TERMINATE_CR = 8,
+    // If sv_split keeps the end of line terminator, instead of replacing with '\0'
+    SV_KEEP_TERMINATOR = 16
 } e_svopt;
 
 /// Other escape sequences supported by the C compiler.
@@ -78,16 +77,15 @@ typedef enum e_svopt
 
 /// Parse state.
 /// The field is [start,end[
-struct s_svstate
-{
-	const char* str; //< string to parse
-	int len; //< string length
-	int off; //< current offset in the string
-	int start; //< where the field starts
-	int end; //< where the field ends
-	enum e_svopt opt; //< parse options
-	char delim; //< field delimiter
-	bool done; //< if all the text has been parsed
+struct s_svstate {
+    const char *str; //< string to parse
+    int len; //< string length
+    int off; //< current offset in the string
+    int start; //< where the field starts
+    int end; //< where the field ends
+    enum e_svopt opt; //< parse options
+    char delim; //< field delimiter
+    bool done; //< if all the text has been parsed
 };
 
 /// Parses a single field in a delim-separated string.
@@ -95,14 +93,14 @@ struct s_svstate
 ///
 /// @param sv Parse state
 /// @return 1 if a field was parsed, 0 if done, -1 on error.
-int sv_parse_next(struct s_svstate* sv);
+int sv_parse_next(struct s_svstate *sv);
 
 /// Parses a delim-separated string.
 /// Starts parsing at startoff and fills the pos array with position pairs.
 /// out_pos[0] and out_pos[1] are the start and end of line.
 /// Other position pairs are the start and end of fields.
 /// Returns the number of fields found or -1 if an error occurs.
-int sv_parse(const char* str, int len, int startoff, char delim, int* out_pos, int npos, enum e_svopt opt);
+int sv_parse(const char *str, int len, int startoff, char delim, int *out_pos, int npos, enum e_svopt opt);
 
 /// Splits a delim-separated string.
 /// WARNING: this function modifies the input string
@@ -110,46 +108,45 @@ int sv_parse(const char* str, int len, int startoff, char delim, int* out_pos, i
 /// out_fields[0] is the start of the next line.
 /// Other entries are the start of fields (nul-teminated).
 /// Returns the number of fields found or -1 if an error occurs.
-int sv_split(char* str, int len, int startoff, char delim, char** out_fields, int nfields, enum e_svopt opt);
+int sv_split(char *str, int len, int startoff, char delim, char **out_fields, int nfields, enum e_svopt opt);
 
 /// Escapes src to out_dest according to the format of the C compiler.
 /// Returns the length of the escaped string.
 /// out_dest should be len*4+1 in size.
-size_t sv_escape_c(char* out_dest, const char* src, size_t len, const char* escapes);
+size_t sv_escape_c(char *out_dest, const char *src, size_t len, const char *escapes);
 
 /// Unescapes src to out_dest according to the format of the C compiler.
 /// Returns the length of the unescaped string.
 /// out_dest should be len+1 in size and can be the same buffer as src.
-size_t sv_unescape_c(char* out_dest, const char* src, size_t len);
+size_t sv_unescape_c(char *out_dest, const char *src, size_t len);
 
 /// Skips a C escape sequence (starting with '\\').
-const char* skip_escaped_c(const char* p);
+const char *skip_escaped_c(const char *p);
 
 /// Opens and parses a file containing delim-separated columns, feeding them to the specified callback function row by row.
 /// Tracks the progress of the operation (current line number, number of successfully processed rows).
 /// Returns 'true' if it was able to process the specified file, or 'false' if it could not be read.
-bool sv_readdb(const char* directory, const char* filename, char delim, int mincols, int maxcols, int maxrows, bool (*parseproc)(char* fields[], int columns, int current));
+bool sv_readdb(const char *directory, const char *filename, char delim, int mincols, int maxcols, int maxrows, bool (*parseproc)(char *fields[], int columns, int current));
 
 
 /// StringBuf - dynamic string
-struct StringBuf
-{
-	char *buf_;
-	char *ptr_;
-	unsigned int max_;
+struct StringBuf {
+    char *buf_;
+    char *ptr_;
+    unsigned int max_;
 };
 typedef struct StringBuf StringBuf;
 
-StringBuf* StringBuf_Malloc(void);
-void StringBuf_Init(StringBuf* self);
-int StringBuf_Printf(StringBuf* self, const char* fmt, ...);
-int StringBuf_Vprintf(StringBuf* self, const char* fmt, va_list args);
-int StringBuf_Append(StringBuf* self, const StringBuf *sbuf);
-int StringBuf_AppendStr(StringBuf* self, const char* str);
-int StringBuf_Length(StringBuf* self);
-char* StringBuf_Value(StringBuf* self);
-void StringBuf_Clear(StringBuf* self);
-void StringBuf_Destroy(StringBuf* self);
-void StringBuf_Free(StringBuf* self);
+StringBuf *StringBuf_Malloc(void);
+void StringBuf_Init(StringBuf *self);
+int StringBuf_Printf(StringBuf *self, const char *fmt, ...);
+int StringBuf_Vprintf(StringBuf *self, const char *fmt, va_list args);
+int StringBuf_Append(StringBuf *self, const StringBuf *sbuf);
+int StringBuf_AppendStr(StringBuf *self, const char *str);
+int StringBuf_Length(StringBuf *self);
+char *StringBuf_Value(StringBuf *self);
+void StringBuf_Clear(StringBuf *self);
+void StringBuf_Destroy(StringBuf *self);
+void StringBuf_Free(StringBuf *self);
 
 #endif /* _STRLIB_H_ */

+ 199 - 185
src/common/thread.c

@@ -9,7 +9,7 @@
 #ifdef WIN32
 #include "../common/winapi.h"
 #define getpagesize() 4096 // @TODO: implement this properly (GetSystemInfo .. dwPageSize..). (Atm as on all supported win platforms its 4k its static.)
-#define __thread __declspec( thread ) 
+#define __thread __declspec( thread )
 #else
 #include <stdlib.h>
 #include <unistd.h>
@@ -25,25 +25,25 @@
 #include "thread.h"
 
 // When Compiling using MSC (on win32..) we know we have support in any case!
-#ifdef _MSC_VER 
-#define HAS_TLS 
+#ifdef _MSC_VER
+#define HAS_TLS
 #endif
 
 
 #define RA_THREADS_MAX 64
 
 struct rAthread {
-	unsigned int myID;
-	
-	RATHREAD_PRIO  prio;
-	rAthreadProc proc;
-	void *param; 
-
-	#ifdef WIN32
-	HANDLE hThread;
-	#else
-	pthread_t hThread;
-	#endif
+    unsigned int myID;
+
+    RATHREAD_PRIO  prio;
+    rAthreadProc proc;
+    void *param;
+
+#ifdef WIN32
+    HANDLE hThread;
+#else
+    pthread_t hThread;
+#endif
 };
 
 
@@ -57,95 +57,100 @@ __thread int g_rathread_ID = -1;
 ///
 static struct rAthread l_threads[RA_THREADS_MAX];
 
-void rathread_init(){
-	register unsigned int i;
-	memset(&l_threads, 0x00, RA_THREADS_MAX * sizeof(struct rAthread) );
-	
-	for(i = 0; i < RA_THREADS_MAX; i++){
-		l_threads[i].myID = i;
-	}
+void rathread_init()
+{
+    register unsigned int i;
+    memset(&l_threads, 0x00, RA_THREADS_MAX * sizeof(struct rAthread));
+
+    for (i = 0; i < RA_THREADS_MAX; i++) {
+        l_threads[i].myID = i;
+    }
 
-	// now lets init thread id 0, which represnts the main thread
+    // now lets init thread id 0, which represnts the main thread
 #ifdef HAS_TLS
-	g_rathread_ID = 0;
+    g_rathread_ID = 0;
 #endif
-	l_threads[0].prio = RAT_PRIO_NORMAL;
-	l_threads[0].proc = (rAthreadProc)0xDEADCAFE;
+    l_threads[0].prio = RAT_PRIO_NORMAL;
+    l_threads[0].proc = (rAthreadProc)0xDEADCAFE;
 
 }//end: rathread_init()
 
 
 
-void rathread_final(){
-	register unsigned int i;
-	
-	// Unterminated Threads Left? 
-	// Should'nt happen ..
-	// Kill 'em all! 
-	//
-	for(i = 1; i < RA_THREADS_MAX; i++){
-		if(l_threads[i].proc != NULL){
-			ShowWarning("rAthread_final: unterminated Thread (tid %u entryPoint %p) - forcing to terminate (kill)\n", i, l_threads[i].proc);
-			rathread_destroy(&l_threads[i]);
-		}
-	}
-	
-	
+void rathread_final()
+{
+    register unsigned int i;
+
+    // Unterminated Threads Left?
+    // Should'nt happen ..
+    // Kill 'em all!
+    //
+    for (i = 1; i < RA_THREADS_MAX; i++) {
+        if (l_threads[i].proc != NULL) {
+            ShowWarning("rAthread_final: unterminated Thread (tid %u entryPoint %p) - forcing to terminate (kill)\n", i, l_threads[i].proc);
+            rathread_destroy(&l_threads[i]);
+        }
+    }
+
+
 }//end: rathread_final()
 
 
 
 // gets called whenever a thread terminated ..
-static void rat_thread_terminated( rAthread handle ){
+static void rat_thread_terminated(rAthread handle)
+{
 
-	int id_backup = handle->myID;
+    int id_backup = handle->myID;
 
-	// Simply set all members to 0 (except the id)
-	memset(handle, 0x00, sizeof(struct rAthread));
-	
-	handle->myID = id_backup; // done ;)
+    // Simply set all members to 0 (except the id)
+    memset(handle, 0x00, sizeof(struct rAthread));
+
+    handle->myID = id_backup; // done ;)
 
 }//end: rat_thread_terminated()
 
 #ifdef WIN32
-DWORD WINAPI _raThreadMainRedirector(LPVOID p){
+DWORD WINAPI _raThreadMainRedirector(LPVOID p)
+{
 #else
-static void *_raThreadMainRedirector( void *p ){
-	sigset_t set; // on Posix Thread platforms
+static void *_raThreadMainRedirector(void *p)
+{
+    sigset_t set; // on Posix Thread platforms
 #endif
-	void *ret;
-	
-	// Update myID @ TLS to right id.
+    void *ret;
+
+    // Update myID @ TLS to right id.
 #ifdef HAS_TLS
-	g_rathread_ID = ((rAthread)p)->myID; 
+    g_rathread_ID = ((rAthread)p)->myID;
 #endif
 
 #ifndef WIN32
-	// When using posix threads
-	// the threads inherits the Signal mask from the thread which's spawned 
-	// this thread
-	// so we've to block everything we dont care about.
-	sigemptyset(&set);
-	sigaddset(&set, SIGINT);
-	sigaddset(&set, SIGTERM);
-	sigaddset(&set, SIGPIPE);
-
-	pthread_sigmask(SIG_BLOCK, &set, NULL);
-		
+    // When using posix threads
+    // the threads inherits the Signal mask from the thread which's spawned
+    // this thread
+    // so we've to block everything we dont care about.
+    sigemptyset(&set);
+    sigaddset(&set, SIGINT);
+    sigaddset(&set, SIGTERM);
+    sigaddset(&set, SIGPIPE);
+
+    pthread_sigmask(SIG_BLOCK, &set, NULL);
+
 #endif
 
 
-	ret = ((rAthread)p)->proc( ((rAthread)p)->param ) ;
+    ret = ((rAthread)p)->proc(((rAthread)p)->param) ;
 
-#ifdef WIN32	
-	CloseHandle( ((rAthread)p)->hThread );
+#ifdef WIN32
+    CloseHandle(((rAthread)p)->hThread);
 #endif
 
-	rat_thread_terminated( (rAthread)p );
+    rat_thread_terminated((rAthread)p);
 #ifdef WIN32
-	return (DWORD)ret;
+    return (DWORD)ret;
 #else
-	return ret;
+    return ret;
 #endif
 }//end: _raThreadMainRedirector()
 
@@ -155,163 +160,172 @@ static void *_raThreadMainRedirector( void *p ){
 
 ///
 /// API Level
-/// 
-rAthread rathread_create( rAthreadProc entryPoint,  void *param ){
-	return rathread_createEx( entryPoint, param,  (1<<23) /*8MB*/,  RAT_PRIO_NORMAL );
+///
+rAthread rathread_create(rAthreadProc entryPoint,  void *param)
+{
+    return rathread_createEx(entryPoint, param, (1<<23) /*8MB*/,  RAT_PRIO_NORMAL);
 }//end: rathread_create()
 
 
-rAthread rathread_createEx( rAthreadProc entryPoint,  void *param,  size_t szStack,  RATHREAD_PRIO prio ){
+rAthread rathread_createEx(rAthreadProc entryPoint,  void *param,  size_t szStack,  RATHREAD_PRIO prio)
+{
 #ifndef WIN32
-	pthread_attr_t attr;
+    pthread_attr_t attr;
 #endif
-	size_t tmp;
-	unsigned int i;
-	rAthread handle = NULL;
-
-
-	// given stacksize aligned to systems pagesize?
-	tmp = szStack % getpagesize();
-	if(tmp != 0)
-		szStack += tmp;
-
-
-	// Get a free Thread Slot. 
-	for(i = 0; i < RA_THREADS_MAX; i++){
-		if(l_threads[i].proc == NULL){
-			handle = &l_threads[i];
-			break;
-		}
-	}
-	
-	if(handle == NULL){
-		ShowError("rAthread: cannot create new thread (entryPoint: %p) - no free thread slot found!", entryPoint);
-		return NULL;
-	}
-	
-	
-	
-	handle->proc = entryPoint;
-	handle->param = param;
+    size_t tmp;
+    unsigned int i;
+    rAthread handle = NULL;
+
+
+    // given stacksize aligned to systems pagesize?
+    tmp = szStack % getpagesize();
+    if (tmp != 0)
+        szStack += tmp;
+
+
+    // Get a free Thread Slot.
+    for (i = 0; i < RA_THREADS_MAX; i++) {
+        if (l_threads[i].proc == NULL) {
+            handle = &l_threads[i];
+            break;
+        }
+    }
+
+    if (handle == NULL) {
+        ShowError("rAthread: cannot create new thread (entryPoint: %p) - no free thread slot found!", entryPoint);
+        return NULL;
+    }
+
+
+
+    handle->proc = entryPoint;
+    handle->param = param;
 
 #ifdef WIN32
-	handle->hThread = CreateThread(NULL, szStack, _raThreadMainRedirector, (void*)handle, 0, NULL);
+    handle->hThread = CreateThread(NULL, szStack, _raThreadMainRedirector, (void *)handle, 0, NULL);
 #else
-	pthread_attr_init(&attr);
-	pthread_attr_setstacksize(&attr, szStack);
-	
-	if(pthread_create(&handle->hThread, &attr, _raThreadMainRedirector, (void*)handle) != 0){
-		handle->proc = NULL;
-		handle->param = NULL;
-		return NULL;
-	}
-	pthread_attr_destroy(&attr);
+    pthread_attr_init(&attr);
+    pthread_attr_setstacksize(&attr, szStack);
+
+    if (pthread_create(&handle->hThread, &attr, _raThreadMainRedirector, (void *)handle) != 0) {
+        handle->proc = NULL;
+        handle->param = NULL;
+        return NULL;
+    }
+    pthread_attr_destroy(&attr);
 #endif
 
-	rathread_prio_set( handle,  prio );
-	
-	return handle;
+    rathread_prio_set(handle,  prio);
+
+    return handle;
 }//end: rathread_createEx
 
 
-void rathread_destroy ( rAthread handle ){
+void rathread_destroy(rAthread handle)
+{
 #ifdef WIN32
-	if( TerminateThread(handle->hThread, 0) != FALSE){
-		CloseHandle(handle->hThread);
-		rat_thread_terminated(handle);
-	}
+    if (TerminateThread(handle->hThread, 0) != FALSE) {
+        CloseHandle(handle->hThread);
+        rat_thread_terminated(handle);
+    }
 #else
-	if( pthread_cancel( handle->hThread ) == 0){
-	
-		// We have to join it, otherwise pthread wont re-cycle its internal ressources assoc. with this thread.
-		// 
-		pthread_join( handle->hThread, NULL );
-		
-		// Tell our manager to release ressources ;)
-		rat_thread_terminated(handle);
-	}
+    if (pthread_cancel(handle->hThread) == 0) {
+
+        // We have to join it, otherwise pthread wont re-cycle its internal ressources assoc. with this thread.
+        //
+        pthread_join(handle->hThread, NULL);
+
+        // Tell our manager to release ressources ;)
+        rat_thread_terminated(handle);
+    }
 #endif
 }//end: rathread_destroy()
 
-rAthread rathread_self( ){
+rAthread rathread_self()
+{
 #ifdef HAS_TLS
-	rAthread handle = &l_threads[g_rathread_ID];
-	
-	if(handle->proc != NULL) // entry point set, so its used!	
-		return handle;
+    rAthread handle = &l_threads[g_rathread_ID];
+
+    if (handle->proc != NULL) // entry point set, so its used!
+        return handle;
 #else
-	// .. so no tls means we have to search the thread by its api-handle .. 
-	int i;
-
-	#ifdef WIN32
-		HANDLE hSelf;
-		hSelf = GetCurrent = GetCurrentThread();
-	#else
-		pthread_t hSelf;
-		hSelf = pthread_self();
-	#endif
-	
-	for(i = 0; i < RA_THREADS_MAX; i++){
-		if(l_threads[i].hThread == hSelf  &&  l_threads[i].proc != NULL)
-			return &l_threads[i];
-	}
-	
+    // .. so no tls means we have to search the thread by its api-handle ..
+    int i;
+
+#ifdef WIN32
+    HANDLE hSelf;
+    hSelf = GetCurrent = GetCurrentThread();
+#else
+    pthread_t hSelf;
+    hSelf = pthread_self();
+#endif
+
+    for (i = 0; i < RA_THREADS_MAX; i++) {
+        if (l_threads[i].hThread == hSelf  &&  l_threads[i].proc != NULL)
+            return &l_threads[i];
+    }
+
 #endif
-		
-	return NULL;	
+
+    return NULL;
 }//end: rathread_self()
 
 
-int rathread_get_tid(){
+int rathread_get_tid()
+{
 
-#ifdef HAS_TLS	
-	return g_rathread_ID;
+#ifdef HAS_TLS
+    return g_rathread_ID;
 #else
-	// todo
-	#ifdef WIN32
-		return (int)GetCurrentThreadId();
-	#else
-		return (intptr_t)pthread_self();
-	#endif
-	
+    // todo
+#ifdef WIN32
+    return (int)GetCurrentThreadId();
+#else
+    return (intptr_t)pthread_self();
+#endif
+
 #endif
-	
+
 }//end: rathread_get_tid()
 
 
-bool rathread_wait( rAthread handle,  void* *out_exitCode ){
-	
-	// Hint:
-	// no thread data cleanup routine call here!
-	// its managed by the callProxy itself..
-	//
+bool rathread_wait(rAthread handle,  void* *out_exitCode)
+{
+
+    // Hint:
+    // no thread data cleanup routine call here!
+    // its managed by the callProxy itself..
+    //
 #ifdef WIN32
-	WaitForSingleObject(handle->hThread, INFINITE);
-	return true; 
+    WaitForSingleObject(handle->hThread, INFINITE);
+    return true;
 #else
-	if(pthread_join(handle->hThread, out_exitCode) == 0)
-		return true;
-	return false;
+    if (pthread_join(handle->hThread, out_exitCode) == 0)
+        return true;
+    return false;
 #endif
 
 }//end: rathread_wait()
 
 
-void rathread_prio_set( rAthread handle, RATHREAD_PRIO prio ){
-	handle->prio = RAT_PRIO_NORMAL; 
-	//@TODO 
+void rathread_prio_set(rAthread handle, RATHREAD_PRIO prio)
+{
+    handle->prio = RAT_PRIO_NORMAL;
+    //@TODO
 }//end: rathread_prio_set()
 
 
-RATHREAD_PRIO rathread_prio_get( rAthread handle){
-	return handle->prio;
+RATHREAD_PRIO rathread_prio_get(rAthread handle)
+{
+    return handle->prio;
 }//end: rathread_prio_get()
 
 
-void rathread_yield(){
-#ifdef WIN32 
-	SwitchToThread();
+void rathread_yield()
+{
+#ifdef WIN32
+    SwitchToThread();
 #else
-	sched_yield();
-#endif	
+    sched_yield();
+#endif
 }//end: rathread_yield()

+ 31 - 31
src/common/thread.h

@@ -1,19 +1,19 @@
 // Copyright (c) rAthena Project (www.rathena.org) - Licensed under GNU GPL
 // For more information, see LICENCE in the main folder
 
-#pragma once 
+#pragma once
 #ifndef _rA_THREAD_H_
 #define _rA_THREAD_H_
 
 #include "../common/cbasetypes.h"
 
 typedef struct rAthread *rAthread;
-typedef void* (*rAthreadProc)(void*);
+typedef void *(*rAthreadProc)(void *);
 
 typedef enum RATHREAD_PRIO {
-	RAT_PRIO_LOW = 0,
-	RAT_PRIO_NORMAL,
-	RAT_PRIO_HIGH	
+    RAT_PRIO_LOW = 0,
+    RAT_PRIO_NORMAL,
+    RAT_PRIO_HIGH
 } RATHREAD_PRIO;
 
 
@@ -22,51 +22,51 @@ typedef enum RATHREAD_PRIO {
  *
  * @param entyPoint  - entryProc,
  * @param param - general purpose parameter, would be given as parameter to the thread's entrypoint.
- * 
+ *
  * @return not NULL if success
  */
-rAthread rathread_create( rAthreadProc entryPoint,  void *param );
+rAthread rathread_create(rAthreadProc entryPoint,  void *param);
 
 
-/** 
+/**
  * Creates a new Thread (with more creation options)
  *
  * @param entyPoint  - entryProc,
  * @param param - general purpose parameter, would be given as parameter to the thread's entrypoint
- * @param szStack - stack Size in bytes 
+ * @param szStack - stack Size in bytes
  * @param prio - Priority of the Thread @ OS Scheduler..
  *
  * @return not NULL if success
  */
-rAthread rathread_createEx( rAthreadProc entryPoint,  void *param,  size_t szStack,  RATHREAD_PRIO prio );
+rAthread rathread_createEx(rAthreadProc entryPoint,  void *param,  size_t szStack,  RATHREAD_PRIO prio);
 
 
 /**
  * Destroys the given Thread immediatly
  *
- * @note The Handle gets invalid after call! dont use it afterwards. 
+ * @note The Handle gets invalid after call! dont use it afterwards.
  *
  * @param handle - thread to destroy.
  */
-void rathread_destroy ( rAthread handle );
+void rathread_destroy(rAthread handle);
 
 
-/** 
+/**
  * Returns the thread handle of the thread calling this function
- * 
+ *
  * @note this wont work @ programms main thread
- * @note the underlying implementation might not perform very well, cache the value received! 
- * 
+ * @note the underlying implementation might not perform very well, cache the value received!
+ *
  * @return not NULL if success
  */
-rAthread rathread_self( );
+rAthread rathread_self();
 
 
 /**
- * Returns own thrad id (TID) 
+ * Returns own thrad id (TID)
  *
- * @note this is an unique identifier for the calling thread, and 
- *        depends on platfrom / compiler, and may not be the systems Thread ID! 
+ * @note this is an unique identifier for the calling thread, and
+ *        depends on platfrom / compiler, and may not be the systems Thread ID!
  *
  * @return -1 when fails, otherwise >= 0
  */
@@ -74,39 +74,39 @@ int rathread_get_tid();
 
 
 /**
- * Waits for the given thread to terminate 
+ * Waits for the given thread to terminate
  *
  * @param handle - thread to wait (join) for
  * @param out_Exitcode - [OPTIONAL] - if given => Exitcode (value) of the given thread - if it's terminated
- * 
+ *
  * @return true - if the given thread has been terminated.
  */
-bool rathread_wait( rAthread handle,  void* *out_exitCode );
+bool rathread_wait(rAthread handle,  void* *out_exitCode);
 
 
-/** 
+/**
  * Sets the given PRIORITY @ OS Task Scheduler
- * 
+ *
  * @param handle - thread to set prio for
  * @param rio - the priority (RAT_PRIO_LOW ... )
  */
-void rathread_prio_set( rAthread handle, RATHREAD_PRIO prio );
+void rathread_prio_set(rAthread handle, RATHREAD_PRIO prio);
 
 
-/** 
+/**
  * Gets the current Prio of the given trhead
  *
  * @param handle - the thread to get the prio for.
  */
-RATHREAD_PRIO rathread_prio_get( rAthread handle);
+RATHREAD_PRIO rathread_prio_get(rAthread handle);
 
 
 /**
  * Tells the OS scheduler to yield the execution of the calling thread
- * 
+ *
  * @note: this will not "pause" the thread,
- *			it just allows the OS to spent the remaining time 
- *			of the slice to another thread.
+ *          it just allows the OS to spent the remaining time
+ *          of the slice to another thread.
  */
 void rathread_yield();
 

+ 236 - 243
src/common/timer.c

@@ -26,12 +26,12 @@
 #define TIMER_MAX_INTERVAL 1000
 
 // timers (array)
-static struct TimerData* timer_data = NULL;
+static struct TimerData *timer_data = NULL;
 static int timer_data_max = 0;
 static int timer_data_num = 0;
 
 // free timers (array)
-static int* free_timer_list = NULL;
+static int *free_timer_list = NULL;
 static int free_timer_list_max = 0;
 static int free_timer_list_pos = 0;
 
@@ -53,85 +53,87 @@ time_t start_time;
 
 
 /*----------------------------
- * 	Timer debugging
+ *  Timer debugging
  *----------------------------*/
 struct timer_func_list {
-	struct timer_func_list* next;
-	TimerFunc func;
-	char* name;
+    struct timer_func_list *next;
+    TimerFunc func;
+    char *name;
 } *tfl_root = NULL;
 
 /// Sets the name of a timer function.
-int add_timer_func_list(TimerFunc func, char* name)
+int add_timer_func_list(TimerFunc func, char *name)
 {
-	struct timer_func_list* tfl;
-
-	if (name) {
-		for( tfl=tfl_root; tfl != NULL; tfl=tfl->next )
-		{// check suspicious cases
-			if( func == tfl->func )
-				ShowWarning("add_timer_func_list: duplicating function %p(%s) as %s.\n",tfl->func,tfl->name,name);
-			else if( strcmp(name,tfl->name) == 0 )
-				ShowWarning("add_timer_func_list: function %p has the same name as %p(%s)\n",func,tfl->func,tfl->name);
-		}
-		CREATE(tfl,struct timer_func_list,1);
-		tfl->next = tfl_root;
-		tfl->func = func;
-		tfl->name = aStrdup(name);
-		tfl_root = tfl;
-	}
-	return 0;
+    struct timer_func_list *tfl;
+
+    if (name) {
+        for (tfl=tfl_root; tfl != NULL; tfl=tfl->next) {
+            // check suspicious cases
+            if (func == tfl->func)
+                ShowWarning("add_timer_func_list: duplicating function %p(%s) as %s.\n",tfl->func,tfl->name,name);
+            else if (strcmp(name,tfl->name) == 0)
+                ShowWarning("add_timer_func_list: function %p has the same name as %p(%s)\n",func,tfl->func,tfl->name);
+        }
+        CREATE(tfl,struct timer_func_list,1);
+        tfl->next = tfl_root;
+        tfl->func = func;
+        tfl->name = aStrdup(name);
+        tfl_root = tfl;
+    }
+    return 0;
 }
 
 /// Returns the name of the timer function.
-char* search_timer_func_list(TimerFunc func)
+char *search_timer_func_list(TimerFunc func)
 {
-	struct timer_func_list* tfl;
+    struct timer_func_list *tfl;
 
-	for( tfl=tfl_root; tfl != NULL; tfl=tfl->next )
-		if (func == tfl->func)
-			return tfl->name;
+    for (tfl=tfl_root; tfl != NULL; tfl=tfl->next)
+        if (func == tfl->func)
+            return tfl->name;
 
-	return "unknown timer function";
+    return "unknown timer function";
 }
 
 /*----------------------------
- * 	Get tick time
+ *  Get tick time
  *----------------------------*/
 
 #if defined(ENABLE_RDTSC)
 static uint64 RDTSC_BEGINTICK = 0,   RDTSC_CLOCK = 0;
 
-static __inline uint64 _rdtsc(){
-	register union{
-		uint64	qw;
-		uint32 	dw[2];
-	} t;
+static __inline uint64 _rdtsc()
+{
+    register union {
+        uint64  qw;
+        uint32  dw[2];
+    } t;
+
+    asm volatile("rdtsc":"=a"(t.dw[0]), "=d"(t.dw[1]));
 
-	asm volatile("rdtsc":"=a"(t.dw[0]), "=d"(t.dw[1]) );
-	
-	return t.qw;
+    return t.qw;
 }
 
-static void rdtsc_calibrate(){
-	uint64 t1, t2;
-	int32 i;
-	
-	ShowStatus("Calibrating Timer Source, please wait... ");
-	
-	RDTSC_CLOCK = 0;
-	
-	for(i = 0; i < 5; i++){
-		t1 = _rdtsc();
-		usleep(1000000); //1000 MS
-		t2 = _rdtsc();
-		RDTSC_CLOCK += (t2 - t1) / 1000; 
-	}
-	RDTSC_CLOCK /= 5;
-	
-	RDTSC_BEGINTICK = _rdtsc();
-	
-	ShowMessage(" done. (Frequency: %u Mhz)\n", (uint32)(RDTSC_CLOCK/1000) );
+static void rdtsc_calibrate()
+{
+    uint64 t1, t2;
+    int32 i;
+
+    ShowStatus("Calibrating Timer Source, please wait... ");
+
+    RDTSC_CLOCK = 0;
+
+    for (i = 0; i < 5; i++) {
+        t1 = _rdtsc();
+        usleep(1000000); //1000 MS
+        t2 = _rdtsc();
+        RDTSC_CLOCK += (t2 - t1) / 1000;
+    }
+    RDTSC_CLOCK /= 5;
+
+    RDTSC_BEGINTICK = _rdtsc();
+
+    ShowMessage(" done. (Frequency: %u Mhz)\n", (uint32)(RDTSC_CLOCK/1000));
 }
 
 #endif
@@ -140,19 +142,19 @@ static void rdtsc_calibrate(){
 static unsigned int tick(void)
 {
 #if defined(WIN32)
-	return GetTickCount();
+    return GetTickCount();
 #elif defined(ENABLE_RDTSC)
-	//
-		return (unsigned int)((_rdtsc() - RDTSC_BEGINTICK) / RDTSC_CLOCK);
-	//
+    //
+    return (unsigned int)((_rdtsc() - RDTSC_BEGINTICK) / RDTSC_CLOCK);
+    //
 #elif defined(HAVE_MONOTONIC_CLOCK)
-	struct timespec tval;
-	clock_gettime(CLOCK_MONOTONIC, &tval);
-	return tval.tv_sec * 1000 + tval.tv_nsec / 1000000;
+    struct timespec tval;
+    clock_gettime(CLOCK_MONOTONIC, &tval);
+    return tval.tv_sec * 1000 + tval.tv_nsec / 1000000;
 #else
-	struct timeval tval;
-	gettimeofday(&tval, NULL);
-	return tval.tv_sec * 1000 + tval.tv_usec / 1000;
+    struct timeval tval;
+    gettimeofday(&tval, NULL);
+    return tval.tv_sec * 1000 + tval.tv_usec / 1000;
 #endif
 }
 
@@ -165,14 +167,14 @@ static int gettick_count = 1;
 
 unsigned int gettick_nocache(void)
 {
-	gettick_count = TICK_CACHE;
-	gettick_cache = tick();
-	return gettick_cache;
+    gettick_count = TICK_CACHE;
+    gettick_cache = tick();
+    return gettick_cache;
 }
 
 unsigned int gettick(void)
 {
-	return ( --gettick_count == 0 ) ? gettick_nocache() : gettick_cache;
+    return (--gettick_count == 0) ? gettick_nocache() : gettick_cache;
 }
 //////////////////////////////
 #else
@@ -180,110 +182,108 @@ unsigned int gettick(void)
 // tick doesn't get cached
 unsigned int gettick_nocache(void)
 {
-	return tick();
+    return tick();
 }
 
 unsigned int gettick(void)
 {
-	return tick();
+    return tick();
 }
 //////////////////////////////////////////////////////////////////////////
 #endif
 //////////////////////////////////////////////////////////////////////////
 
 /*======================================
- * 	CORE : Timer Heap
+ *  CORE : Timer Heap
  *--------------------------------------*/
 
 /// Adds a timer to the timer_heap
 static void push_timer_heap(int tid)
 {
-	BHEAP_ENSURE(timer_heap, 1, 256);
-	BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP);
+    BHEAP_ENSURE(timer_heap, 1, 256);
+    BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP);
 }
 
 /*==========================
- * 	Timer Management
+ *  Timer Management
  *--------------------------*/
 
 /// Returns a free timer id.
 static int acquire_timer(void)
 {
-	int tid;
-
-	// select a free timer
-	if (free_timer_list_pos) {
-		do {
-			tid = free_timer_list[--free_timer_list_pos];
-		} while(tid >= timer_data_num && free_timer_list_pos > 0);
-	} else
-		tid = timer_data_num;
-
-	// check available space
-	if( tid >= timer_data_num )
-		for (tid = timer_data_num; tid < timer_data_max && timer_data[tid].type; tid++);
-	if (tid >= timer_data_num && tid >= timer_data_max)
-	{// expand timer array
-		timer_data_max += 256;
-		if( timer_data )
-			RECREATE(timer_data, struct TimerData, timer_data_max);
-		else
-			CREATE(timer_data, struct TimerData, timer_data_max);
-		memset(timer_data + (timer_data_max - 256), 0, sizeof(struct TimerData)*256);
-	}
-
-	if( tid >= timer_data_num )
-		timer_data_num = tid + 1;
-
-	return tid;
+    int tid;
+
+    // select a free timer
+    if (free_timer_list_pos) {
+        do {
+            tid = free_timer_list[--free_timer_list_pos];
+        } while (tid >= timer_data_num && free_timer_list_pos > 0);
+    } else
+        tid = timer_data_num;
+
+    // check available space
+    if (tid >= timer_data_num)
+        for (tid = timer_data_num; tid < timer_data_max && timer_data[tid].type; tid++);
+    if (tid >= timer_data_num && tid >= timer_data_max) {
+        // expand timer array
+        timer_data_max += 256;
+        if (timer_data)
+            RECREATE(timer_data, struct TimerData, timer_data_max);
+        else
+            CREATE(timer_data, struct TimerData, timer_data_max);
+        memset(timer_data + (timer_data_max - 256), 0, sizeof(struct TimerData)*256);
+    }
+
+    if (tid >= timer_data_num)
+        timer_data_num = tid + 1;
+
+    return tid;
 }
 
 /// Starts a new timer that is deleted once it expires (single-use).
 /// Returns the timer's id.
 int add_timer(unsigned int tick, TimerFunc func, int id, intptr_t data)
 {
-	int tid;
-	
-	tid = acquire_timer();
-	timer_data[tid].tick     = tick;
-	timer_data[tid].func     = func;
-	timer_data[tid].id       = id;
-	timer_data[tid].data     = data;
-	timer_data[tid].type     = TIMER_ONCE_AUTODEL;
-	timer_data[tid].interval = 1000;
-	push_timer_heap(tid);
-
-	return tid;
+    int tid;
+
+    tid = acquire_timer();
+    timer_data[tid].tick     = tick;
+    timer_data[tid].func     = func;
+    timer_data[tid].id       = id;
+    timer_data[tid].data     = data;
+    timer_data[tid].type     = TIMER_ONCE_AUTODEL;
+    timer_data[tid].interval = 1000;
+    push_timer_heap(tid);
+
+    return tid;
 }
 
 /// Starts a new timer that automatically restarts itself (infinite loop until manually removed).
 /// Returns the timer's id, or INVALID_TIMER if it fails.
 int add_timer_interval(unsigned int tick, TimerFunc func, int id, intptr_t data, int interval)
 {
-	int tid;
-
-	if( interval < 1 )
-	{
-		ShowError("add_timer_interval: invalid interval (tick=%u %p[%s] id=%d data=%d diff_tick=%d)\n", tick, func, search_timer_func_list(func), id, data, DIFF_TICK(tick, gettick()));
-		return INVALID_TIMER;
-	}
-	
-	tid = acquire_timer();
-	timer_data[tid].tick     = tick;
-	timer_data[tid].func     = func;
-	timer_data[tid].id       = id;
-	timer_data[tid].data     = data;
-	timer_data[tid].type     = TIMER_INTERVAL;
-	timer_data[tid].interval = interval;
-	push_timer_heap(tid);
-
-	return tid;
+    int tid;
+
+    if (interval < 1) {
+        ShowError("add_timer_interval: invalid interval (tick=%u %p[%s] id=%d data=%d diff_tick=%d)\n", tick, func, search_timer_func_list(func), id, data, DIFF_TICK(tick, gettick()));
+        return INVALID_TIMER;
+    }
+
+    tid = acquire_timer();
+    timer_data[tid].tick     = tick;
+    timer_data[tid].func     = func;
+    timer_data[tid].id       = id;
+    timer_data[tid].data     = data;
+    timer_data[tid].type     = TIMER_INTERVAL;
+    timer_data[tid].interval = interval;
+    push_timer_heap(tid);
+
+    return tid;
 }
 
 /// Retrieves internal timer data
-const struct TimerData* get_timer(int tid)
-{
-	return ( tid >= 0 && tid < timer_data_num ) ? &timer_data[tid] : NULL;
+const struct TimerData *get_timer(int tid) {
+    return (tid >= 0 && tid < timer_data_num) ? &timer_data[tid] : NULL;
 }
 
 /// Marks a timer specified by 'id' for immediate deletion once it expires.
@@ -291,142 +291,135 @@ const struct TimerData* get_timer(int tid)
 /// Returns 0 on success, < 0 on failure.
 int delete_timer(int tid, TimerFunc func)
 {
-	if( tid < 0 || tid >= timer_data_num )
-	{
-		ShowError("delete_timer error : no such timer %d (%p(%s))\n", tid, func, search_timer_func_list(func));
-		return -1;
-	}
-	if( timer_data[tid].func != func )
-	{
-		ShowError("delete_timer error : function mismatch %p(%s) != %p(%s)\n", timer_data[tid].func, search_timer_func_list(timer_data[tid].func), func, search_timer_func_list(func));
-		return -2;
-	}
-
-	timer_data[tid].func = NULL;
-	timer_data[tid].type = TIMER_ONCE_AUTODEL;
-
-	return 0;
+    if (tid < 0 || tid >= timer_data_num) {
+        ShowError("delete_timer error : no such timer %d (%p(%s))\n", tid, func, search_timer_func_list(func));
+        return -1;
+    }
+    if (timer_data[tid].func != func) {
+        ShowError("delete_timer error : function mismatch %p(%s) != %p(%s)\n", timer_data[tid].func, search_timer_func_list(timer_data[tid].func), func, search_timer_func_list(func));
+        return -2;
+    }
+
+    timer_data[tid].func = NULL;
+    timer_data[tid].type = TIMER_ONCE_AUTODEL;
+
+    return 0;
 }
 
 /// Adjusts a timer's expiration time.
 /// Returns the new tick value, or -1 if it fails.
 int addtick_timer(int tid, unsigned int tick)
 {
-	return settick_timer(tid, timer_data[tid].tick+tick);
+    return settick_timer(tid, timer_data[tid].tick+tick);
 }
 
 /// Modifies a timer's expiration time (an alternative to deleting a timer and starting a new one).
 /// Returns the new tick value, or -1 if it fails.
 int settick_timer(int tid, unsigned int tick)
 {
-	size_t i;
-	
-	// search timer position
-	ARR_FIND(0, BHEAP_LENGTH(timer_heap), i, BHEAP_DATA(timer_heap)[i] == tid);
-	if( i == BHEAP_LENGTH(timer_heap) )
-	{
-		ShowError("settick_timer: no such timer %d (%p(%s))\n", tid, timer_data[tid].func, search_timer_func_list(timer_data[tid].func));
-		return -1;
-	}
-
-	if( (int)tick == -1 )
-		tick = 0;// add 1ms to avoid the error value -1
-
-	if( timer_data[tid].tick == tick )
-		return (int)tick;// nothing to do, already in propper position
-
-	// pop and push adjusted timer
-	BHEAP_POPINDEX(timer_heap, i, DIFFTICK_MINTOPCMP);
-	timer_data[tid].tick = tick;
-	BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP);
-	return (int)tick;
+    size_t i;
+
+    // search timer position
+    ARR_FIND(0, BHEAP_LENGTH(timer_heap), i, BHEAP_DATA(timer_heap)[i] == tid);
+    if (i == BHEAP_LENGTH(timer_heap)) {
+        ShowError("settick_timer: no such timer %d (%p(%s))\n", tid, timer_data[tid].func, search_timer_func_list(timer_data[tid].func));
+        return -1;
+    }
+
+    if ((int)tick == -1)
+        tick = 0;// add 1ms to avoid the error value -1
+
+    if (timer_data[tid].tick == tick)
+        return (int)tick;// nothing to do, already in propper position
+
+    // pop and push adjusted timer
+    BHEAP_POPINDEX(timer_heap, i, DIFFTICK_MINTOPCMP);
+    timer_data[tid].tick = tick;
+    BHEAP_PUSH(timer_heap, tid, DIFFTICK_MINTOPCMP);
+    return (int)tick;
 }
 
 /// Executes all expired timers.
 /// Returns the value of the smallest non-expired timer (or 1 second if there aren't any).
 int do_timer(unsigned int tick)
 {
-	int diff = TIMER_MAX_INTERVAL; // return value
-
-	// process all timers one by one
-	while( BHEAP_LENGTH(timer_heap) )
-	{
-		int tid = BHEAP_PEEK(timer_heap);// top element in heap (smallest tick)
-
-		diff = DIFF_TICK(timer_data[tid].tick, tick);
-		if( diff > 0 )
-			break; // no more expired timers to process
-
-		// remove timer
-		BHEAP_POP(timer_heap, DIFFTICK_MINTOPCMP);
-		timer_data[tid].type |= TIMER_REMOVE_HEAP;
-
-		if( timer_data[tid].func )
-		{
-			if( diff < -1000 )
-				// timer was delayed for more than 1 second, use current tick instead
-				timer_data[tid].func(tid, tick, timer_data[tid].id, timer_data[tid].data);
-			else
-				timer_data[tid].func(tid, timer_data[tid].tick, timer_data[tid].id, timer_data[tid].data);
-		}
-
-		// in the case the function didn't change anything...
-		if( timer_data[tid].type & TIMER_REMOVE_HEAP )
-		{
-			timer_data[tid].type &= ~TIMER_REMOVE_HEAP;
-
-			switch( timer_data[tid].type )
-			{
-			default:
-			case TIMER_ONCE_AUTODEL:
-				timer_data[tid].type = 0;
-				if (free_timer_list_pos >= free_timer_list_max) {
-					free_timer_list_max += 256;
-					RECREATE(free_timer_list,int,free_timer_list_max);
-					memset(free_timer_list + (free_timer_list_max - 256), 0, 256 * sizeof(int));
-				}
-				free_timer_list[free_timer_list_pos++] = tid;
-			break;
-			case TIMER_INTERVAL:
-				if( DIFF_TICK(timer_data[tid].tick, tick) < -1000 )
-					timer_data[tid].tick = tick + timer_data[tid].interval;
-				else
-					timer_data[tid].tick += timer_data[tid].interval;
-				push_timer_heap(tid);
-			break;
-			}
-		}
-	}
-
-	return cap_value(diff, TIMER_MIN_INTERVAL, TIMER_MAX_INTERVAL);
+    int diff = TIMER_MAX_INTERVAL; // return value
+
+    // process all timers one by one
+    while (BHEAP_LENGTH(timer_heap)) {
+        int tid = BHEAP_PEEK(timer_heap);// top element in heap (smallest tick)
+
+        diff = DIFF_TICK(timer_data[tid].tick, tick);
+        if (diff > 0)
+            break; // no more expired timers to process
+
+        // remove timer
+        BHEAP_POP(timer_heap, DIFFTICK_MINTOPCMP);
+        timer_data[tid].type |= TIMER_REMOVE_HEAP;
+
+        if (timer_data[tid].func) {
+            if (diff < -1000)
+                // timer was delayed for more than 1 second, use current tick instead
+                timer_data[tid].func(tid, tick, timer_data[tid].id, timer_data[tid].data);
+            else
+                timer_data[tid].func(tid, timer_data[tid].tick, timer_data[tid].id, timer_data[tid].data);
+        }
+
+        // in the case the function didn't change anything...
+        if (timer_data[tid].type & TIMER_REMOVE_HEAP) {
+            timer_data[tid].type &= ~TIMER_REMOVE_HEAP;
+
+            switch (timer_data[tid].type) {
+                default:
+                case TIMER_ONCE_AUTODEL:
+                    timer_data[tid].type = 0;
+                    if (free_timer_list_pos >= free_timer_list_max) {
+                        free_timer_list_max += 256;
+                        RECREATE(free_timer_list,int,free_timer_list_max);
+                        memset(free_timer_list + (free_timer_list_max - 256), 0, 256 * sizeof(int));
+                    }
+                    free_timer_list[free_timer_list_pos++] = tid;
+                    break;
+                case TIMER_INTERVAL:
+                    if (DIFF_TICK(timer_data[tid].tick, tick) < -1000)
+                        timer_data[tid].tick = tick + timer_data[tid].interval;
+                    else
+                        timer_data[tid].tick += timer_data[tid].interval;
+                    push_timer_heap(tid);
+                    break;
+            }
+        }
+    }
+
+    return cap_value(diff, TIMER_MIN_INTERVAL, TIMER_MAX_INTERVAL);
 }
 
 unsigned long get_uptime(void)
 {
-	return (unsigned long)difftime(time(NULL), start_time);
+    return (unsigned long)difftime(time(NULL), start_time);
 }
 
 void timer_init(void)
 {
 #if defined(ENABLE_RDTSC)
-	rdtsc_calibrate();
+    rdtsc_calibrate();
 #endif
 
-	time(&start_time);
+    time(&start_time);
 }
 
 void timer_final(void)
 {
-	struct timer_func_list *tfl;
-	struct timer_func_list *next;
-
-	for( tfl=tfl_root; tfl != NULL; tfl = next ) {
-		next = tfl->next;	// copy next pointer
-		aFree(tfl->name);	// free structures
-		aFree(tfl);
-	}
-
-	if (timer_data) aFree(timer_data);
-	BHEAP_CLEAR(timer_heap);
-	if (free_timer_list) aFree(free_timer_list);
+    struct timer_func_list *tfl;
+    struct timer_func_list *next;
+
+    for (tfl=tfl_root; tfl != NULL; tfl = next) {
+        next = tfl->next;   // copy next pointer
+        aFree(tfl->name);   // free structures
+        aFree(tfl);
+    }
+
+    if (timer_data) aFree(timer_data);
+    BHEAP_CLEAR(timer_heap);
+    if (free_timer_list) aFree(free_timer_list);
 }

+ 16 - 16
src/common/timer.h

@@ -1,8 +1,8 @@
 // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
 // For more information, see LICENCE in the main folder
 
-#ifndef	_TIMER_H_
-#define	_TIMER_H_
+#ifndef _TIMER_H_
+#define _TIMER_H_
 
 #include "../common/cbasetypes.h"
 
@@ -12,9 +12,9 @@
 
 // timer flags
 enum {
-	TIMER_ONCE_AUTODEL = 0x01,
-	TIMER_INTERVAL = 0x02,
-	TIMER_REMOVE_HEAP = 0x10,
+    TIMER_ONCE_AUTODEL = 0x01,
+    TIMER_INTERVAL = 0x02,
+    TIMER_REMOVE_HEAP = 0x10,
 };
 
 // Struct declaration
@@ -22,15 +22,15 @@ enum {
 typedef int (*TimerFunc)(int tid, unsigned int tick, int id, intptr_t data);
 
 struct TimerData {
-	unsigned int tick;
-	TimerFunc func;
-	int type;
-	int interval;
-	int heap_pos;
-
-	// general-purpose storage
-	int id; 
-	intptr_t data;
+    unsigned int tick;
+    TimerFunc func;
+    int type;
+    int interval;
+    int heap_pos;
+
+    // general-purpose storage
+    int id;
+    intptr_t data;
 };
 
 // Function prototype declaration
@@ -40,13 +40,13 @@ unsigned int gettick_nocache(void);
 
 int add_timer(unsigned int tick, TimerFunc func, int id, intptr_t data);
 int add_timer_interval(unsigned int tick, TimerFunc func, int id, intptr_t data, int interval);
-const struct TimerData* get_timer(int tid);
+const struct TimerData *get_timer(int tid);
 int delete_timer(int tid, TimerFunc func);
 
 int addtick_timer(int tid, unsigned int tick);
 int settick_timer(int tid, unsigned int tick);
 
-int add_timer_func_list(TimerFunc func, char* name);
+int add_timer_func_list(TimerFunc func, char *name);
 
 unsigned long get_uptime(void);
 

+ 198 - 205
src/common/utils.c

@@ -15,269 +15,262 @@
 #include <math.h> // floor()
 
 #ifdef WIN32
-	#include "../common/winapi.h"
-	#ifndef F_OK
-		#define F_OK   0x0
-	#endif  /* F_OK */
+#include "../common/winapi.h"
+#ifndef F_OK
+#define F_OK   0x0
+#endif  /* F_OK */
 #else
-	#include <unistd.h>
-	#include <dirent.h>
-	#include <sys/stat.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <sys/stat.h>
 #endif
 
 
 /// Dumps given buffer into file pointed to by a handle.
-void WriteDump(FILE* fp, const void* buffer, size_t length)
+void WriteDump(FILE *fp, const void *buffer, size_t length)
 {
-	size_t i;
-	char hex[48+1], ascii[16+1];
-
-	fprintf(fp, "--- 00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F   0123456789ABCDEF\n");
-	ascii[16] = 0;
-
-	for( i = 0; i < length; i++ )
-	{
-		char c = RBUFB(buffer,i);
-
-		ascii[i%16] = ISCNTRL(c) ? '.' : c;
-		sprintf(hex+(i%16)*3, "%02X ", RBUFB(buffer,i));
-
-		if( (i%16) == 15 )
-		{
-			fprintf(fp, "%03X %s  %s\n", (unsigned int)(i/16), hex, ascii);
-		}
-	}
-
-	if( (i%16) != 0 )
-	{
-		ascii[i%16] = 0;
-		fprintf(fp, "%03X %-48s  %-16s\n", (unsigned int)(i/16), hex, ascii);
-	}
+    size_t i;
+    char hex[48+1], ascii[16+1];
+
+    fprintf(fp, "--- 00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F   0123456789ABCDEF\n");
+    ascii[16] = 0;
+
+    for (i = 0; i < length; i++) {
+        char c = RBUFB(buffer,i);
+
+        ascii[i%16] = ISCNTRL(c) ? '.' : c;
+        sprintf(hex+(i%16)*3, "%02X ", RBUFB(buffer,i));
+
+        if ((i%16) == 15) {
+            fprintf(fp, "%03X %s  %s\n", (unsigned int)(i/16), hex, ascii);
+        }
+    }
+
+    if ((i%16) != 0) {
+        ascii[i%16] = 0;
+        fprintf(fp, "%03X %-48s  %-16s\n", (unsigned int)(i/16), hex, ascii);
+    }
 }
 
 
 /// Dumps given buffer on the console.
-void ShowDump(const void* buffer, size_t length)
+void ShowDump(const void *buffer, size_t length)
 {
-	size_t i;
-	char hex[48+1], ascii[16+1];
-
-	ShowDebug("--- 00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F   0123456789ABCDEF\n");
-	ascii[16] = 0;
-
-	for( i = 0; i < length; i++ )
-	{
-		char c = RBUFB(buffer,i);
-
-		ascii[i%16] = ISCNTRL(c) ? '.' : c;
-		sprintf(hex+(i%16)*3, "%02X ", RBUFB(buffer,i));
-
-		if( (i%16) == 15 )
-		{
-			ShowDebug("%03X %s  %s\n", i/16, hex, ascii);
-		}
-	}
-
-	if( (i%16) != 0 )
-	{
-		ascii[i%16] = 0;
-		ShowDebug("%03X %-48s  %-16s\n", i/16, hex, ascii);
-	}
+    size_t i;
+    char hex[48+1], ascii[16+1];
+
+    ShowDebug("--- 00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F   0123456789ABCDEF\n");
+    ascii[16] = 0;
+
+    for (i = 0; i < length; i++) {
+        char c = RBUFB(buffer,i);
+
+        ascii[i%16] = ISCNTRL(c) ? '.' : c;
+        sprintf(hex+(i%16)*3, "%02X ", RBUFB(buffer,i));
+
+        if ((i%16) == 15) {
+            ShowDebug("%03X %s  %s\n", i/16, hex, ascii);
+        }
+    }
+
+    if ((i%16) != 0) {
+        ascii[i%16] = 0;
+        ShowDebug("%03X %-48s  %-16s\n", i/16, hex, ascii);
+    }
 }
 
 
 #ifdef WIN32
 
-static char* checkpath(char *path, const char *srcpath)
-{	// just make sure the char*path is not const
-	char *p=path;
-	if(NULL!=path && NULL!=srcpath)
-	while(*srcpath) {
-		if (*srcpath=='/') {
-			*p++ = '\\';
-			srcpath++;
-		}
-		else
-			*p++ = *srcpath++;
-	}
-	*p = *srcpath; //EOS
-	return path;
+static char *checkpath(char *path, const char *srcpath)
+{
+    // just make sure the char*path is not const
+    char *p=path;
+    if (NULL!=path && NULL!=srcpath)
+        while (*srcpath) {
+            if (*srcpath=='/') {
+                *p++ = '\\';
+                srcpath++;
+            } else
+                *p++ = *srcpath++;
+        }
+    *p = *srcpath; //EOS
+    return path;
 }
 
-void findfile(const char *p, const char *pat, void (func)(const char*))
+void findfile(const char *p, const char *pat, void (func)(const char *))
 {
-	WIN32_FIND_DATAA FindFileData;
-	HANDLE hFind;
-	char tmppath[MAX_PATH+1];
-	
-	const char *path    = (p  ==NULL)? "." : p;
-	const char *pattern = (pat==NULL)? "" : pat;
-	
-	checkpath(tmppath,path);
-	if( PATHSEP != tmppath[strlen(tmppath)-1])
-		strcat(tmppath, "\\*");
-	else
-		strcat(tmppath, "*");
-	
-	hFind = FindFirstFileA(tmppath, &FindFileData);
-	if (hFind != INVALID_HANDLE_VALUE)
-	{
-		do
-		{
-			if (strcmp(FindFileData.cFileName, ".") == 0)
-				continue;
-			if (strcmp(FindFileData.cFileName, "..") == 0)
-				continue;
-
-			sprintf(tmppath,"%s%c%s",path,PATHSEP,FindFileData.cFileName);
-
-			if (FindFileData.cFileName && strstr(FindFileData.cFileName, pattern)) {
-				func( tmppath );
-			}
-
-
-			if( FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
-			{
-				findfile(tmppath, pat, func);
-			}
-		}while (FindNextFileA(hFind, &FindFileData) != 0);
-		FindClose(hFind);
-	}
-	return;
+    WIN32_FIND_DATAA FindFileData;
+    HANDLE hFind;
+    char tmppath[MAX_PATH+1];
+
+    const char *path    = (p  ==NULL)? "." : p;
+    const char *pattern = (pat==NULL)? "" : pat;
+
+    checkpath(tmppath,path);
+    if (PATHSEP != tmppath[strlen(tmppath)-1])
+        strcat(tmppath, "\\*");
+    else
+        strcat(tmppath, "*");
+
+    hFind = FindFirstFileA(tmppath, &FindFileData);
+    if (hFind != INVALID_HANDLE_VALUE) {
+        do {
+            if (strcmp(FindFileData.cFileName, ".") == 0)
+                continue;
+            if (strcmp(FindFileData.cFileName, "..") == 0)
+                continue;
+
+            sprintf(tmppath,"%s%c%s",path,PATHSEP,FindFileData.cFileName);
+
+            if (FindFileData.cFileName && strstr(FindFileData.cFileName, pattern)) {
+                func(tmppath);
+            }
+
+
+            if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
+                findfile(tmppath, pat, func);
+            }
+        } while (FindNextFileA(hFind, &FindFileData) != 0);
+        FindClose(hFind);
+    }
+    return;
 }
 #else
 
 #define MAX_DIR_PATH 2048
 
-static char* checkpath(char *path, const char*srcpath)
-{	// just make sure the char*path is not const
-	char *p=path;
-	if(NULL!=path && NULL!=srcpath)
-	while(*srcpath) {
-		if (*srcpath=='\\') {
-			*p++ = '/';
-			srcpath++;
-		}
-		else
-			*p++ = *srcpath++;
-	}
-	*p = *srcpath; //EOS
-	return path;
+static char *checkpath(char *path, const char *srcpath)
+{
+    // just make sure the char*path is not const
+    char *p=path;
+    if (NULL!=path && NULL!=srcpath)
+        while (*srcpath) {
+            if (*srcpath=='\\') {
+                *p++ = '/';
+                srcpath++;
+            } else
+                *p++ = *srcpath++;
+        }
+    *p = *srcpath; //EOS
+    return path;
 }
 
-void findfile(const char *p, const char *pat, void (func)(const char*))
+void findfile(const char *p, const char *pat, void (func)(const char *))
 {
-	DIR* dir;					// pointer to the scanned directory.
-	struct dirent* entry;		// pointer to one directory entry.
-	struct stat dir_stat;       // used by stat().
-	char tmppath[MAX_DIR_PATH+1];
-	char path[MAX_DIR_PATH+1]= ".";
-	const char *pattern = (pat==NULL)? "" : pat;
-	if(p!=NULL) strcpy(path,p);
-
-	// open the directory for reading
-	dir = opendir( checkpath(path, path) );
-	if (!dir) {
-		ShowError("Cannot read directory '%s'\n", path);
-		return;
-	}
-
-	// scan the directory, traversing each sub-directory
-	// matching the pattern for each file name.
-	while ((entry = readdir(dir))) {
-		// skip the "." and ".." entries.
-		if (strcmp(entry->d_name, ".") == 0)
-			continue;
-		if (strcmp(entry->d_name, "..") == 0)
-			continue;
-
-		sprintf(tmppath,"%s%c%s",path, PATHSEP, entry->d_name);
-
-		// check if the pattern matchs.
-		if (entry->d_name && strstr(entry->d_name, pattern)) {
-			func( tmppath );
-		}
-		// check if it is a directory.
-		if (stat(tmppath, &dir_stat) == -1) {
-			ShowError("stat error %s\n': ", tmppath);
-			continue;
-		}
-		// is this a directory?
-		if (S_ISDIR(dir_stat.st_mode)) {
-			// decent recursivly
-			findfile(tmppath, pat, func);
-		}
-	}//end while
-
-	closedir(dir);
+    DIR *dir;                   // pointer to the scanned directory.
+    struct dirent *entry;       // pointer to one directory entry.
+    struct stat dir_stat;       // used by stat().
+    char tmppath[MAX_DIR_PATH+1];
+    char path[MAX_DIR_PATH+1]= ".";
+    const char *pattern = (pat==NULL)? "" : pat;
+    if (p!=NULL) strcpy(path,p);
+
+    // open the directory for reading
+    dir = opendir(checkpath(path, path));
+    if (!dir) {
+        ShowError("Cannot read directory '%s'\n", path);
+        return;
+    }
+
+    // scan the directory, traversing each sub-directory
+    // matching the pattern for each file name.
+    while ((entry = readdir(dir))) {
+        // skip the "." and ".." entries.
+        if (strcmp(entry->d_name, ".") == 0)
+            continue;
+        if (strcmp(entry->d_name, "..") == 0)
+            continue;
+
+        sprintf(tmppath,"%s%c%s",path, PATHSEP, entry->d_name);
+
+        // check if the pattern matchs.
+        if (entry->d_name && strstr(entry->d_name, pattern)) {
+            func(tmppath);
+        }
+        // check if it is a directory.
+        if (stat(tmppath, &dir_stat) == -1) {
+            ShowError("stat error %s\n': ", tmppath);
+            continue;
+        }
+        // is this a directory?
+        if (S_ISDIR(dir_stat.st_mode)) {
+            // decent recursivly
+            findfile(tmppath, pat, func);
+        }
+    }//end while
+
+    closedir(dir);
 }
 #endif
 
-bool exists(const char* filename)
+bool exists(const char *filename)
 {
-	return !access(filename, F_OK);
+    return !access(filename, F_OK);
 }
 
 uint8 GetByte(uint32 val, int idx)
 {
-	switch( idx )
-	{
-	case 0: return (uint8)( (val & 0x000000FF)         );
-	case 1: return (uint8)( (val & 0x0000FF00) >> 0x08 );
-	case 2: return (uint8)( (val & 0x00FF0000) >> 0x10 );
-	case 3: return (uint8)( (val & 0xFF000000) >> 0x18 );
-	default:
+    switch (idx) {
+        case 0:
+            return (uint8)((val & 0x000000FF));
+        case 1:
+            return (uint8)((val & 0x0000FF00) >> 0x08);
+        case 2:
+            return (uint8)((val & 0x00FF0000) >> 0x10);
+        case 3:
+            return (uint8)((val & 0xFF000000) >> 0x18);
+        default:
 #if defined(DEBUG)
-		ShowDebug("GetByte: invalid index (idx=%d)\n", idx);
+            ShowDebug("GetByte: invalid index (idx=%d)\n", idx);
 #endif
-		return 0;
-	}
+            return 0;
+    }
 }
 
 uint16 GetWord(uint32 val, int idx)
 {
-	switch( idx )
-	{
-	case 0: return (uint16)( (val & 0x0000FFFF)         );
-	case 1: return (uint16)( (val & 0xFFFF0000) >> 0x10 );
-	default:
+    switch (idx) {
+        case 0:
+            return (uint16)((val & 0x0000FFFF));
+        case 1:
+            return (uint16)((val & 0xFFFF0000) >> 0x10);
+        default:
 #if defined(DEBUG)
-		ShowDebug("GetWord: invalid index (idx=%d)\n", idx);
+            ShowDebug("GetWord: invalid index (idx=%d)\n", idx);
 #endif
-		return 0;
-	}
+            return 0;
+    }
 }
 uint16 MakeWord(uint8 byte0, uint8 byte1)
 {
-	return byte0 | (byte1 << 0x08);
+    return byte0 | (byte1 << 0x08);
 }
 
 uint32 MakeDWord(uint16 word0, uint16 word1)
 {
-	return
-		( (uint32)(word0        ) )|
-		( (uint32)(word1 << 0x10) );
+    return
+        ((uint32)(word0))|
+        ((uint32)(word1 << 0x10));
 }
 
 
 /// calculates the value of A / B, in percent (rounded down)
 unsigned int get_percentage(const unsigned int A, const unsigned int B)
 {
-	double result;
+    double result;
 
-	if( B == 0 )
-	{
-		ShowError("get_percentage(): divison by zero! (A=%u,B=%u)\n", A, B);
-		return ~0U;
-	}
+    if (B == 0) {
+        ShowError("get_percentage(): divison by zero! (A=%u,B=%u)\n", A, B);
+        return ~0U;
+    }
 
-	result = 100 * ((double)A / (double)B);
+    result = 100 * ((double)A / (double)B);
 
-	if( result > UINT_MAX )
-	{
-		ShowError("get_percentage(): result percentage too high! (A=%u,B=%u,result=%g)\n", A, B, result);
-		return UINT_MAX;
-	}
+    if (result > UINT_MAX) {
+        ShowError("get_percentage(): result percentage too high! (A=%u,B=%u,result=%g)\n", A, B, result);
+        return UINT_MAX;
+    }
 
-	return (unsigned int)floor(result);
+    return (unsigned int)floor(result);
 }

+ 4 - 4
src/common/utils.h

@@ -8,11 +8,11 @@
 #include <stdio.h> // FILE*
 
 // generate a hex dump of the first 'length' bytes of 'buffer'
-void WriteDump(FILE* fp, const void* buffer, size_t length);
-void ShowDump(const void* buffer, size_t length);
+void WriteDump(FILE *fp, const void *buffer, size_t length);
+void ShowDump(const void *buffer, size_t length);
 
-void findfile(const char *p, const char *pat, void (func)(const char*));
-bool exists(const char* filename);
+void findfile(const char *p, const char *pat, void (func)(const char *));
+bool exists(const char *filename);
 
 //Caps values to min/max
 #define cap_value(a, min, max) ((a >= max) ? max : (a <= min) ? min : a)

+ 3 - 3
src/common/winapi.h

@@ -2,12 +2,12 @@
 
 
 #define STRICT
-#define NTDDI_VERSION 	NTDDI_WIN2K
+#define NTDDI_VERSION   NTDDI_WIN2K
 #define _WIN32_WINNT  0x0500
 #define WINVER 0x0500
-#define _WIN32_IE 	0x0600
+#define _WIN32_IE   0x0600
 #define WIN32_LEAN_AND_MEAN
-#define NOCOMM 
+#define NOCOMM
 #define NOKANJI
 #define NOHELP
 #define NOMCX

+ 37 - 37
src/config/const.h

@@ -13,85 +13,85 @@
  */
 
 /**
- * "Sane Checks" to save you from compiling with cool bugs 
+ * "Sane Checks" to save you from compiling with cool bugs
  **/
 #if SECURE_NPCTIMEOUT_INTERVAL <= 0
-	#error SECURE_NPCTIMEOUT_INTERVAL should be at least 1 (1s)
+#error SECURE_NPCTIMEOUT_INTERVAL should be at least 1 (1s)
 #endif
 #if SECURE_NPCTIMEOUT < 0
-	#error SECURE_NPCTIMEOUT cannot be lower than 0
+#error SECURE_NPCTIMEOUT cannot be lower than 0
 #endif
 
 /**
  * Path within the /db folder to (non-)renewal specific db files
  **/
 #ifdef RENEWAL
-	#define DBPATH "re/"
+#define DBPATH "re/"
 #else
-	#define DBPATH "pre-re/"
+#define DBPATH "pre-re/"
 #endif
 
 /**
  * DefType
  **/
 #ifdef RENEWAL
-	typedef short defType;
-	#define DEFTYPE_MIN SHRT_MIN
-	#define DEFTYPE_MAX SHRT_MAX
+typedef short defType;
+#define DEFTYPE_MIN SHRT_MIN
+#define DEFTYPE_MAX SHRT_MAX
 #else
-	typedef signed char defType;
-	#define DEFTYPE_MIN CHAR_MIN
-	#define DEFTYPE_MAX CHAR_MAX
+typedef signed char defType;
+#define DEFTYPE_MIN CHAR_MIN
+#define DEFTYPE_MAX CHAR_MAX
 #endif
 
 /* pointer size fix which fixes several gcc warnings */
 #ifdef __64BIT__
-	#define __64BPRTSIZE(y) (intptr)y
+#define __64BPRTSIZE(y) (intptr)y
 #else
-	#define __64BPRTSIZE(y) y
+#define __64BPRTSIZE(y) y
 #endif
 
 /* ATCMD_FUNC(mobinfo) HIT and FLEE calculations */
 #ifdef RENEWAL
-	#define MOB_FLEE(mob) ( mob->lv + mob->status.agi + mob->status.luk/5 + 100 )
-	#define MOB_HIT(mob)  ( mob->lv + mob->status.dex + mob->status.luk/3 + 175 )
+#define MOB_FLEE(mob) ( mob->lv + mob->status.agi + mob->status.luk/5 + 100 )
+#define MOB_HIT(mob)  ( mob->lv + mob->status.dex + mob->status.luk/3 + 175 )
 #else
-	#define MOB_FLEE(mob) ( mob->lv + mob->status.agi )
-	#define MOB_HIT(mob)  ( mob->lv + mob->status.dex )
+#define MOB_FLEE(mob) ( mob->lv + mob->status.agi )
+#define MOB_HIT(mob)  ( mob->lv + mob->status.dex )
 #endif
 
 /* Renewal's dmg level modifier, used as a macro for a easy way to turn off. */
 #ifdef RENEWAL_LVDMG
-	#define RE_LVL_DMOD(val) \
-		if( status_get_lv(src) > 100 && val > 0 ) \
-			skillratio = skillratio * status_get_lv(src) / val;
-	#define RE_LVL_MDMOD(val) \
-		if( status_get_lv(src) > 100 && val > 0) \
-			md.damage = md.damage * status_get_lv(src) / val;
-	/* ranger traps special */
-	#define RE_LVL_TMDMOD() \
-		if( status_get_lv(src) > 100 ) \
-			md.damage = md.damage * 150 / 100 + md.damage * status_get_lv(src) / 100;
+#define RE_LVL_DMOD(val) \
+    if( status_get_lv(src) > 100 && val > 0 ) \
+        skillratio = skillratio * status_get_lv(src) / val;
+#define RE_LVL_MDMOD(val) \
+    if( status_get_lv(src) > 100 && val > 0) \
+        md.damage = md.damage * status_get_lv(src) / val;
+/* ranger traps special */
+#define RE_LVL_TMDMOD() \
+    if( status_get_lv(src) > 100 ) \
+        md.damage = md.damage * 150 / 100 + md.damage * status_get_lv(src) / 100;
 #else
-	#define RE_LVL_DMOD(val) 
-	#define RE_LVL_MDMOD(val)
-	#define RE_LVL_TMDMOD()
+#define RE_LVL_DMOD(val)
+#define RE_LVL_MDMOD(val)
+#define RE_LVL_TMDMOD()
 #endif
 
 /* Feb 1st 2012 */
 #if PACKETVER >= 20120201
-	#define NEW_CARTS
-	#define MAX_CARTS 9
+#define NEW_CARTS
+#define MAX_CARTS 9
 #else
-	#define MAX_CARTS 5
+#define MAX_CARTS 5
 #endif
 
 // Renewal variable cast time reduction
 #ifdef RENEWAL_CAST
-	#define VARCAST_REDUCTION(val){ \
-		if( (varcast_r += val) != 0 && varcast_r >= 0 ) \
-			time = time * (1 - (float)min(val, 100) / 100); \
-	}
+#define VARCAST_REDUCTION(val){ \
+        if( (varcast_r += val) != 0 && varcast_r >= 0 ) \
+            time = time * (1 - (float)min(val, 100) / 100); \
+    }
 #endif
 /**
  * End of File

+ 112 - 115
src/login/account.h

@@ -12,144 +12,141 @@ typedef struct AccountDBIterator AccountDBIterator;
 
 
 // standard engines
-AccountDB* account_db_sql(void);
+AccountDB *account_db_sql(void);
 
 // extra engines (will probably use the other txt functions)
 #define ACCOUNTDB_CONSTRUCTOR_(engine) account_db_##engine
 #define ACCOUNTDB_CONSTRUCTOR(engine) ACCOUNTDB_CONSTRUCTOR_(engine)
 #ifdef ACCOUNTDB_ENGINE_0
-AccountDB* ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_0)(void);
+AccountDB *ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_0)(void);
 #endif
 #ifdef ACCOUNTDB_ENGINE_1
-AccountDB* ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_1)(void);
+AccountDB *ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_1)(void);
 #endif
 #ifdef ACCOUNTDB_ENGINE_2
-AccountDB* ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_2)(void);
+AccountDB *ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_2)(void);
 #endif
 #ifdef ACCOUNTDB_ENGINE_3
-AccountDB* ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_3)(void);
+AccountDB *ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_3)(void);
 #endif
 #ifdef ACCOUNTDB_ENGINE_4
-AccountDB* ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_4)(void);
+AccountDB *ACCOUNTDB_CONSTRUCTOR(ACCOUNTDB_ENGINE_4)(void);
 #endif
 
 
-struct mmo_account
-{
-	int account_id;
-	char userid[NAME_LENGTH];
-	char pass[32+1];        // 23+1 for plaintext, 32+1 for md5-ed passwords
-	char sex;               // gender (M/F/S)
-	char email[40];         // e-mail (by default: a@a.com)
-	int group_id;           // player group id
-	unsigned int state;     // packet 0x006a value + 1 (0: compte OK)
-	time_t unban_time;      // (timestamp): ban time limit of the account (0 = no ban)
-	time_t expiration_time; // (timestamp): validity limit of the account (0 = unlimited)
-	unsigned int logincount;// number of successful auth attempts
-	char lastlogin[24];     // date+time of last successful login
-	char last_ip[16];       // save of last IP of connection
-	char birthdate[10+1];   // assigned birth date (format: YYYY-MM-DD, default: 0000-00-00)
-	int account_reg2_num;
-	struct global_reg account_reg2[ACCOUNT_REG2_NUM]; // account script variables (stored on login server)
+struct mmo_account {
+    int account_id;
+    char userid[NAME_LENGTH];
+    char pass[32+1];        // 23+1 for plaintext, 32+1 for md5-ed passwords
+    char sex;               // gender (M/F/S)
+    char email[40];         // e-mail (by default: a@a.com)
+    int group_id;           // player group id
+    unsigned int state;     // packet 0x006a value + 1 (0: compte OK)
+    time_t unban_time;      // (timestamp): ban time limit of the account (0 = no ban)
+    time_t expiration_time; // (timestamp): validity limit of the account (0 = unlimited)
+    unsigned int logincount;// number of successful auth attempts
+    char lastlogin[24];     // date+time of last successful login
+    char last_ip[16];       // save of last IP of connection
+    char birthdate[10+1];   // assigned birth date (format: YYYY-MM-DD, default: 0000-00-00)
+    int account_reg2_num;
+    struct global_reg account_reg2[ACCOUNT_REG2_NUM]; // account script variables (stored on login server)
 };
 
 
-struct AccountDBIterator
-{
-	/// Destroys this iterator, releasing all allocated memory (including itself).
-	///
-	/// @param self Iterator
-	void (*destroy)(AccountDBIterator* self);
+struct AccountDBIterator {
+    /// Destroys this iterator, releasing all allocated memory (including itself).
+    ///
+    /// @param self Iterator
+    void (*destroy)(AccountDBIterator *self);
 
-	/// Fetches the next account in the database.
-	/// Fills acc with the account data.
-	/// @param self Iterator
-	/// @param acc Account data
-	/// @return true if successful
-	bool (*next)(AccountDBIterator* self, struct mmo_account* acc);
+    /// Fetches the next account in the database.
+    /// Fills acc with the account data.
+    /// @param self Iterator
+    /// @param acc Account data
+    /// @return true if successful
+    bool (*next)(AccountDBIterator *self, struct mmo_account *acc);
 };
 
 
-struct AccountDB
-{
-	/// Initializes this database, making it ready for use.
-	/// Call this after setting the properties.
-	///
-	/// @param self Database
-	/// @return true if successful
-	bool (*init)(AccountDB* self);
-
-	/// Destroys this database, releasing all allocated memory (including itself).
-	///
-	/// @param self Database
-	void (*destroy)(AccountDB* self);
-
-	/// Gets a property from this database.
-	/// These read-only properties must be implemented:
-	/// "engine.name" -> "txt", "sql", ...
-	/// "engine.version" -> internal version
-	/// "engine.comment" -> anything (suggestion: description or specs of the engine)
-	///
-	/// @param self Database
-	/// @param key Property name
-	/// @param buf Buffer for the value
-	/// @param buflen Buffer length
-	/// @return true if successful
-	bool (*get_property)(AccountDB* self, const char* key, char* buf, size_t buflen);
-
-	/// Sets a property in this database.
-	///
-	/// @param self Database
-	/// @param key Property name
-	/// @param value Property value
-	/// @return true if successful
-	bool (*set_property)(AccountDB* self, const char* key, const char* value);
-
-	/// Creates a new account in this database.
-	/// If acc->account_id is not -1, the provided value will be used.
-	/// Otherwise the account_id will be auto-generated and written to acc->account_id.
-	///
-	/// @param self Database
-	/// @param acc Account data
-	/// @return true if successful
-	bool (*create)(AccountDB* self, struct mmo_account* acc);
-
-	/// Removes an account from this database.
-	///
-	/// @param self Database
-	/// @param account_id Account id
-	/// @return true if successful
-	bool (*remove)(AccountDB* self, const int account_id);
-
-	/// Modifies the data of an existing account.
-	/// Uses acc->account_id to identify the account.
-	///
-	/// @param self Database
-	/// @param acc Account data
-	/// @return true if successful
-	bool (*save)(AccountDB* self, const struct mmo_account* acc);
-
-	/// Finds an account with account_id and copies it to acc.
-	///
-	/// @param self Database
-	/// @param acc Pointer that receives the account data
-	/// @param account_id Target account id
-	/// @return true if successful
-	bool (*load_num)(AccountDB* self, struct mmo_account* acc, const int account_id);
-
-	/// Finds an account with userid and copies it to acc.
-	///
-	/// @param self Database
-	/// @param acc Pointer that receives the account data
-	/// @param userid Target username
-	/// @return true if successful
-	bool (*load_str)(AccountDB* self, struct mmo_account* acc, const char* userid);
-
-	/// Returns a new forward iterator.
-	///
-	/// @param self Database
-	/// @return Iterator
-	AccountDBIterator* (*iterator)(AccountDB* self);
+struct AccountDB {
+    /// Initializes this database, making it ready for use.
+    /// Call this after setting the properties.
+    ///
+    /// @param self Database
+    /// @return true if successful
+    bool (*init)(AccountDB *self);
+
+    /// Destroys this database, releasing all allocated memory (including itself).
+    ///
+    /// @param self Database
+    void (*destroy)(AccountDB *self);
+
+    /// Gets a property from this database.
+    /// These read-only properties must be implemented:
+    /// "engine.name" -> "txt", "sql", ...
+    /// "engine.version" -> internal version
+    /// "engine.comment" -> anything (suggestion: description or specs of the engine)
+    ///
+    /// @param self Database
+    /// @param key Property name
+    /// @param buf Buffer for the value
+    /// @param buflen Buffer length
+    /// @return true if successful
+    bool (*get_property)(AccountDB *self, const char *key, char *buf, size_t buflen);
+
+    /// Sets a property in this database.
+    ///
+    /// @param self Database
+    /// @param key Property name
+    /// @param value Property value
+    /// @return true if successful
+    bool (*set_property)(AccountDB *self, const char *key, const char *value);
+
+    /// Creates a new account in this database.
+    /// If acc->account_id is not -1, the provided value will be used.
+    /// Otherwise the account_id will be auto-generated and written to acc->account_id.
+    ///
+    /// @param self Database
+    /// @param acc Account data
+    /// @return true if successful
+    bool (*create)(AccountDB *self, struct mmo_account *acc);
+
+    /// Removes an account from this database.
+    ///
+    /// @param self Database
+    /// @param account_id Account id
+    /// @return true if successful
+    bool (*remove)(AccountDB *self, const int account_id);
+
+    /// Modifies the data of an existing account.
+    /// Uses acc->account_id to identify the account.
+    ///
+    /// @param self Database
+    /// @param acc Account data
+    /// @return true if successful
+    bool (*save)(AccountDB *self, const struct mmo_account *acc);
+
+    /// Finds an account with account_id and copies it to acc.
+    ///
+    /// @param self Database
+    /// @param acc Pointer that receives the account data
+    /// @param account_id Target account id
+    /// @return true if successful
+    bool (*load_num)(AccountDB *self, struct mmo_account *acc, const int account_id);
+
+    /// Finds an account with userid and copies it to acc.
+    ///
+    /// @param self Database
+    /// @param acc Pointer that receives the account data
+    /// @param userid Target username
+    /// @return true if successful
+    bool (*load_str)(AccountDB *self, struct mmo_account *acc, const char *userid);
+
+    /// Returns a new forward iterator.
+    ///
+    /// @param self Database
+    /// @return Iterator
+    AccountDBIterator *(*iterator)(AccountDB *self);
 };
 
 

+ 543 - 580
src/login/account_sql.c

@@ -15,98 +15,96 @@
 #define ACCOUNT_SQL_DB_VERSION 20110114
 
 /// internal structure
-typedef struct AccountDB_SQL
-{
-	AccountDB vtable;    // public interface
-
-	Sql* accounts;       // SQL accounts storage
-
-	// global sql settings
-	char   global_db_hostname[32];
-	uint16 global_db_port;
-	char   global_db_username[32];
-	char   global_db_password[32];
-	char   global_db_database[32];
-	char   global_codepage[32];
-	// local sql settings
-	char   db_hostname[32];
-	uint16 db_port;
-	char   db_username[32];
-	char   db_password[32];
-	char   db_database[32];
-	char   codepage[32];
-	// other settings
-	bool case_sensitive;
-	char account_db[32];
-	char accreg_db[32];
+typedef struct AccountDB_SQL {
+    AccountDB vtable;    // public interface
+
+    Sql *accounts;       // SQL accounts storage
+
+    // global sql settings
+    char   global_db_hostname[32];
+    uint16 global_db_port;
+    char   global_db_username[32];
+    char   global_db_password[32];
+    char   global_db_database[32];
+    char   global_codepage[32];
+    // local sql settings
+    char   db_hostname[32];
+    uint16 db_port;
+    char   db_username[32];
+    char   db_password[32];
+    char   db_database[32];
+    char   codepage[32];
+    // other settings
+    bool case_sensitive;
+    char account_db[32];
+    char accreg_db[32];
 
 } AccountDB_SQL;
 
 /// internal structure
-typedef struct AccountDBIterator_SQL
-{
-	AccountDBIterator vtable;    // public interface
+typedef struct AccountDBIterator_SQL {
+    AccountDBIterator vtable;    // public interface
 
-	AccountDB_SQL* db;
-	int last_account_id;
+    AccountDB_SQL *db;
+    int last_account_id;
 } AccountDBIterator_SQL;
 
 /// internal functions
-static bool account_db_sql_init(AccountDB* self);
-static void account_db_sql_destroy(AccountDB* self);
-static bool account_db_sql_get_property(AccountDB* self, const char* key, char* buf, size_t buflen);
-static bool account_db_sql_set_property(AccountDB* self, const char* option, const char* value);
-static bool account_db_sql_create(AccountDB* self, struct mmo_account* acc);
-static bool account_db_sql_remove(AccountDB* self, const int account_id);
-static bool account_db_sql_save(AccountDB* self, const struct mmo_account* acc);
-static bool account_db_sql_load_num(AccountDB* self, struct mmo_account* acc, const int account_id);
-static bool account_db_sql_load_str(AccountDB* self, struct mmo_account* acc, const char* userid);
-static AccountDBIterator* account_db_sql_iterator(AccountDB* self);
-static void account_db_sql_iter_destroy(AccountDBIterator* self);
-static bool account_db_sql_iter_next(AccountDBIterator* self, struct mmo_account* acc);
-
-static bool mmo_auth_fromsql(AccountDB_SQL* db, struct mmo_account* acc, int account_id);
-static bool mmo_auth_tosql(AccountDB_SQL* db, const struct mmo_account* acc, bool is_new);
+static bool account_db_sql_init(AccountDB *self);
+static void account_db_sql_destroy(AccountDB *self);
+static bool account_db_sql_get_property(AccountDB *self, const char *key, char *buf, size_t buflen);
+static bool account_db_sql_set_property(AccountDB *self, const char *option, const char *value);
+static bool account_db_sql_create(AccountDB *self, struct mmo_account *acc);
+static bool account_db_sql_remove(AccountDB *self, const int account_id);
+static bool account_db_sql_save(AccountDB *self, const struct mmo_account *acc);
+static bool account_db_sql_load_num(AccountDB *self, struct mmo_account *acc, const int account_id);
+static bool account_db_sql_load_str(AccountDB *self, struct mmo_account *acc, const char *userid);
+static AccountDBIterator *account_db_sql_iterator(AccountDB *self);
+static void account_db_sql_iter_destroy(AccountDBIterator *self);
+static bool account_db_sql_iter_next(AccountDBIterator *self, struct mmo_account *acc);
+
+static bool mmo_auth_fromsql(AccountDB_SQL *db, struct mmo_account *acc, int account_id);
+static bool mmo_auth_tosql(AccountDB_SQL *db, const struct mmo_account *acc, bool is_new);
 
 /// public constructor
-AccountDB* account_db_sql(void)
+AccountDB *account_db_sql(void)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)aCalloc(1, sizeof(AccountDB_SQL));
-
-	// set up the vtable
-	db->vtable.init         = &account_db_sql_init;
-	db->vtable.destroy      = &account_db_sql_destroy;
-	db->vtable.get_property = &account_db_sql_get_property;
-	db->vtable.set_property = &account_db_sql_set_property;
-	db->vtable.save         = &account_db_sql_save;
-	db->vtable.create       = &account_db_sql_create;
-	db->vtable.remove       = &account_db_sql_remove;
-	db->vtable.load_num     = &account_db_sql_load_num;
-	db->vtable.load_str     = &account_db_sql_load_str;
-	db->vtable.iterator     = &account_db_sql_iterator;
-
-	// initialize to default values
-	db->accounts = NULL;
-	// global sql settings
-	safestrncpy(db->global_db_hostname, "127.0.0.1", sizeof(db->global_db_hostname));
-	db->global_db_port = 3306;
-	safestrncpy(db->global_db_username, "ragnarok", sizeof(db->global_db_username));
-	safestrncpy(db->global_db_password, "ragnarok", sizeof(db->global_db_password));
-	safestrncpy(db->global_db_database, "ragnarok", sizeof(db->global_db_database));
-	safestrncpy(db->global_codepage, "", sizeof(db->global_codepage));
-	// local sql settings
-	safestrncpy(db->db_hostname, "", sizeof(db->db_hostname));
-	db->db_port = 3306;
-	safestrncpy(db->db_username, "", sizeof(db->db_username));
-	safestrncpy(db->db_password, "", sizeof(db->db_password));
-	safestrncpy(db->db_database, "", sizeof(db->db_database));
-	safestrncpy(db->codepage, "", sizeof(db->codepage));
-	// other settings
-	db->case_sensitive = false;
-	safestrncpy(db->account_db, "login", sizeof(db->account_db));
-	safestrncpy(db->accreg_db, "global_reg_value", sizeof(db->accreg_db));
-
-	return &db->vtable;
+    AccountDB_SQL *db = (AccountDB_SQL *)aCalloc(1, sizeof(AccountDB_SQL));
+
+    // set up the vtable
+    db->vtable.init         = &account_db_sql_init;
+    db->vtable.destroy      = &account_db_sql_destroy;
+    db->vtable.get_property = &account_db_sql_get_property;
+    db->vtable.set_property = &account_db_sql_set_property;
+    db->vtable.save         = &account_db_sql_save;
+    db->vtable.create       = &account_db_sql_create;
+    db->vtable.remove       = &account_db_sql_remove;
+    db->vtable.load_num     = &account_db_sql_load_num;
+    db->vtable.load_str     = &account_db_sql_load_str;
+    db->vtable.iterator     = &account_db_sql_iterator;
+
+    // initialize to default values
+    db->accounts = NULL;
+    // global sql settings
+    safestrncpy(db->global_db_hostname, "127.0.0.1", sizeof(db->global_db_hostname));
+    db->global_db_port = 3306;
+    safestrncpy(db->global_db_username, "ragnarok", sizeof(db->global_db_username));
+    safestrncpy(db->global_db_password, "ragnarok", sizeof(db->global_db_password));
+    safestrncpy(db->global_db_database, "ragnarok", sizeof(db->global_db_database));
+    safestrncpy(db->global_codepage, "", sizeof(db->global_codepage));
+    // local sql settings
+    safestrncpy(db->db_hostname, "", sizeof(db->db_hostname));
+    db->db_port = 3306;
+    safestrncpy(db->db_username, "", sizeof(db->db_username));
+    safestrncpy(db->db_password, "", sizeof(db->db_password));
+    safestrncpy(db->db_database, "", sizeof(db->db_database));
+    safestrncpy(db->codepage, "", sizeof(db->codepage));
+    // other settings
+    db->case_sensitive = false;
+    safestrncpy(db->account_db, "login", sizeof(db->account_db));
+    safestrncpy(db->accreg_db, "global_reg_value", sizeof(db->accreg_db));
+
+    return &db->vtable;
 }
 
 
@@ -114,567 +112,532 @@ AccountDB* account_db_sql(void)
 
 
 /// establishes database connection
-static bool account_db_sql_init(AccountDB* self)
+static bool account_db_sql_init(AccountDB *self)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	Sql* sql_handle;
-	const char* username;
-	const char* password;
-	const char* hostname;
-	uint16      port;
-	const char* database;
-	const char* codepage;
-
-	db->accounts = Sql_Malloc();
-	sql_handle = db->accounts;
-
-	if( db->db_hostname[0] != '\0' )
-	{// local settings
-		username = db->db_username;
-		password = db->db_password;
-		hostname = db->db_hostname;
-		port     = db->db_port;
-		database = db->db_database;
-		codepage = db->codepage;
-	}
-	else
-	{// global settings
-		username = db->global_db_username;
-		password = db->global_db_password;
-		hostname = db->global_db_hostname;
-		port     = db->global_db_port;
-		database = db->global_db_database;
-		codepage = db->global_codepage;
-	}
-
-	if( SQL_ERROR == Sql_Connect(sql_handle, username, password, hostname, port, database) )
-	{
-		Sql_ShowDebug(sql_handle);
-		Sql_Free(db->accounts);
-		db->accounts = NULL;
-		return false;
-	}
-
-	if( codepage[0] != '\0' && SQL_ERROR == Sql_SetEncoding(sql_handle, codepage) )
-		Sql_ShowDebug(sql_handle);
-
-	return true;
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    Sql *sql_handle;
+    const char *username;
+    const char *password;
+    const char *hostname;
+    uint16      port;
+    const char *database;
+    const char *codepage;
+
+    db->accounts = Sql_Malloc();
+    sql_handle = db->accounts;
+
+    if (db->db_hostname[0] != '\0') {
+        // local settings
+        username = db->db_username;
+        password = db->db_password;
+        hostname = db->db_hostname;
+        port     = db->db_port;
+        database = db->db_database;
+        codepage = db->codepage;
+    } else {
+        // global settings
+        username = db->global_db_username;
+        password = db->global_db_password;
+        hostname = db->global_db_hostname;
+        port     = db->global_db_port;
+        database = db->global_db_database;
+        codepage = db->global_codepage;
+    }
+
+    if (SQL_ERROR == Sql_Connect(sql_handle, username, password, hostname, port, database)) {
+        Sql_ShowDebug(sql_handle);
+        Sql_Free(db->accounts);
+        db->accounts = NULL;
+        return false;
+    }
+
+    if (codepage[0] != '\0' && SQL_ERROR == Sql_SetEncoding(sql_handle, codepage))
+        Sql_ShowDebug(sql_handle);
+
+    return true;
 }
 
 /// disconnects from database
-static void account_db_sql_destroy(AccountDB* self)
+static void account_db_sql_destroy(AccountDB *self)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
 
-	Sql_Free(db->accounts);
-	db->accounts = NULL;
-	aFree(db);
+    Sql_Free(db->accounts);
+    db->accounts = NULL;
+    aFree(db);
 }
 
 /// Gets a property from this database.
-static bool account_db_sql_get_property(AccountDB* self, const char* key, char* buf, size_t buflen)
+static bool account_db_sql_get_property(AccountDB *self, const char *key, char *buf, size_t buflen)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	const char* signature;
-
-	signature = "engine.";
-	if( strncmpi(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "name") == 0 )
-			safesnprintf(buf, buflen, "sql");
-		else
-		if( strcmpi(key, "version") == 0 )
-			safesnprintf(buf, buflen, "%d", ACCOUNT_SQL_DB_VERSION);
-		else
-		if( strcmpi(key, "comment") == 0 )
-			safesnprintf(buf, buflen, "SQL Account Database");
-		else
-			return false;// not found
-		return true;
-	}
-
-	signature = "sql.";
-	if( strncmpi(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "db_hostname") == 0 )
-			safesnprintf(buf, buflen, "%s", db->global_db_hostname);
-		else
-		if( strcmpi(key, "db_port") == 0 )
-			safesnprintf(buf, buflen, "%d", db->global_db_port);
-		else
-		if( strcmpi(key, "db_username") == 0 )
-			safesnprintf(buf, buflen, "%s", db->global_db_username);
-		else
-		if(	strcmpi(key, "db_password") == 0 )
-			safesnprintf(buf, buflen, "%s", db->global_db_password);
-		else
-		if( strcmpi(key, "db_database") == 0 )
-			safesnprintf(buf, buflen, "%s", db->global_db_database);
-		else
-		if( strcmpi(key, "codepage") == 0 )
-			safesnprintf(buf, buflen, "%s", db->global_codepage);
-		else
-			return false;// not found
-		return true;
-	}
-
-	signature = "account.sql.";
-	if( strncmpi(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "db_hostname") == 0 )
-			safesnprintf(buf, buflen, "%s", db->db_hostname);
-		else
-		if( strcmpi(key, "db_port") == 0 )
-			safesnprintf(buf, buflen, "%d", db->db_port);
-		else
-		if( strcmpi(key, "db_username") == 0 )
-			safesnprintf(buf, buflen, "%s", db->db_username);
-		else
-		if(	strcmpi(key, "db_password") == 0 )
-			safesnprintf(buf, buflen, "%s", db->db_password);
-		else
-		if( strcmpi(key, "db_database") == 0 )
-			safesnprintf(buf, buflen, "%s", db->db_database);
-		else
-		if( strcmpi(key, "codepage") == 0 )
-			safesnprintf(buf, buflen, "%s", db->codepage);
-		else
-		if( strcmpi(key, "case_sensitive") == 0 )
-			safesnprintf(buf, buflen, "%d", (db->case_sensitive ? 1 : 0));
-		else
-		if( strcmpi(key, "account_db") == 0 )
-			safesnprintf(buf, buflen, "%s", db->account_db);
-		else
-		if( strcmpi(key, "accreg_db") == 0 )
-			safesnprintf(buf, buflen, "%s", db->accreg_db);
-		else
-			return false;// not found
-		return true;
-	}
-
-	return false;// not found
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    const char *signature;
+
+    signature = "engine.";
+    if (strncmpi(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "name") == 0)
+            safesnprintf(buf, buflen, "sql");
+        else if (strcmpi(key, "version") == 0)
+            safesnprintf(buf, buflen, "%d", ACCOUNT_SQL_DB_VERSION);
+        else if (strcmpi(key, "comment") == 0)
+            safesnprintf(buf, buflen, "SQL Account Database");
+        else
+            return false;// not found
+        return true;
+    }
+
+    signature = "sql.";
+    if (strncmpi(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "db_hostname") == 0)
+            safesnprintf(buf, buflen, "%s", db->global_db_hostname);
+        else if (strcmpi(key, "db_port") == 0)
+            safesnprintf(buf, buflen, "%d", db->global_db_port);
+        else if (strcmpi(key, "db_username") == 0)
+            safesnprintf(buf, buflen, "%s", db->global_db_username);
+        else if (strcmpi(key, "db_password") == 0)
+            safesnprintf(buf, buflen, "%s", db->global_db_password);
+        else if (strcmpi(key, "db_database") == 0)
+            safesnprintf(buf, buflen, "%s", db->global_db_database);
+        else if (strcmpi(key, "codepage") == 0)
+            safesnprintf(buf, buflen, "%s", db->global_codepage);
+        else
+            return false;// not found
+        return true;
+    }
+
+    signature = "account.sql.";
+    if (strncmpi(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "db_hostname") == 0)
+            safesnprintf(buf, buflen, "%s", db->db_hostname);
+        else if (strcmpi(key, "db_port") == 0)
+            safesnprintf(buf, buflen, "%d", db->db_port);
+        else if (strcmpi(key, "db_username") == 0)
+            safesnprintf(buf, buflen, "%s", db->db_username);
+        else if (strcmpi(key, "db_password") == 0)
+            safesnprintf(buf, buflen, "%s", db->db_password);
+        else if (strcmpi(key, "db_database") == 0)
+            safesnprintf(buf, buflen, "%s", db->db_database);
+        else if (strcmpi(key, "codepage") == 0)
+            safesnprintf(buf, buflen, "%s", db->codepage);
+        else if (strcmpi(key, "case_sensitive") == 0)
+            safesnprintf(buf, buflen, "%d", (db->case_sensitive ? 1 : 0));
+        else if (strcmpi(key, "account_db") == 0)
+            safesnprintf(buf, buflen, "%s", db->account_db);
+        else if (strcmpi(key, "accreg_db") == 0)
+            safesnprintf(buf, buflen, "%s", db->accreg_db);
+        else
+            return false;// not found
+        return true;
+    }
+
+    return false;// not found
 }
 
 /// if the option is supported, adjusts the internal state
-static bool account_db_sql_set_property(AccountDB* self, const char* key, const char* value)
+static bool account_db_sql_set_property(AccountDB *self, const char *key, const char *value)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	const char* signature;
-
-
-	signature = "sql.";
-	if( strncmp(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "db_hostname") == 0 )
-			safestrncpy(db->global_db_hostname, value, sizeof(db->global_db_hostname));
-		else
-		if( strcmpi(key, "db_port") == 0 )
-			db->global_db_port = (uint16)strtoul(value, NULL, 10);
-		else
-		if( strcmpi(key, "db_username") == 0 )
-			safestrncpy(db->global_db_username, value, sizeof(db->global_db_username));
-		else
-		if( strcmpi(key, "db_password") == 0 )
-			safestrncpy(db->global_db_password, value, sizeof(db->global_db_password));
-		else
-		if( strcmpi(key, "db_database") == 0 )
-			safestrncpy(db->global_db_database, value, sizeof(db->global_db_database));
-		else
-		if( strcmpi(key, "codepage") == 0 )
-			safestrncpy(db->global_codepage, value, sizeof(db->global_codepage));
-		else
-			return false;// not found
-		return true;
-	}
-
-	signature = "account.sql.";
-	if( strncmp(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "db_hostname") == 0 )
-			safestrncpy(db->db_hostname, value, sizeof(db->db_hostname));
-		else
-		if( strcmpi(key, "db_port") == 0 )
-			db->db_port = (uint16)strtoul(value, NULL, 10);
-		else
-		if( strcmpi(key, "db_username") == 0 )
-			safestrncpy(db->db_username, value, sizeof(db->db_username));
-		else
-		if( strcmpi(key, "db_password") == 0 )
-			safestrncpy(db->db_password, value, sizeof(db->db_password));
-		else
-		if( strcmpi(key, "db_database") == 0 )
-			safestrncpy(db->db_database, value, sizeof(db->db_database));
-		else
-		if( strcmpi(key, "codepage") == 0 )
-			safestrncpy(db->codepage, value, sizeof(db->codepage));
-		else
-		if( strcmpi(key, "case_sensitive") == 0 )
-			db->case_sensitive = config_switch(value);
-		else
-		if( strcmpi(key, "account_db") == 0 )
-			safestrncpy(db->account_db, value, sizeof(db->account_db));
-		else
-		if( strcmpi(key, "accreg_db") == 0 )
-			safestrncpy(db->accreg_db, value, sizeof(db->accreg_db));
-		else
-			return false;// not found
-		return true;
-	}
-
-	return false;// not found
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    const char *signature;
+
+
+    signature = "sql.";
+    if (strncmp(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "db_hostname") == 0)
+            safestrncpy(db->global_db_hostname, value, sizeof(db->global_db_hostname));
+        else if (strcmpi(key, "db_port") == 0)
+            db->global_db_port = (uint16)strtoul(value, NULL, 10);
+        else if (strcmpi(key, "db_username") == 0)
+            safestrncpy(db->global_db_username, value, sizeof(db->global_db_username));
+        else if (strcmpi(key, "db_password") == 0)
+            safestrncpy(db->global_db_password, value, sizeof(db->global_db_password));
+        else if (strcmpi(key, "db_database") == 0)
+            safestrncpy(db->global_db_database, value, sizeof(db->global_db_database));
+        else if (strcmpi(key, "codepage") == 0)
+            safestrncpy(db->global_codepage, value, sizeof(db->global_codepage));
+        else
+            return false;// not found
+        return true;
+    }
+
+    signature = "account.sql.";
+    if (strncmp(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "db_hostname") == 0)
+            safestrncpy(db->db_hostname, value, sizeof(db->db_hostname));
+        else if (strcmpi(key, "db_port") == 0)
+            db->db_port = (uint16)strtoul(value, NULL, 10);
+        else if (strcmpi(key, "db_username") == 0)
+            safestrncpy(db->db_username, value, sizeof(db->db_username));
+        else if (strcmpi(key, "db_password") == 0)
+            safestrncpy(db->db_password, value, sizeof(db->db_password));
+        else if (strcmpi(key, "db_database") == 0)
+            safestrncpy(db->db_database, value, sizeof(db->db_database));
+        else if (strcmpi(key, "codepage") == 0)
+            safestrncpy(db->codepage, value, sizeof(db->codepage));
+        else if (strcmpi(key, "case_sensitive") == 0)
+            db->case_sensitive = config_switch(value);
+        else if (strcmpi(key, "account_db") == 0)
+            safestrncpy(db->account_db, value, sizeof(db->account_db));
+        else if (strcmpi(key, "accreg_db") == 0)
+            safestrncpy(db->accreg_db, value, sizeof(db->accreg_db));
+        else
+            return false;// not found
+        return true;
+    }
+
+    return false;// not found
 }
 
 /// create a new account entry
 /// If acc->account_id is -1, the account id will be auto-generated,
 /// and its value will be written to acc->account_id if everything succeeds.
-static bool account_db_sql_create(AccountDB* self, struct mmo_account* acc)
+static bool account_db_sql_create(AccountDB *self, struct mmo_account *acc)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	Sql* sql_handle = db->accounts;
-
-	// decide on the account id to assign
-	int account_id;
-	if( acc->account_id != -1 )
-	{// caller specifies it manually
-		account_id = acc->account_id;
-	}
-	else
-	{// ask the database
-		char* data;
-		size_t len;
-
-		if( SQL_SUCCESS != Sql_Query(sql_handle, "SELECT MAX(`account_id`)+1 FROM `%s`", db->account_db) )
-		{
-			Sql_ShowDebug(sql_handle);
-			return false;
-		}
-		if( SQL_SUCCESS != Sql_NextRow(sql_handle) )
-		{
-			Sql_ShowDebug(sql_handle);
-			Sql_FreeResult(sql_handle);
-			return false;
-		}
-
-		Sql_GetData(sql_handle, 0, &data, &len);
-		account_id = ( data != NULL ) ? atoi(data) : 0;
-		Sql_FreeResult(sql_handle);
-
-		if( account_id < START_ACCOUNT_NUM )
-			account_id = START_ACCOUNT_NUM;
-
-	}
-
-	// zero value is prohibited
-	if( account_id == 0 )
-		return false;
-
-	// absolute maximum
-	if( account_id > END_ACCOUNT_NUM )
-		return false;
-
-	// insert the data into the database
-	acc->account_id = account_id;
-	return mmo_auth_tosql(db, acc, true);
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    Sql *sql_handle = db->accounts;
+
+    // decide on the account id to assign
+    int account_id;
+    if (acc->account_id != -1) {
+        // caller specifies it manually
+        account_id = acc->account_id;
+    } else {
+        // ask the database
+        char *data;
+        size_t len;
+
+        if (SQL_SUCCESS != Sql_Query(sql_handle, "SELECT MAX(`account_id`)+1 FROM `%s`", db->account_db)) {
+            Sql_ShowDebug(sql_handle);
+            return false;
+        }
+        if (SQL_SUCCESS != Sql_NextRow(sql_handle)) {
+            Sql_ShowDebug(sql_handle);
+            Sql_FreeResult(sql_handle);
+            return false;
+        }
+
+        Sql_GetData(sql_handle, 0, &data, &len);
+        account_id = (data != NULL) ? atoi(data) : 0;
+        Sql_FreeResult(sql_handle);
+
+        if (account_id < START_ACCOUNT_NUM)
+            account_id = START_ACCOUNT_NUM;
+
+    }
+
+    // zero value is prohibited
+    if (account_id == 0)
+        return false;
+
+    // absolute maximum
+    if (account_id > END_ACCOUNT_NUM)
+        return false;
+
+    // insert the data into the database
+    acc->account_id = account_id;
+    return mmo_auth_tosql(db, acc, true);
 }
 
 /// delete an existing account entry + its regs
-static bool account_db_sql_remove(AccountDB* self, const int account_id)
+static bool account_db_sql_remove(AccountDB *self, const int account_id)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	Sql* sql_handle = db->accounts;
-	bool result = false;
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    Sql *sql_handle = db->accounts;
+    bool result = false;
 
-	if( SQL_SUCCESS != Sql_QueryStr(sql_handle, "START TRANSACTION")
-	||  SQL_SUCCESS != Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id` = %d", db->account_db, account_id)
-	||  SQL_SUCCESS != Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id` = %d", db->accreg_db, account_id) )
-		Sql_ShowDebug(sql_handle);
-	else
-		result = true;
+    if (SQL_SUCCESS != Sql_QueryStr(sql_handle, "START TRANSACTION")
+        ||  SQL_SUCCESS != Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id` = %d", db->account_db, account_id)
+        ||  SQL_SUCCESS != Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `account_id` = %d", db->accreg_db, account_id))
+        Sql_ShowDebug(sql_handle);
+    else
+        result = true;
 
-	result &= ( SQL_SUCCESS == Sql_QueryStr(sql_handle, (result == true) ? "COMMIT" : "ROLLBACK") );
+    result &= (SQL_SUCCESS == Sql_QueryStr(sql_handle, (result == true) ? "COMMIT" : "ROLLBACK"));
 
-	return result;
+    return result;
 }
 
 /// update an existing account with the provided new data (both account and regs)
-static bool account_db_sql_save(AccountDB* self, const struct mmo_account* acc)
+static bool account_db_sql_save(AccountDB *self, const struct mmo_account *acc)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	return mmo_auth_tosql(db, acc, false);
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    return mmo_auth_tosql(db, acc, false);
 }
 
 /// retrieve data from db and store it in the provided data structure
-static bool account_db_sql_load_num(AccountDB* self, struct mmo_account* acc, const int account_id)
+static bool account_db_sql_load_num(AccountDB *self, struct mmo_account *acc, const int account_id)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	return mmo_auth_fromsql(db, acc, account_id);
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    return mmo_auth_fromsql(db, acc, account_id);
 }
 
 /// retrieve data from db and store it in the provided data structure
-static bool account_db_sql_load_str(AccountDB* self, struct mmo_account* acc, const char* userid)
+static bool account_db_sql_load_str(AccountDB *self, struct mmo_account *acc, const char *userid)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	Sql* sql_handle = db->accounts;
-	char esc_userid[2*NAME_LENGTH+1];
-	int account_id;
-	char* data;
-
-	Sql_EscapeString(sql_handle, esc_userid, userid);
-
-	// get the list of account IDs for this user ID
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id` FROM `%s` WHERE `userid`= %s '%s'",
-		db->account_db, (db->case_sensitive ? "BINARY" : ""), esc_userid) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-
-	if( Sql_NumRows(sql_handle) > 1 )
-	{// serious problem - duplicit account
-		ShowError("account_db_sql_load_str: multiple accounts found when retrieving data for account '%s'!\n", userid);
-		Sql_FreeResult(sql_handle);
-		return false;
-	}
-
-	if( SQL_SUCCESS != Sql_NextRow(sql_handle) )
-	{// no such entry
-		Sql_FreeResult(sql_handle);
-		return false;
-	}
-
-	Sql_GetData(sql_handle, 0, &data, NULL);
-	account_id = atoi(data);
-
-	return account_db_sql_load_num(self, acc, account_id);
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    Sql *sql_handle = db->accounts;
+    char esc_userid[2*NAME_LENGTH+1];
+    int account_id;
+    char *data;
+
+    Sql_EscapeString(sql_handle, esc_userid, userid);
+
+    // get the list of account IDs for this user ID
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id` FROM `%s` WHERE `userid`= %s '%s'",
+                               db->account_db, (db->case_sensitive ? "BINARY" : ""), esc_userid)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+
+    if (Sql_NumRows(sql_handle) > 1) {
+        // serious problem - duplicit account
+        ShowError("account_db_sql_load_str: multiple accounts found when retrieving data for account '%s'!\n", userid);
+        Sql_FreeResult(sql_handle);
+        return false;
+    }
+
+    if (SQL_SUCCESS != Sql_NextRow(sql_handle)) {
+        // no such entry
+        Sql_FreeResult(sql_handle);
+        return false;
+    }
+
+    Sql_GetData(sql_handle, 0, &data, NULL);
+    account_id = atoi(data);
+
+    return account_db_sql_load_num(self, acc, account_id);
 }
 
 
 /// Returns a new forward iterator.
-static AccountDBIterator* account_db_sql_iterator(AccountDB* self)
+static AccountDBIterator *account_db_sql_iterator(AccountDB *self)
 {
-	AccountDB_SQL* db = (AccountDB_SQL*)self;
-	AccountDBIterator_SQL* iter = (AccountDBIterator_SQL*)aCalloc(1, sizeof(AccountDBIterator_SQL));
+    AccountDB_SQL *db = (AccountDB_SQL *)self;
+    AccountDBIterator_SQL *iter = (AccountDBIterator_SQL *)aCalloc(1, sizeof(AccountDBIterator_SQL));
 
-	// set up the vtable
-	iter->vtable.destroy = &account_db_sql_iter_destroy;
-	iter->vtable.next    = &account_db_sql_iter_next;
+    // set up the vtable
+    iter->vtable.destroy = &account_db_sql_iter_destroy;
+    iter->vtable.next    = &account_db_sql_iter_next;
 
-	// fill data
-	iter->db = db;
-	iter->last_account_id = -1;
+    // fill data
+    iter->db = db;
+    iter->last_account_id = -1;
 
-	return &iter->vtable;
+    return &iter->vtable;
 }
 
 
 /// Destroys this iterator, releasing all allocated memory (including itself).
-static void account_db_sql_iter_destroy(AccountDBIterator* self)
+static void account_db_sql_iter_destroy(AccountDBIterator *self)
 {
-	AccountDBIterator_SQL* iter = (AccountDBIterator_SQL*)self;
-	aFree(iter);
+    AccountDBIterator_SQL *iter = (AccountDBIterator_SQL *)self;
+    aFree(iter);
 }
 
 
 /// Fetches the next account in the database.
-static bool account_db_sql_iter_next(AccountDBIterator* self, struct mmo_account* acc)
+static bool account_db_sql_iter_next(AccountDBIterator *self, struct mmo_account *acc)
 {
-	AccountDBIterator_SQL* iter = (AccountDBIterator_SQL*)self;
-	AccountDB_SQL* db = (AccountDB_SQL*)iter->db;
-	Sql* sql_handle = db->accounts;
-	int account_id;
-	char* data;
-
-	// get next account ID
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id` FROM `%s` WHERE `account_id` > '%d' ORDER BY `account_id` ASC LIMIT 1",
-		db->account_db, iter->last_account_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-
-	if( SQL_SUCCESS == Sql_NextRow(sql_handle) &&
-		SQL_SUCCESS == Sql_GetData(sql_handle, 0, &data, NULL) &&
-		data != NULL )
-	{// get account data
-		account_id = atoi(data);
-		if( mmo_auth_fromsql(db, acc, account_id) )
-		{
-			iter->last_account_id = account_id;
-			Sql_FreeResult(sql_handle);
-			return true;
-		}
-	}
-	Sql_FreeResult(sql_handle);
-	return false;
+    AccountDBIterator_SQL *iter = (AccountDBIterator_SQL *)self;
+    AccountDB_SQL *db = (AccountDB_SQL *)iter->db;
+    Sql *sql_handle = db->accounts;
+    int account_id;
+    char *data;
+
+    // get next account ID
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `account_id` FROM `%s` WHERE `account_id` > '%d' ORDER BY `account_id` ASC LIMIT 1",
+                               db->account_db, iter->last_account_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+
+    if (SQL_SUCCESS == Sql_NextRow(sql_handle) &&
+        SQL_SUCCESS == Sql_GetData(sql_handle, 0, &data, NULL) &&
+        data != NULL) {
+        // get account data
+        account_id = atoi(data);
+        if (mmo_auth_fromsql(db, acc, account_id)) {
+            iter->last_account_id = account_id;
+            Sql_FreeResult(sql_handle);
+            return true;
+        }
+    }
+    Sql_FreeResult(sql_handle);
+    return false;
 }
 
 
-static bool mmo_auth_fromsql(AccountDB_SQL* db, struct mmo_account* acc, int account_id)
+static bool mmo_auth_fromsql(AccountDB_SQL *db, struct mmo_account *acc, int account_id)
 {
-	Sql* sql_handle = db->accounts;
-	char* data;
-	int i = 0;
-
-	// retrieve login entry for the specified account
-	if( SQL_ERROR == Sql_Query(sql_handle,
-	    "SELECT `account_id`,`userid`,`user_pass`,`sex`,`email`,`group_id`,`state`,`unban_time`,`expiration_time`,`logincount`,`lastlogin`,`last_ip`,`birthdate` FROM `%s` WHERE `account_id` = %d",
-		db->account_db, account_id )
-	) {
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-
-	if( SQL_SUCCESS != Sql_NextRow(sql_handle) )
-	{// no such entry
-		Sql_FreeResult(sql_handle);
-		return false;
-	}
-
-	Sql_GetData(sql_handle,  0, &data, NULL); acc->account_id = atoi(data);
-	Sql_GetData(sql_handle,  1, &data, NULL); safestrncpy(acc->userid, data, sizeof(acc->userid));
-	Sql_GetData(sql_handle,  2, &data, NULL); safestrncpy(acc->pass, data, sizeof(acc->pass));
-	Sql_GetData(sql_handle,  3, &data, NULL); acc->sex = data[0];
-	Sql_GetData(sql_handle,  4, &data, NULL); safestrncpy(acc->email, data, sizeof(acc->email));
-	Sql_GetData(sql_handle,  5, &data, NULL); acc->group_id = atoi(data);
-	Sql_GetData(sql_handle,  6, &data, NULL); acc->state = strtoul(data, NULL, 10);
-	Sql_GetData(sql_handle,  7, &data, NULL); acc->unban_time = atol(data);
-	Sql_GetData(sql_handle,  8, &data, NULL); acc->expiration_time = atol(data);
-	Sql_GetData(sql_handle,  9, &data, NULL); acc->logincount = strtoul(data, NULL, 10);
-	Sql_GetData(sql_handle, 10, &data, NULL); safestrncpy(acc->lastlogin, data, sizeof(acc->lastlogin));
-	Sql_GetData(sql_handle, 11, &data, NULL); safestrncpy(acc->last_ip, data, sizeof(acc->last_ip));
-	Sql_GetData(sql_handle, 12, &data, NULL); safestrncpy(acc->birthdate, data, sizeof(acc->birthdate));
-
-	Sql_FreeResult(sql_handle);
-
-
-	// retrieve account regs for the specified user
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT `str`,`value` FROM `%s` WHERE `type`='1' AND `account_id`='%d'", db->accreg_db, acc->account_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		return false;
-	}
-
-	acc->account_reg2_num = (int)Sql_NumRows(sql_handle);
-
-	while( SQL_SUCCESS == Sql_NextRow(sql_handle) )
-	{
-		char* data;
-		Sql_GetData(sql_handle, 0, &data, NULL); safestrncpy(acc->account_reg2[i].str, data, sizeof(acc->account_reg2[i].str));
-		Sql_GetData(sql_handle, 1, &data, NULL); safestrncpy(acc->account_reg2[i].value, data, sizeof(acc->account_reg2[i].value));
-		++i;
-	}
-	Sql_FreeResult(sql_handle);
-
-	if( i != acc->account_reg2_num )
-		return false;
-
-	return true;
+    Sql *sql_handle = db->accounts;
+    char *data;
+    int i = 0;
+
+    // retrieve login entry for the specified account
+    if (SQL_ERROR == Sql_Query(sql_handle,
+                               "SELECT `account_id`,`userid`,`user_pass`,`sex`,`email`,`group_id`,`state`,`unban_time`,`expiration_time`,`logincount`,`lastlogin`,`last_ip`,`birthdate` FROM `%s` WHERE `account_id` = %d",
+                               db->account_db, account_id)
+       ) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+
+    if (SQL_SUCCESS != Sql_NextRow(sql_handle)) {
+        // no such entry
+        Sql_FreeResult(sql_handle);
+        return false;
+    }
+
+    Sql_GetData(sql_handle,  0, &data, NULL);
+    acc->account_id = atoi(data);
+    Sql_GetData(sql_handle,  1, &data, NULL);
+    safestrncpy(acc->userid, data, sizeof(acc->userid));
+    Sql_GetData(sql_handle,  2, &data, NULL);
+    safestrncpy(acc->pass, data, sizeof(acc->pass));
+    Sql_GetData(sql_handle,  3, &data, NULL);
+    acc->sex = data[0];
+    Sql_GetData(sql_handle,  4, &data, NULL);
+    safestrncpy(acc->email, data, sizeof(acc->email));
+    Sql_GetData(sql_handle,  5, &data, NULL);
+    acc->group_id = atoi(data);
+    Sql_GetData(sql_handle,  6, &data, NULL);
+    acc->state = strtoul(data, NULL, 10);
+    Sql_GetData(sql_handle,  7, &data, NULL);
+    acc->unban_time = atol(data);
+    Sql_GetData(sql_handle,  8, &data, NULL);
+    acc->expiration_time = atol(data);
+    Sql_GetData(sql_handle,  9, &data, NULL);
+    acc->logincount = strtoul(data, NULL, 10);
+    Sql_GetData(sql_handle, 10, &data, NULL);
+    safestrncpy(acc->lastlogin, data, sizeof(acc->lastlogin));
+    Sql_GetData(sql_handle, 11, &data, NULL);
+    safestrncpy(acc->last_ip, data, sizeof(acc->last_ip));
+    Sql_GetData(sql_handle, 12, &data, NULL);
+    safestrncpy(acc->birthdate, data, sizeof(acc->birthdate));
+
+    Sql_FreeResult(sql_handle);
+
+
+    // retrieve account regs for the specified user
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT `str`,`value` FROM `%s` WHERE `type`='1' AND `account_id`='%d'", db->accreg_db, acc->account_id)) {
+        Sql_ShowDebug(sql_handle);
+        return false;
+    }
+
+    acc->account_reg2_num = (int)Sql_NumRows(sql_handle);
+
+    while (SQL_SUCCESS == Sql_NextRow(sql_handle)) {
+        char *data;
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        safestrncpy(acc->account_reg2[i].str, data, sizeof(acc->account_reg2[i].str));
+        Sql_GetData(sql_handle, 1, &data, NULL);
+        safestrncpy(acc->account_reg2[i].value, data, sizeof(acc->account_reg2[i].value));
+        ++i;
+    }
+    Sql_FreeResult(sql_handle);
+
+    if (i != acc->account_reg2_num)
+        return false;
+
+    return true;
 }
 
-static bool mmo_auth_tosql(AccountDB_SQL* db, const struct mmo_account* acc, bool is_new)
+static bool mmo_auth_tosql(AccountDB_SQL *db, const struct mmo_account *acc, bool is_new)
 {
-	Sql* sql_handle = db->accounts;
-	SqlStmt* stmt = SqlStmt_Malloc(sql_handle);
-	bool result = false;
-	int i;
-
-	// try
-	do
-	{
-
-	if( SQL_SUCCESS != Sql_QueryStr(sql_handle, "START TRANSACTION") )
-	{
-		Sql_ShowDebug(sql_handle);
-		break;
-	}
-
-	if( is_new )
-	{// insert into account table
-		if( SQL_SUCCESS != SqlStmt_Prepare(stmt,
-			"INSERT INTO `%s` (`account_id`, `userid`, `user_pass`, `sex`, `email`, `group_id`, `state`, `unban_time`, `expiration_time`, `logincount`, `lastlogin`, `last_ip`, `birthdate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
-			db->account_db)
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  0, SQLDT_INT,    (void*)&acc->account_id,      sizeof(acc->account_id))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  1, SQLDT_STRING, (void*)acc->userid,           strlen(acc->userid))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  2, SQLDT_STRING, (void*)acc->pass,             strlen(acc->pass))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  3, SQLDT_ENUM,   (void*)&acc->sex,             sizeof(acc->sex))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  4, SQLDT_STRING, (void*)&acc->email,           strlen(acc->email))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  5, SQLDT_INT,    (void*)&acc->group_id,        sizeof(acc->group_id))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  6, SQLDT_UINT,   (void*)&acc->state,           sizeof(acc->state))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  7, SQLDT_LONG,   (void*)&acc->unban_time,      sizeof(acc->unban_time))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  8, SQLDT_INT,    (void*)&acc->expiration_time, sizeof(acc->expiration_time))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  9, SQLDT_UINT,   (void*)&acc->logincount,      sizeof(acc->logincount))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 10, SQLDT_STRING, (void*)&acc->lastlogin,       strlen(acc->lastlogin))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 11, SQLDT_STRING, (void*)&acc->last_ip,         strlen(acc->last_ip))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 12, SQLDT_STRING, (void*)&acc->birthdate,       strlen(acc->birthdate))
-		||  SQL_SUCCESS != SqlStmt_Execute(stmt)
-		) {
-			SqlStmt_ShowDebug(stmt);
-			break;
-		}
-	}
-	else
-	{// update account table
-		if( SQL_SUCCESS != SqlStmt_Prepare(stmt, "UPDATE `%s` SET `userid`=?,`user_pass`=?,`sex`=?,`email`=?,`group_id`=?,`state`=?,`unban_time`=?,`expiration_time`=?,`logincount`=?,`lastlogin`=?,`last_ip`=?,`birthdate`=? WHERE `account_id` = '%d'", db->account_db, acc->account_id)
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  0, SQLDT_STRING, (void*)acc->userid,           strlen(acc->userid))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  1, SQLDT_STRING, (void*)acc->pass,             strlen(acc->pass))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  2, SQLDT_ENUM,   (void*)&acc->sex,             sizeof(acc->sex))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  3, SQLDT_STRING, (void*)acc->email,            strlen(acc->email))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  4, SQLDT_INT,    (void*)&acc->group_id,        sizeof(acc->group_id))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  5, SQLDT_UINT,   (void*)&acc->state,           sizeof(acc->state))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  6, SQLDT_LONG,   (void*)&acc->unban_time,      sizeof(acc->unban_time))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  7, SQLDT_LONG,   (void*)&acc->expiration_time, sizeof(acc->expiration_time))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  8, SQLDT_UINT,   (void*)&acc->logincount,      sizeof(acc->logincount))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  9, SQLDT_STRING, (void*)&acc->lastlogin,       strlen(acc->lastlogin))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 10, SQLDT_STRING, (void*)&acc->last_ip,         strlen(acc->last_ip))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 11, SQLDT_STRING, (void*)&acc->birthdate,       strlen(acc->birthdate))
-		||  SQL_SUCCESS != SqlStmt_Execute(stmt)
-		) {
-			SqlStmt_ShowDebug(stmt);
-			break;
-		}
-	}
-
-	// remove old account regs
-	if( SQL_SUCCESS != Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `type`='1' AND `account_id`='%d'", db->accreg_db, acc->account_id) )
-	{
-		Sql_ShowDebug(sql_handle);
-		break;
-	}
-	// insert new account regs
-	if( SQL_SUCCESS != SqlStmt_Prepare(stmt, "INSERT INTO `%s` (`type`, `account_id`, `str`, `value`) VALUES ( 1 , '%d' , ? , ? );",  db->accreg_db, acc->account_id) )
-	{
-		SqlStmt_ShowDebug(stmt);
-		break;
-	}
-	for( i = 0; i < acc->account_reg2_num; ++i )
-	{
-		if( SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, (void*)acc->account_reg2[i].str, strlen(acc->account_reg2[i].str))
-		||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, (void*)acc->account_reg2[i].value, strlen(acc->account_reg2[i].value))
-		||  SQL_SUCCESS != SqlStmt_Execute(stmt)
-		) {
-			SqlStmt_ShowDebug(stmt);
-			break;
-		}
-	}
-	if( i < acc->account_reg2_num )
-	{
-		result = false;
-		break;
-	}
-
-	// if we got this far, everything was successful
-	result = true;
-
-	} while(0);
-	// finally
-
-	result &= ( SQL_SUCCESS == Sql_QueryStr(sql_handle, (result == true) ? "COMMIT" : "ROLLBACK") );
-	SqlStmt_Free(stmt);
-
-	return result;
+    Sql *sql_handle = db->accounts;
+    SqlStmt *stmt = SqlStmt_Malloc(sql_handle);
+    bool result = false;
+    int i;
+
+    // try
+    do {
+
+        if (SQL_SUCCESS != Sql_QueryStr(sql_handle, "START TRANSACTION")) {
+            Sql_ShowDebug(sql_handle);
+            break;
+        }
+
+        if (is_new) {
+            // insert into account table
+            if (SQL_SUCCESS != SqlStmt_Prepare(stmt,
+                                               "INSERT INTO `%s` (`account_id`, `userid`, `user_pass`, `sex`, `email`, `group_id`, `state`, `unban_time`, `expiration_time`, `logincount`, `lastlogin`, `last_ip`, `birthdate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+                                               db->account_db)
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  0, SQLDT_INT, (void *)&acc->account_id,      sizeof(acc->account_id))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  1, SQLDT_STRING, (void *)acc->userid,           strlen(acc->userid))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  2, SQLDT_STRING, (void *)acc->pass,             strlen(acc->pass))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  3, SQLDT_ENUM, (void *)&acc->sex,             sizeof(acc->sex))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  4, SQLDT_STRING, (void *)&acc->email,           strlen(acc->email))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  5, SQLDT_INT, (void *)&acc->group_id,        sizeof(acc->group_id))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  6, SQLDT_UINT, (void *)&acc->state,           sizeof(acc->state))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  7, SQLDT_LONG, (void *)&acc->unban_time,      sizeof(acc->unban_time))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  8, SQLDT_INT, (void *)&acc->expiration_time, sizeof(acc->expiration_time))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  9, SQLDT_UINT, (void *)&acc->logincount,      sizeof(acc->logincount))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 10, SQLDT_STRING, (void *)&acc->lastlogin,       strlen(acc->lastlogin))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 11, SQLDT_STRING, (void *)&acc->last_ip,         strlen(acc->last_ip))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 12, SQLDT_STRING, (void *)&acc->birthdate,       strlen(acc->birthdate))
+                ||  SQL_SUCCESS != SqlStmt_Execute(stmt)
+               ) {
+                SqlStmt_ShowDebug(stmt);
+                break;
+            }
+        } else {
+            // update account table
+            if (SQL_SUCCESS != SqlStmt_Prepare(stmt, "UPDATE `%s` SET `userid`=?,`user_pass`=?,`sex`=?,`email`=?,`group_id`=?,`state`=?,`unban_time`=?,`expiration_time`=?,`logincount`=?,`lastlogin`=?,`last_ip`=?,`birthdate`=? WHERE `account_id` = '%d'", db->account_db, acc->account_id)
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  0, SQLDT_STRING, (void *)acc->userid,           strlen(acc->userid))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  1, SQLDT_STRING, (void *)acc->pass,             strlen(acc->pass))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  2, SQLDT_ENUM, (void *)&acc->sex,             sizeof(acc->sex))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  3, SQLDT_STRING, (void *)acc->email,            strlen(acc->email))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  4, SQLDT_INT, (void *)&acc->group_id,        sizeof(acc->group_id))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  5, SQLDT_UINT, (void *)&acc->state,           sizeof(acc->state))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  6, SQLDT_LONG, (void *)&acc->unban_time,      sizeof(acc->unban_time))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  7, SQLDT_LONG, (void *)&acc->expiration_time, sizeof(acc->expiration_time))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  8, SQLDT_UINT, (void *)&acc->logincount,      sizeof(acc->logincount))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt,  9, SQLDT_STRING, (void *)&acc->lastlogin,       strlen(acc->lastlogin))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 10, SQLDT_STRING, (void *)&acc->last_ip,         strlen(acc->last_ip))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 11, SQLDT_STRING, (void *)&acc->birthdate,       strlen(acc->birthdate))
+                ||  SQL_SUCCESS != SqlStmt_Execute(stmt)
+               ) {
+                SqlStmt_ShowDebug(stmt);
+                break;
+            }
+        }
+
+        // remove old account regs
+        if (SQL_SUCCESS != Sql_Query(sql_handle, "DELETE FROM `%s` WHERE `type`='1' AND `account_id`='%d'", db->accreg_db, acc->account_id)) {
+            Sql_ShowDebug(sql_handle);
+            break;
+        }
+        // insert new account regs
+        if (SQL_SUCCESS != SqlStmt_Prepare(stmt, "INSERT INTO `%s` (`type`, `account_id`, `str`, `value`) VALUES ( 1 , '%d' , ? , ? );",  db->accreg_db, acc->account_id)) {
+            SqlStmt_ShowDebug(stmt);
+            break;
+        }
+        for (i = 0; i < acc->account_reg2_num; ++i) {
+            if (SQL_SUCCESS != SqlStmt_BindParam(stmt, 0, SQLDT_STRING, (void *)acc->account_reg2[i].str, strlen(acc->account_reg2[i].str))
+                ||  SQL_SUCCESS != SqlStmt_BindParam(stmt, 1, SQLDT_STRING, (void *)acc->account_reg2[i].value, strlen(acc->account_reg2[i].value))
+                ||  SQL_SUCCESS != SqlStmt_Execute(stmt)
+               ) {
+                SqlStmt_ShowDebug(stmt);
+                break;
+            }
+        }
+        if (i < acc->account_reg2_num) {
+            result = false;
+            break;
+        }
+
+        // if we got this far, everything was successful
+        result = true;
+
+    } while (0);
+    // finally
+
+    result &= (SQL_SUCCESS == Sql_QueryStr(sql_handle, (result == true) ? "COMMIT" : "ROLLBACK"));
+    SqlStmt_Free(stmt);
+
+    return result;
 }

+ 1 - 1
src/login/ipban.h

@@ -19,7 +19,7 @@ bool ipban_check(uint32 ip);
 void ipban_log(uint32 ip);
 
 // parses configuration option
-bool ipban_config_read(const char* key, const char* value);
+bool ipban_config_read(const char *key, const char *value);
 
 
 #endif // __IPBAN_H_INCLUDED__

+ 159 - 181
src/login/ipban_sql.c

@@ -31,7 +31,7 @@ static char   ipban_codepage[32] = "";
 static char   ipban_table[32] = "ipbanlist";
 
 // globals
-static Sql* sql_handle = NULL;
+static Sql *sql_handle = NULL;
 static int cleanup_timer_id = INVALID_TIMER;
 static bool ipban_inited = false;
 
@@ -41,218 +41,196 @@ int ipban_cleanup(int tid, unsigned int tick, int id, intptr_t data);
 // initialize
 void ipban_init(void)
 {
-	const char* username;
-	const char* password;
-	const char* hostname;
-	uint16      port;
-	const char* database;
-	const char* codepage;
-
-	ipban_inited = true;
-
-	if( !login_config.ipban )
-		return;// ipban disabled
-
-	if( ipban_db_hostname[0] != '\0' )
-	{// local settings
-		username = ipban_db_username;
-		password = ipban_db_password;
-		hostname = ipban_db_hostname;
-		port     = ipban_db_port;
-		database = ipban_db_database;
-		codepage = ipban_codepage;
-	}
-	else
-	{// global settings
-		username = global_db_username;
-		password = global_db_password;
-		hostname = global_db_hostname;
-		port     = global_db_port;
-		database = global_db_database;
-		codepage = global_codepage;
-	}
-
-	// establish connections
-	sql_handle = Sql_Malloc();
-	if( SQL_ERROR == Sql_Connect(sql_handle, username, password, hostname, port, database) )
-	{
-		Sql_ShowDebug(sql_handle);
-		Sql_Free(sql_handle);
-		exit(EXIT_FAILURE);
-	}
-	if( codepage[0] != '\0' && SQL_ERROR == Sql_SetEncoding(sql_handle, codepage) )
-		Sql_ShowDebug(sql_handle);
-
-	if( login_config.ipban_cleanup_interval > 0 )
-	{ // set up periodic cleanup of connection history and active bans
-		add_timer_func_list(ipban_cleanup, "ipban_cleanup");
-		cleanup_timer_id = add_timer_interval(gettick()+10, ipban_cleanup, 0, 0, login_config.ipban_cleanup_interval*1000);
-	} else // make sure it gets cleaned up on login-server start regardless of interval-based cleanups
-		ipban_cleanup(0,0,0,0);
+    const char *username;
+    const char *password;
+    const char *hostname;
+    uint16      port;
+    const char *database;
+    const char *codepage;
+
+    ipban_inited = true;
+
+    if (!login_config.ipban)
+        return;// ipban disabled
+
+    if (ipban_db_hostname[0] != '\0') {
+        // local settings
+        username = ipban_db_username;
+        password = ipban_db_password;
+        hostname = ipban_db_hostname;
+        port     = ipban_db_port;
+        database = ipban_db_database;
+        codepage = ipban_codepage;
+    } else {
+        // global settings
+        username = global_db_username;
+        password = global_db_password;
+        hostname = global_db_hostname;
+        port     = global_db_port;
+        database = global_db_database;
+        codepage = global_codepage;
+    }
+
+    // establish connections
+    sql_handle = Sql_Malloc();
+    if (SQL_ERROR == Sql_Connect(sql_handle, username, password, hostname, port, database)) {
+        Sql_ShowDebug(sql_handle);
+        Sql_Free(sql_handle);
+        exit(EXIT_FAILURE);
+    }
+    if (codepage[0] != '\0' && SQL_ERROR == Sql_SetEncoding(sql_handle, codepage))
+        Sql_ShowDebug(sql_handle);
+
+    if (login_config.ipban_cleanup_interval > 0) {
+        // set up periodic cleanup of connection history and active bans
+        add_timer_func_list(ipban_cleanup, "ipban_cleanup");
+        cleanup_timer_id = add_timer_interval(gettick()+10, ipban_cleanup, 0, 0, login_config.ipban_cleanup_interval*1000);
+    } else // make sure it gets cleaned up on login-server start regardless of interval-based cleanups
+        ipban_cleanup(0,0,0,0);
 }
 
 // finalize
 void ipban_final(void)
 {
-	if( !login_config.ipban )
-		return;// ipban disabled
-
-	if( login_config.ipban_cleanup_interval > 0 )
-		// release data
-		delete_timer(cleanup_timer_id, ipban_cleanup);
-	
-	ipban_cleanup(0,0,0,0); // always clean up on login-server stop
-
-	// close connections
-	Sql_Free(sql_handle);
-	sql_handle = NULL;
+    if (!login_config.ipban)
+        return;// ipban disabled
+
+    if (login_config.ipban_cleanup_interval > 0)
+        // release data
+        delete_timer(cleanup_timer_id, ipban_cleanup);
+
+    ipban_cleanup(0,0,0,0); // always clean up on login-server stop
+
+    // close connections
+    Sql_Free(sql_handle);
+    sql_handle = NULL;
 }
 
 // load configuration options
-bool ipban_config_read(const char* key, const char* value)
+bool ipban_config_read(const char *key, const char *value)
 {
-	const char* signature;
-
-	if( ipban_inited )
-		return false;// settings can only be changed before init
-
-	signature = "sql.";
-	if( strncmpi(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "db_hostname") == 0 )
-			safestrncpy(global_db_hostname, value, sizeof(global_db_hostname));
-		else
-		if( strcmpi(key, "db_port") == 0 )
-			global_db_port = (uint16)strtoul(value, NULL, 10);
-		else
-		if( strcmpi(key, "db_username") == 0 )
-			safestrncpy(global_db_username, value, sizeof(global_db_username));
-		else
-		if( strcmpi(key, "db_password") == 0 )
-			safestrncpy(global_db_password, value, sizeof(global_db_password));
-		else
-		if( strcmpi(key, "db_database") == 0 )
-			safestrncpy(global_db_database, value, sizeof(global_db_database));
-		else
-		if( strcmpi(key, "codepage") == 0 )
-			safestrncpy(global_codepage, value, sizeof(global_codepage));
-		else
-			return false;// not found
-		return true;
-	}
-
-	signature = "ipban.sql.";
-	if( strncmpi(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "db_hostname") == 0 )
-			safestrncpy(ipban_db_hostname, value, sizeof(ipban_db_hostname));
-		else
-		if( strcmpi(key, "db_port") == 0 )
-			ipban_db_port = (uint16)strtoul(value, NULL, 10);
-		else
-		if( strcmpi(key, "db_username") == 0 )
-			safestrncpy(ipban_db_username, value, sizeof(ipban_db_username));
-		else
-		if( strcmpi(key, "db_password") == 0 )
-			safestrncpy(ipban_db_password, value, sizeof(ipban_db_password));
-		else
-		if( strcmpi(key, "db_database") == 0 )
-			safestrncpy(ipban_db_database, value, sizeof(ipban_db_database));
-		else
-		if( strcmpi(key, "codepage") == 0 )
-			safestrncpy(ipban_codepage, value, sizeof(ipban_codepage));
-		else
-		if( strcmpi(key, "ipban_table") == 0 )
-			safestrncpy(ipban_table, value, sizeof(ipban_table));
-		else
-			return false;// not found
-		return true;
-	}
-
-	signature = "ipban.";
-	if( strncmpi(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "enable") == 0 )
-			login_config.ipban = (bool)config_switch(value);
-		else
-		if( strcmpi(key, "dynamic_pass_failure_ban") == 0 )
-			login_config.dynamic_pass_failure_ban = (bool)config_switch(value);
-		else
-		if( strcmpi(key, "dynamic_pass_failure_ban_interval") == 0 )
-			login_config.dynamic_pass_failure_ban_interval = atoi(value);
-		else
-		if( strcmpi(key, "dynamic_pass_failure_ban_limit") == 0 )
-			login_config.dynamic_pass_failure_ban_limit = atoi(value);
-		else
-		if( strcmpi(key, "dynamic_pass_failure_ban_duration") == 0 )
-			login_config.dynamic_pass_failure_ban_duration = atoi(value);
-		else
-			return false;// not found
-		return true;
-	}
-
-	return false;// not found
+    const char *signature;
+
+    if (ipban_inited)
+        return false;// settings can only be changed before init
+
+    signature = "sql.";
+    if (strncmpi(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "db_hostname") == 0)
+            safestrncpy(global_db_hostname, value, sizeof(global_db_hostname));
+        else if (strcmpi(key, "db_port") == 0)
+            global_db_port = (uint16)strtoul(value, NULL, 10);
+        else if (strcmpi(key, "db_username") == 0)
+            safestrncpy(global_db_username, value, sizeof(global_db_username));
+        else if (strcmpi(key, "db_password") == 0)
+            safestrncpy(global_db_password, value, sizeof(global_db_password));
+        else if (strcmpi(key, "db_database") == 0)
+            safestrncpy(global_db_database, value, sizeof(global_db_database));
+        else if (strcmpi(key, "codepage") == 0)
+            safestrncpy(global_codepage, value, sizeof(global_codepage));
+        else
+            return false;// not found
+        return true;
+    }
+
+    signature = "ipban.sql.";
+    if (strncmpi(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "db_hostname") == 0)
+            safestrncpy(ipban_db_hostname, value, sizeof(ipban_db_hostname));
+        else if (strcmpi(key, "db_port") == 0)
+            ipban_db_port = (uint16)strtoul(value, NULL, 10);
+        else if (strcmpi(key, "db_username") == 0)
+            safestrncpy(ipban_db_username, value, sizeof(ipban_db_username));
+        else if (strcmpi(key, "db_password") == 0)
+            safestrncpy(ipban_db_password, value, sizeof(ipban_db_password));
+        else if (strcmpi(key, "db_database") == 0)
+            safestrncpy(ipban_db_database, value, sizeof(ipban_db_database));
+        else if (strcmpi(key, "codepage") == 0)
+            safestrncpy(ipban_codepage, value, sizeof(ipban_codepage));
+        else if (strcmpi(key, "ipban_table") == 0)
+            safestrncpy(ipban_table, value, sizeof(ipban_table));
+        else
+            return false;// not found
+        return true;
+    }
+
+    signature = "ipban.";
+    if (strncmpi(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "enable") == 0)
+            login_config.ipban = (bool)config_switch(value);
+        else if (strcmpi(key, "dynamic_pass_failure_ban") == 0)
+            login_config.dynamic_pass_failure_ban = (bool)config_switch(value);
+        else if (strcmpi(key, "dynamic_pass_failure_ban_interval") == 0)
+            login_config.dynamic_pass_failure_ban_interval = atoi(value);
+        else if (strcmpi(key, "dynamic_pass_failure_ban_limit") == 0)
+            login_config.dynamic_pass_failure_ban_limit = atoi(value);
+        else if (strcmpi(key, "dynamic_pass_failure_ban_duration") == 0)
+            login_config.dynamic_pass_failure_ban_duration = atoi(value);
+        else
+            return false;// not found
+        return true;
+    }
+
+    return false;// not found
 }
 
 // check ip against active bans list
 bool ipban_check(uint32 ip)
 {
-	uint8* p = (uint8*)&ip;
-	char* data = NULL;
-	int matches;
+    uint8 *p = (uint8 *)&ip;
+    char *data = NULL;
+    int matches;
 
-	if( !login_config.ipban )
-		return false;// ipban disabled
+    if (!login_config.ipban)
+        return false;// ipban disabled
 
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT count(*) FROM `%s` WHERE `rtime` > NOW() AND (`list` = '%u.*.*.*' OR `list` = '%u.%u.*.*' OR `list` = '%u.%u.%u.*' OR `list` = '%u.%u.%u.%u')",
-		ipban_table, p[3], p[3], p[2], p[3], p[2], p[1], p[3], p[2], p[1], p[0]) )
-	{
-		Sql_ShowDebug(sql_handle);
-		// close connection because we can't verify their connectivity.
-		return true;
-	}
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT count(*) FROM `%s` WHERE `rtime` > NOW() AND (`list` = '%u.*.*.*' OR `list` = '%u.%u.*.*' OR `list` = '%u.%u.%u.*' OR `list` = '%u.%u.%u.%u')",
+                               ipban_table, p[3], p[3], p[2], p[3], p[2], p[1], p[3], p[2], p[1], p[0])) {
+        Sql_ShowDebug(sql_handle);
+        // close connection because we can't verify their connectivity.
+        return true;
+    }
 
-	if( SQL_ERROR == Sql_NextRow(sql_handle) )
-		return true;// Shouldn't happen, but just in case...
+    if (SQL_ERROR == Sql_NextRow(sql_handle))
+        return true;// Shouldn't happen, but just in case...
 
-	Sql_GetData(sql_handle, 0, &data, NULL);
-	matches = atoi(data);
-	Sql_FreeResult(sql_handle);
+    Sql_GetData(sql_handle, 0, &data, NULL);
+    matches = atoi(data);
+    Sql_FreeResult(sql_handle);
 
-	return( matches > 0 );
+    return(matches > 0);
 }
 
 // log failed attempt
 void ipban_log(uint32 ip)
 {
-	unsigned long failures;
+    unsigned long failures;
 
-	if( !login_config.ipban )
-		return;// ipban disabled
+    if (!login_config.ipban)
+        return;// ipban disabled
 
-	failures = loginlog_failedattempts(ip, login_config.dynamic_pass_failure_ban_interval);// how many times failed account? in one ip.
+    failures = loginlog_failedattempts(ip, login_config.dynamic_pass_failure_ban_interval);// how many times failed account? in one ip.
 
-	// if over the limit, add a temporary ban entry
-	if( failures >= login_config.dynamic_pass_failure_ban_limit )
-	{
-		uint8* p = (uint8*)&ip;
-		if( SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s`(`list`,`btime`,`rtime`,`reason`) VALUES ('%u.%u.%u.*', NOW() , NOW() +  INTERVAL %d MINUTE ,'Password error ban')",
-			ipban_table, p[3], p[2], p[1], login_config.dynamic_pass_failure_ban_duration) )
-			Sql_ShowDebug(sql_handle);
-	}
+    // if over the limit, add a temporary ban entry
+    if (failures >= login_config.dynamic_pass_failure_ban_limit) {
+        uint8 *p = (uint8 *)&ip;
+        if (SQL_ERROR == Sql_Query(sql_handle, "INSERT INTO `%s`(`list`,`btime`,`rtime`,`reason`) VALUES ('%u.%u.%u.*', NOW() , NOW() +  INTERVAL %d MINUTE ,'Password error ban')",
+                                   ipban_table, p[3], p[2], p[1], login_config.dynamic_pass_failure_ban_duration))
+            Sql_ShowDebug(sql_handle);
+    }
 }
 
 // remove expired bans
 int ipban_cleanup(int tid, unsigned int tick, int id, intptr_t data)
 {
-	if( !login_config.ipban )
-		return 0;// ipban disabled
+    if (!login_config.ipban)
+        return 0;// ipban disabled
 
-	if( SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `ipbanlist` WHERE `rtime` <= NOW()") )
-		Sql_ShowDebug(sql_handle);
+    if (SQL_ERROR == Sql_Query(sql_handle, "DELETE FROM `ipbanlist` WHERE `rtime` <= NOW()"))
+        Sql_ShowDebug(sql_handle);
 
-	return 0;
+    return 0;
 }

File diff suppressed because it is too large
+ 1080 - 1084
src/login/login.c


+ 61 - 62
src/login/login.h

@@ -7,11 +7,10 @@
 #include "../common/mmo.h" // NAME_LENGTH,SEX_*
 #include "../common/core.h" // CORE_ST_LAST
 
-enum E_LOGINSERVER_ST
-{
-	LOGINSERVER_ST_RUNNING = CORE_ST_LAST,
-	LOGINSERVER_ST_SHUTDOWN,
-	LOGINSERVER_ST_LAST
+enum E_LOGINSERVER_ST {
+    LOGINSERVER_ST_RUNNING = CORE_ST_LAST,
+    LOGINSERVER_ST_SHUTDOWN,
+    LOGINSERVER_ST_LAST
 };
 
 #define LOGIN_CONF_NAME "conf/login_athena.conf"
@@ -21,74 +20,74 @@ enum E_LOGINSERVER_ST
 #define PASSWORDENC 3
 
 struct login_session_data {
-	int account_id;
-	long login_id1;
-	long login_id2;
-	char sex;// 'F','M','S'
-
-	char userid[NAME_LENGTH];
-	char passwd[32+1]; // 23+1 for plaintext, 32+1 for md5-ed passwords
-	int passwdenc;
-	char md5key[20];
-	uint16 md5keylen;
-
-	char lastlogin[24];
-	uint8 group_id;
-	uint8 clienttype;
-	uint32 version;
-
-	uint8 client_hash[16];
-	int has_client_hash;
-
-	int fd;
+    int account_id;
+    long login_id1;
+    long login_id2;
+    char sex;// 'F','M','S'
+
+    char userid[NAME_LENGTH];
+    char passwd[32+1]; // 23+1 for plaintext, 32+1 for md5-ed passwords
+    int passwdenc;
+    char md5key[20];
+    uint16 md5keylen;
+
+    char lastlogin[24];
+    uint8 group_id;
+    uint8 clienttype;
+    uint32 version;
+
+    uint8 client_hash[16];
+    int has_client_hash;
+
+    int fd;
 };
 
 struct mmo_char_server {
 
-	char name[20];
-	int fd;
-	uint32 ip;
-	uint16 port;
-	uint16 users;       // user count on this server
-	uint16 type;        // 0=normal, 1=maintenance, 2=over 18, 3=paying, 4=P2P
-	uint16 new_;        // should display as 'new'?
+    char name[20];
+    int fd;
+    uint32 ip;
+    uint16 port;
+    uint16 users;       // user count on this server
+    uint16 type;        // 0=normal, 1=maintenance, 2=over 18, 3=paying, 4=P2P
+    uint16 new_;        // should display as 'new'?
 };
 
 struct client_hash_node {
-	int group_id;
-	uint8 hash[16];
-	struct client_hash_node *next;
+    int group_id;
+    uint8 hash[16];
+    struct client_hash_node *next;
 };
 
 struct Login_Config {
 
-	uint32 login_ip;                                // the address to bind to
-	uint16 login_port;                              // the port to bind to
-	unsigned int ipban_cleanup_interval;            // interval (in seconds) to clean up expired IP bans
-	unsigned int ip_sync_interval;                  // interval (in minutes) to execute a DNS/IP update (for dynamic IPs)
-	bool log_login;                                 // whether to log login server actions or not
-	char date_format[32];                           // date format used in messages
-	bool console;                                   // console input system enabled?
-	bool new_account_flag,new_acc_length_limit;     // autoregistration via _M/_F ? / if yes minimum length is 4?
-	int start_limited_time;                         // new account expiration time (-1: unlimited)
-	bool use_md5_passwds;                           // work with password hashes instead of plaintext passwords?
-	int group_id_to_connect;                        // required group id to connect
-	int min_group_id_to_connect;                    // minimum group id to connect
-	bool check_client_version;                      // check the clientversion set in the clientinfo ?
-	uint32 client_version_to_connect;               // the client version needed to connect (if checking is enabled)
-
-	bool ipban;                                     // perform IP blocking (via contents of `ipbanlist`) ?
-	bool dynamic_pass_failure_ban;                  // automatic IP blocking due to failed login attemps ?
-	unsigned int dynamic_pass_failure_ban_interval; // how far to scan the loginlog for password failures
-	unsigned int dynamic_pass_failure_ban_limit;    // number of failures needed to trigger the ipban
-	unsigned int dynamic_pass_failure_ban_duration; // duration of the ipban
-	bool use_dnsbl;                                 // dns blacklist blocking ?
-	char dnsbl_servs[1024];                         // comma-separated list of dnsbl servers
-
-	char account_engine[256];                       // name of the engine to use (defaults to auto, for the first available engine)
-
-	int client_hash_check;							// flags for checking client md5
-	struct client_hash_node *client_hash_nodes;		// linked list containg md5 hash for each gm group
+    uint32 login_ip;                                // the address to bind to
+    uint16 login_port;                              // the port to bind to
+    unsigned int ipban_cleanup_interval;            // interval (in seconds) to clean up expired IP bans
+    unsigned int ip_sync_interval;                  // interval (in minutes) to execute a DNS/IP update (for dynamic IPs)
+    bool log_login;                                 // whether to log login server actions or not
+    char date_format[32];                           // date format used in messages
+    bool console;                                   // console input system enabled?
+    bool new_account_flag,new_acc_length_limit;     // autoregistration via _M/_F ? / if yes minimum length is 4?
+    int start_limited_time;                         // new account expiration time (-1: unlimited)
+    bool use_md5_passwds;                           // work with password hashes instead of plaintext passwords?
+    int group_id_to_connect;                        // required group id to connect
+    int min_group_id_to_connect;                    // minimum group id to connect
+    bool check_client_version;                      // check the clientversion set in the clientinfo ?
+    uint32 client_version_to_connect;               // the client version needed to connect (if checking is enabled)
+
+    bool ipban;                                     // perform IP blocking (via contents of `ipbanlist`) ?
+    bool dynamic_pass_failure_ban;                  // automatic IP blocking due to failed login attemps ?
+    unsigned int dynamic_pass_failure_ban_interval; // how far to scan the loginlog for password failures
+    unsigned int dynamic_pass_failure_ban_limit;    // number of failures needed to trigger the ipban
+    unsigned int dynamic_pass_failure_ban_duration; // duration of the ipban
+    bool use_dnsbl;                                 // dns blacklist blocking ?
+    char dnsbl_servs[1024];                         // comma-separated list of dnsbl servers
+
+    char account_engine[256];                       // name of the engine to use (defaults to auto, for the first available engine)
+
+    int client_hash_check;                          // flags for checking client md5
+    struct client_hash_node *client_hash_nodes;     // linked list containg md5 hash for each gm group
 };
 
 #define sex_num2str(num) ( (num ==  SEX_FEMALE  ) ? 'F' : (num ==  SEX_MALE  ) ? 'M' : 'S' )

+ 2 - 2
src/login/loginlog.h

@@ -6,10 +6,10 @@
 
 
 unsigned long loginlog_failedattempts(uint32 ip, unsigned int minutes);
-void login_log(uint32 ip, const char* username, int rcode, const char* message);
+void login_log(uint32 ip, const char *username, int rcode, const char *message);
 bool loginlog_init(void);
 bool loginlog_final(void);
-bool loginlog_config_read(const char* w1, const char* w2);
+bool loginlog_config_read(const char *w1, const char *w2);
 
 
 #endif // __LOGINLOG_H_INCLUDED__

+ 113 - 128
src/login/loginlog_sql.c

@@ -25,160 +25,145 @@ static char   log_db_database[32] = "";
 static char   log_codepage[32] = "";
 static char   log_login_db[256] = "loginlog";
 
-static Sql* sql_handle = NULL;
+static Sql *sql_handle = NULL;
 static bool enabled = false;
 
 
 // Returns the number of failed login attemps by the ip in the last minutes.
 unsigned long loginlog_failedattempts(uint32 ip, unsigned int minutes)
 {
-	unsigned long failures = 0;
-
-	if( !enabled )
-		return 0;
-
-	if( SQL_ERROR == Sql_Query(sql_handle, "SELECT count(*) FROM `%s` WHERE `ip` = '%s' AND `rcode` = '1' AND `time` > NOW() - INTERVAL %d MINUTE",
-		log_login_db, ip2str(ip,NULL), minutes) )// how many times failed account? in one ip.
-		Sql_ShowDebug(sql_handle);
-
-	if( SQL_SUCCESS == Sql_NextRow(sql_handle) )
-	{
-		char* data;
-		Sql_GetData(sql_handle, 0, &data, NULL);
-		failures = strtoul(data, NULL, 10);
-		Sql_FreeResult(sql_handle);
-	}
-	return failures;
+    unsigned long failures = 0;
+
+    if (!enabled)
+        return 0;
+
+    if (SQL_ERROR == Sql_Query(sql_handle, "SELECT count(*) FROM `%s` WHERE `ip` = '%s' AND `rcode` = '1' AND `time` > NOW() - INTERVAL %d MINUTE",
+                               log_login_db, ip2str(ip,NULL), minutes)) // how many times failed account? in one ip.
+        Sql_ShowDebug(sql_handle);
+
+    if (SQL_SUCCESS == Sql_NextRow(sql_handle)) {
+        char *data;
+        Sql_GetData(sql_handle, 0, &data, NULL);
+        failures = strtoul(data, NULL, 10);
+        Sql_FreeResult(sql_handle);
+    }
+    return failures;
 }
 
 
 /*=============================================
  * Records an event in the login log
  *---------------------------------------------*/
-void login_log(uint32 ip, const char* username, int rcode, const char* message)
+void login_log(uint32 ip, const char *username, int rcode, const char *message)
 {
-	char esc_username[NAME_LENGTH*2+1];
-	char esc_message[255*2+1];
-	int retcode;
+    char esc_username[NAME_LENGTH*2+1];
+    char esc_message[255*2+1];
+    int retcode;
 
-	if( !enabled )
-		return;
+    if (!enabled)
+        return;
 
-	Sql_EscapeStringLen(sql_handle, esc_username, username, strnlen(username, NAME_LENGTH));
-	Sql_EscapeStringLen(sql_handle, esc_message, message, strnlen(message, 255));
+    Sql_EscapeStringLen(sql_handle, esc_username, username, strnlen(username, NAME_LENGTH));
+    Sql_EscapeStringLen(sql_handle, esc_message, message, strnlen(message, 255));
 
-	retcode = Sql_Query(sql_handle,
-		"INSERT INTO `%s`(`time`,`ip`,`user`,`rcode`,`log`) VALUES (NOW(), '%s', '%s', '%d', '%s')",
-		log_login_db, ip2str(ip,NULL), esc_username, rcode, esc_message);
+    retcode = Sql_Query(sql_handle,
+                        "INSERT INTO `%s`(`time`,`ip`,`user`,`rcode`,`log`) VALUES (NOW(), '%s', '%s', '%d', '%s')",
+                        log_login_db, ip2str(ip,NULL), esc_username, rcode, esc_message);
 
-	if( retcode != SQL_SUCCESS )
-		Sql_ShowDebug(sql_handle);
+    if (retcode != SQL_SUCCESS)
+        Sql_ShowDebug(sql_handle);
 }
 
 bool loginlog_init(void)
 {
-	const char* username;
-	const char* password;
-	const char* hostname;
-	uint16      port;
-	const char* database;
-	const char* codepage;
-
-	if( log_db_hostname[0] != '\0' )
-	{// local settings
-		username = log_db_username;
-		password = log_db_password;
-		hostname = log_db_hostname;
-		port     = log_db_port;
-		database = log_db_database;
-		codepage = log_codepage;
-	}
-	else
-	{// global settings
-		username = global_db_username;
-		password = global_db_password;
-		hostname = global_db_hostname;
-		port     = global_db_port;
-		database = global_db_database;
-		codepage = global_codepage;
-	}
-
-	sql_handle = Sql_Malloc();
-
-	if( SQL_ERROR == Sql_Connect(sql_handle, username, password, hostname, port, database) )
-	{
-		Sql_ShowDebug(sql_handle);
-		Sql_Free(sql_handle);
-		exit(EXIT_FAILURE);
-	}
-
-	if( codepage[0] != '\0' && SQL_ERROR == Sql_SetEncoding(sql_handle, codepage) )
-		Sql_ShowDebug(sql_handle);
-
-	enabled = true;
-
-	return true;
+    const char *username;
+    const char *password;
+    const char *hostname;
+    uint16      port;
+    const char *database;
+    const char *codepage;
+
+    if (log_db_hostname[0] != '\0') {
+        // local settings
+        username = log_db_username;
+        password = log_db_password;
+        hostname = log_db_hostname;
+        port     = log_db_port;
+        database = log_db_database;
+        codepage = log_codepage;
+    } else {
+        // global settings
+        username = global_db_username;
+        password = global_db_password;
+        hostname = global_db_hostname;
+        port     = global_db_port;
+        database = global_db_database;
+        codepage = global_codepage;
+    }
+
+    sql_handle = Sql_Malloc();
+
+    if (SQL_ERROR == Sql_Connect(sql_handle, username, password, hostname, port, database)) {
+        Sql_ShowDebug(sql_handle);
+        Sql_Free(sql_handle);
+        exit(EXIT_FAILURE);
+    }
+
+    if (codepage[0] != '\0' && SQL_ERROR == Sql_SetEncoding(sql_handle, codepage))
+        Sql_ShowDebug(sql_handle);
+
+    enabled = true;
+
+    return true;
 }
 
 bool loginlog_final(void)
 {
-	Sql_Free(sql_handle);
-	sql_handle = NULL;
-	return true;
+    Sql_Free(sql_handle);
+    sql_handle = NULL;
+    return true;
 }
 
-bool loginlog_config_read(const char* key, const char* value)
+bool loginlog_config_read(const char *key, const char *value)
 {
-	const char* signature;
-
-	signature = "sql.";
-	if( strncmpi(key, signature, strlen(signature)) == 0 )
-	{
-		key += strlen(signature);
-		if( strcmpi(key, "db_hostname") == 0 )
-			safestrncpy(global_db_hostname, value, sizeof(global_db_hostname));
-		else
-		if( strcmpi(key, "db_port") == 0 )
-			global_db_port = (uint16)strtoul(value, NULL, 10);
-		else
-		if( strcmpi(key, "db_username") == 0 )
-			safestrncpy(global_db_username, value, sizeof(global_db_username));
-		else
-		if( strcmpi(key, "db_password") == 0 )
-			safestrncpy(global_db_password, value, sizeof(global_db_password));
-		else
-		if( strcmpi(key, "db_database") == 0 )
-			safestrncpy(global_db_database, value, sizeof(global_db_database));
-		else
-		if( strcmpi(key, "codepage") == 0 )
-			safestrncpy(global_codepage, value, sizeof(global_codepage));
-		else
-			return false;// not found
-		return true;
-	}
-
-	if( strcmpi(key, "log_db_ip") == 0 )
-		safestrncpy(log_db_hostname, value, sizeof(log_db_hostname));
-	else
-	if( strcmpi(key, "log_db_port") == 0 )
-		log_db_port = (uint16)strtoul(value, NULL, 10);
-	else
-	if( strcmpi(key, "log_db_id") == 0 )
-		safestrncpy(log_db_username, value, sizeof(log_db_username));
-	else
-	if( strcmpi(key, "log_db_pw") == 0 )
-		safestrncpy(log_db_password, value, sizeof(log_db_password));
-	else
-	if( strcmpi(key, "log_db_db") == 0 )
-		safestrncpy(log_db_database, value, sizeof(log_db_database));
-	else
-	if( strcmpi(key, "log_codepage") == 0 )
-		safestrncpy(log_codepage, value, sizeof(log_codepage));
-	else
-	if( strcmpi(key, "log_login_db") == 0 )
-		safestrncpy(log_login_db, value, sizeof(log_login_db));
-	else
-		return false;
-
-	return true;
+    const char *signature;
+
+    signature = "sql.";
+    if (strncmpi(key, signature, strlen(signature)) == 0) {
+        key += strlen(signature);
+        if (strcmpi(key, "db_hostname") == 0)
+            safestrncpy(global_db_hostname, value, sizeof(global_db_hostname));
+        else if (strcmpi(key, "db_port") == 0)
+            global_db_port = (uint16)strtoul(value, NULL, 10);
+        else if (strcmpi(key, "db_username") == 0)
+            safestrncpy(global_db_username, value, sizeof(global_db_username));
+        else if (strcmpi(key, "db_password") == 0)
+            safestrncpy(global_db_password, value, sizeof(global_db_password));
+        else if (strcmpi(key, "db_database") == 0)
+            safestrncpy(global_db_database, value, sizeof(global_db_database));
+        else if (strcmpi(key, "codepage") == 0)
+            safestrncpy(global_codepage, value, sizeof(global_codepage));
+        else
+            return false;// not found
+        return true;
+    }
+
+    if (strcmpi(key, "log_db_ip") == 0)
+        safestrncpy(log_db_hostname, value, sizeof(log_db_hostname));
+    else if (strcmpi(key, "log_db_port") == 0)
+        log_db_port = (uint16)strtoul(value, NULL, 10);
+    else if (strcmpi(key, "log_db_id") == 0)
+        safestrncpy(log_db_username, value, sizeof(log_db_username));
+    else if (strcmpi(key, "log_db_pw") == 0)
+        safestrncpy(log_db_password, value, sizeof(log_db_password));
+    else if (strcmpi(key, "log_db_db") == 0)
+        safestrncpy(log_db_database, value, sizeof(log_db_database));
+    else if (strcmpi(key, "log_codepage") == 0)
+        safestrncpy(log_codepage, value, sizeof(log_codepage));
+    else if (strcmpi(key, "log_login_db") == 0)
+        safestrncpy(log_login_db, value, sizeof(log_login_db));
+    else
+        return false;
+
+    return true;
 }

File diff suppressed because it is too large
+ 505 - 498
src/map/atcommand.c


+ 14 - 14
src/map/atcommand.h

@@ -16,36 +16,36 @@ extern char atcommand_symbol;
 extern char charcommand_symbol;
 
 typedef enum {
-	COMMAND_ATCOMMAND = 1,
-	COMMAND_CHARCOMMAND = 2,
+    COMMAND_ATCOMMAND = 1,
+    COMMAND_CHARCOMMAND = 2,
 } AtCommandType;
 
-typedef int (*AtCommandFunc)(const int fd, struct map_session_data* sd, const char* command, const char* message);
+typedef int (*AtCommandFunc)(const int fd, struct map_session_data *sd, const char *command, const char *message);
 
-bool is_atcommand(const int fd, struct map_session_data* sd, const char* message, int type);
+bool is_atcommand(const int fd, struct map_session_data *sd, const char *message, int type);
 
 void do_init_atcommand(void);
 void do_final_atcommand(void);
-void atcommand_db_load_groups(int* group_ids);
+void atcommand_db_load_groups(int *group_ids);
 
-bool atcommand_exists(const char* name);
+bool atcommand_exists(const char *name);
 
-const char* msg_txt(int msg_number);
-int msg_config_read(const char* cfgName);
+const char *msg_txt(int msg_number);
+int msg_config_read(const char *cfgName);
 void do_final_msg(void);
 
 extern int atcmd_binding_count;
 
 // @commands (script based)
 struct atcmd_binding_data {
-	char command[50];
-	char npc_event[50];
-	int level;
-	int level2;
+    char command[50];
+    char npc_event[50];
+    int level;
+    int level2;
 };
 
-struct atcmd_binding_data** atcmd_binding;
+struct atcmd_binding_data **atcmd_binding;
 
-struct atcmd_binding_data* get_atcommandbind_byname(const char* name);
+struct atcmd_binding_data *get_atcommandbind_byname(const char *name);
 
 #endif /* _ATCOMMAND_H_ */

File diff suppressed because it is too large
+ 781 - 783
src/map/battle.c


+ 424 - 425
src/map/battle.h

@@ -6,22 +6,22 @@
 
 // state of a single attack attempt; used in flee/def penalty calculations when mobbed
 typedef enum damage_lv {
-	ATK_NONE,    // not an attack
-	ATK_LUCKY,   // attack was lucky-dodged
-	ATK_FLEE,    // attack was dodged
-	ATK_MISS,    // attack missed because of element/race modifier.
-	ATK_BLOCK,   // attack was blocked by some skills.
-	ATK_DEF      // attack connected
+    ATK_NONE,    // not an attack
+    ATK_LUCKY,   // attack was lucky-dodged
+    ATK_FLEE,    // attack was dodged
+    ATK_MISS,    // attack missed because of element/race modifier.
+    ATK_BLOCK,   // attack was blocked by some skills.
+    ATK_DEF      // attack connected
 } damage_lv;
 
 // dammage structure
 struct Damage {
-	int damage,damage2; //right, left dmg
-	int type,div_; //chk clif_damage for type @TODO add an enum ? ;  nb of hit
-	int amotion,dmotion;
-	int blewcount; //nb of knockback
-	int flag; //chk BF_* flag, (enum below)
-	enum damage_lv dmg_lv;	//ATK_LUCKY,ATK_FLEE,ATK_DEF
+    int damage,damage2; //right, left dmg
+    int type,div_; //chk clif_damage for type @TODO add an enum ? ;  nb of hit
+    int amotion,dmotion;
+    int blewcount; //nb of knockback
+    int flag; //chk BF_* flag, (enum below)
+    enum damage_lv dmg_lv;  //ATK_LUCKY,ATK_FLEE,ATK_DEF
 };
 
 //(Used in read pc.c,) attribute table (battle_attr_fix)
@@ -47,52 +47,52 @@ int battle_calc_damage(struct block_list *src,struct block_list *bl,struct Damag
 int battle_calc_gvg_damage(struct block_list *src,struct block_list *bl,int damage,int div_,int skill_num,int skill_lv,int flag);
 int battle_calc_bg_damage(struct block_list *src,struct block_list *bl,int damage,int div_,int skill_num,int skill_lv,int flag);
 
-enum {	// Flag of the final calculation
-	BF_WEAPON	= 0x0001,
-	BF_MAGIC	= 0x0002,
-	BF_MISC		= 0x0004,
-	BF_SHORT	= 0x0010,
-	BF_LONG		= 0x0040,
-	BF_SKILL	= 0x0100,
-	BF_NORMAL	= 0x0200,
-	BF_WEAPONMASK=0x000f,
-	BF_RANGEMASK= 0x00f0,
-	BF_SKILLMASK= 0x0f00,
+enum {  // Flag of the final calculation
+    BF_WEAPON   = 0x0001,
+    BF_MAGIC    = 0x0002,
+    BF_MISC     = 0x0004,
+    BF_SHORT    = 0x0010,
+    BF_LONG     = 0x0040,
+    BF_SKILL    = 0x0100,
+    BF_NORMAL   = 0x0200,
+    BF_WEAPONMASK=0x000f,
+    BF_RANGEMASK= 0x00f0,
+    BF_SKILLMASK= 0x0f00,
 };
 
-int battle_delay_damage (unsigned int tick, int amotion, struct block_list *src, struct block_list *target, int attack_type, int skill_id, int skill_lv, int damage, enum damage_lv dmg_lv, int ddelay);
+int battle_delay_damage(unsigned int tick, int amotion, struct block_list *src, struct block_list *target, int attack_type, int skill_id, int skill_lv, int damage, enum damage_lv dmg_lv, int ddelay);
 
 // Summary normal attack treatment (basic attack)
-enum damage_lv battle_weapon_attack( struct block_list *bl,struct block_list *target,unsigned int tick,int flag);
+enum damage_lv battle_weapon_attack(struct block_list *bl,struct block_list *target,unsigned int tick,int flag);
 
 // Accessors
-struct block_list* battle_get_master(struct block_list *src);
-struct block_list* battle_gettargeted(struct block_list *target);
-struct block_list* battle_getenemy(struct block_list *target, int type, int range);
+struct block_list *battle_get_master(struct block_list *src);
+struct block_list *battle_gettargeted(struct block_list *target);
+struct block_list *battle_getenemy(struct block_list *target, int type, int range);
 int battle_gettarget(struct block_list *bl);
 int battle_getcurrentskill(struct block_list *bl);
 
-enum e_battle_check_target
-{//New definitions [Skotlex]
-	BCT_ENEMY   = 0x020000,
-	BCT_NOENEMY = 0x1d0000, //This should be (~BCT_ENEMY&BCT_ALL)
-	BCT_PARTY	= 0x040000,
-	BCT_NOPARTY = 0x1b0000, //This should be (~BCT_PARTY&BCT_ALL)
-	BCT_GUILD	= 0x080000,
-	BCT_NOGUILD = 0x170000, //This should be (~BCT_GUILD&BCT_ALL)
-	BCT_ALL     = 0x1f0000,
-	BCT_NOONE   = 0x000000,
-	BCT_SELF    = 0x010000,
-	BCT_NEUTRAL = 0x100000,
+enum e_battle_check_target {
+    //New definitions [Skotlex]
+    BCT_ENEMY   = 0x020000,
+    BCT_NOENEMY = 0x1d0000, //This should be (~BCT_ENEMY&BCT_ALL)
+    BCT_PARTY   = 0x040000,
+    BCT_NOPARTY = 0x1b0000, //This should be (~BCT_PARTY&BCT_ALL)
+    BCT_GUILD   = 0x080000,
+    BCT_NOGUILD = 0x170000, //This should be (~BCT_GUILD&BCT_ALL)
+    BCT_ALL     = 0x1f0000,
+    BCT_NOONE   = 0x000000,
+    BCT_SELF    = 0x010000,
+    BCT_NEUTRAL = 0x100000,
 };
 
-#define	is_boss(bl)	(status_get_mode(bl)&MD_BOSS)	// Can refine later [Aru]
+#define is_boss(bl) (status_get_mode(bl)&MD_BOSS)   // Can refine later [Aru]
 
 int battle_check_undead(int race,int element);
 int battle_check_target(struct block_list *src, struct block_list *target,int flag);
 bool battle_check_range(struct block_list *src,struct block_list *bl,int range);
 
-void battle_consume_ammo(struct map_session_data* sd, int skill, int lv);
+void battle_consume_ammo(struct map_session_data *sd, int skill, int lv);
 // Settings
 
 #define MIN_HAIR_STYLE battle_config.min_hair_style
@@ -102,386 +102,385 @@ void battle_consume_ammo(struct map_session_data* sd, int skill, int lv);
 #define MIN_CLOTH_COLOR battle_config.min_cloth_color
 #define MAX_CLOTH_COLOR battle_config.max_cloth_color
 
-extern struct Battle_Config
-{
-	int warp_point_debug;
-	int enable_critical;
-	int mob_critical_rate;
-	int critical_rate;
-	int enable_baseatk;
-	int enable_perfect_flee;
-	int cast_rate, delay_rate;
-	int delay_dependon_dex, delay_dependon_agi;
-	int sdelay_attack_enable;
-	int left_cardfix_to_right;
-	int skill_add_range;
-	int skill_out_range_consume;
-	int skill_amotion_leniency;
-	int skillrange_by_distance; //[Skotlex]
-	int use_weapon_skill_range; //[Skotlex]
-	int pc_damage_delay_rate;
-	int defnotenemy;
-	int vs_traps_bctall;
-	int traps_setting;
-	int summon_flora; //[Skotlex]
-	int clear_unit_ondeath; //[Skotlex]
-	int clear_unit_onwarp; //[Skotlex]
-	int random_monster_checklv;
-	int attr_recover;
-	int item_auto_get;
-	int flooritem_lifetime;
-	int item_first_get_time;
-	int item_second_get_time;
-	int item_third_get_time;
-	int mvp_item_first_get_time;
-	int mvp_item_second_get_time;
-	int mvp_item_third_get_time;
-	int base_exp_rate,job_exp_rate;
-	int drop_rate0item;
-	int death_penalty_type;
-	int death_penalty_base,death_penalty_job;
-	int pvp_exp;  // [MouseJstr]
-	int gtb_sc_immunity;
-	int zeny_penalty;
-	int restart_hp_rate;
-	int restart_sp_rate;
-	int mvp_exp_rate;
-	int mvp_hp_rate;
-	int monster_hp_rate;
-	int monster_max_aspd;
-	int view_range_rate;
-	int chase_range_rate;
-	int atc_spawn_quantity_limit;
-	int atc_slave_clone_limit;
-	int partial_name_scan;
-	int skillfree;
-	int skillup_limit;
-	int wp_rate;
-	int pp_rate;
-	int monster_active_enable;
-	int monster_damage_delay_rate;
-	int monster_loot_type;
-	int mob_skill_rate;	//[Skotlex]
-	int mob_skill_delay;	//[Skotlex]
-	int mob_count_rate;
-	int no_spawn_on_player; //[Skotlex]
-	int force_random_spawn; //[Skotlex]
-	int mob_spawn_delay, plant_spawn_delay, boss_spawn_delay;	// [Skotlex]
-	int slaves_inherit_mode;
-	int slaves_inherit_speed;
-	int summons_trigger_autospells;
-	int pc_walk_delay_rate; //Adjusts can't walk delay after being hit for players. [Skotlex]
-	int walk_delay_rate; //Adjusts can't walk delay after being hit. [Skotlex]
-	int multihit_delay;  //Adjusts can't walk delay per hit on multi-hitting skills. [Skotlex]
-	int quest_skill_learn;
-	int quest_skill_reset;
-	int basic_skill_check;
-	int guild_emperium_check;
-	int guild_exp_limit;
-	int guild_max_castles;
-	int guild_skill_relog_delay;
-	int emergency_call;
-	int guild_aura;
-	int pc_invincible_time;
-
-	int pet_catch_rate;
-	int pet_rename;
-	int pet_friendly_rate;
-	int pet_hungry_delay_rate;
-	int pet_hungry_friendly_decrease;
-	int pet_status_support;
-	int pet_attack_support;
-	int pet_damage_support;
-	int pet_support_min_friendly;	//[Skotlex]
-	int pet_equip_min_friendly;
-	int pet_support_rate;
-	int pet_attack_exp_to_master;
-	int pet_attack_exp_rate;
-	int pet_lv_rate; //[Skotlex]
-	int pet_max_stats; //[Skotlex]
-	int pet_max_atk1; //[Skotlex]
-	int pet_max_atk2; //[Skotlex]
-	int pet_no_gvg; //Disables pets in gvg. [Skotlex]
-	int pet_equip_required;
-
-	int skill_min_damage;
-	int finger_offensive_type;
-	int heal_exp;
-	int max_heal_lv;
-	int max_heal; //Mitternacht
-	int resurrection_exp;
-	int shop_exp;
-	int combo_delay_rate;
-	int item_check;
-	int item_use_interval;	//[Skotlex]
-	int cashfood_use_interval;
-	int wedding_modifydisplay;
-	int wedding_ignorepalette;	//[Skotlex]
-	int xmas_ignorepalette;	// [Valaris]
-	int summer_ignorepalette; // [Zephyrus]
-	int natural_healhp_interval;
-	int natural_healsp_interval;
-	int natural_heal_skill_interval;
-	int natural_heal_weight_rate;
-	int arrow_decrement;
-	int max_aspd;
-	int max_walk_speed;	//Maximum walking speed after buffs [Skotlex]
-	int max_hp;
-	int max_sp;
-	int max_lv, aura_lv;
-	int max_parameter, max_baby_parameter;
-	int max_cart_weight;
-	int skill_log;
-	int battle_log;
-	int etc_log;
-	int save_clothcolor;
-	int undead_detect_type;
-	int auto_counter_type;
-	int min_hitrate;	//[Skotlex]
-	int max_hitrate;	//[Skotlex]
-	int agi_penalty_target;
-	int agi_penalty_type;
-	int agi_penalty_count;
-	int agi_penalty_num;
-	int vit_penalty_target;
-	int vit_penalty_type;
-	int vit_penalty_count;
-	int vit_penalty_num;
-	int weapon_defense_type;
-	int magic_defense_type;
-	int skill_reiteration;
-	int skill_nofootset;
-	int pc_cloak_check_type;
-	int monster_cloak_check_type;
-	int estimation_type;
-	int gvg_short_damage_rate;
-	int gvg_long_damage_rate;
-	int gvg_weapon_damage_rate;
-	int gvg_magic_damage_rate;
-	int gvg_misc_damage_rate;
-	int gvg_flee_penalty;
-	int pk_short_damage_rate;
-	int pk_long_damage_rate;
-	int pk_weapon_damage_rate;
-	int pk_magic_damage_rate;
-	int pk_misc_damage_rate;
-	int mob_changetarget_byskill;
-	int attack_direction_change;
-	int land_skill_limit;
-	int monster_class_change_recover;
-	int produce_item_name_input;
-	int display_skill_fail;
-	int chat_warpportal;
-	int mob_warp;
-	int dead_branch_active;
-	int vending_max_value;
-	int vending_over_max;
-	int vending_tax;
-	int show_steal_in_same_party;
-	int party_share_type;
-	int party_hp_mode;
-	int party_show_share_picker;
-	int show_picker_item_type;
-	int attack_attr_none;
-	int item_rate_mvp, item_rate_common, item_rate_common_boss, item_rate_card, item_rate_card_boss,
-		item_rate_equip, item_rate_equip_boss, item_rate_heal, item_rate_heal_boss, item_rate_use,
-		item_rate_use_boss, item_rate_treasure, item_rate_adddrop;
-
-	int logarithmic_drops;
-	int item_drop_common_min,item_drop_common_max;	// Added by TyrNemesis^
-	int item_drop_card_min,item_drop_card_max;
-	int item_drop_equip_min,item_drop_equip_max;
-	int item_drop_mvp_min,item_drop_mvp_max;	// End Addition
-	int item_drop_heal_min,item_drop_heal_max;	// Added by Valatris
-	int item_drop_use_min,item_drop_use_max;	//End
-	int item_drop_treasure_min,item_drop_treasure_max; //by [Skotlex]
-	int item_drop_adddrop_min,item_drop_adddrop_max; //[Skotlex]
-
-	int prevent_logout;	// Added by RoVeRT
-
-	int alchemist_summon_reward;	// [Valaris]
-	int drops_by_luk;
-	int drops_by_luk2;
-	int equip_natural_break_rate;	//Base Natural break rate for attacks.
-	int equip_self_break_rate; //Natural & Penalty skills break rate
-	int equip_skill_break_rate; //Offensive skills break rate
-	int multi_level_up;
-	int max_exp_gain_rate; //Max amount of exp bar % you can get in one go.
-	int pk_mode;
-	int pk_level_range;
-
-	int manner_system; // end additions [Valaris]
-	int show_mob_info; 
-	
-	int gx_allhit;
-	int gx_disptype;
-	int devotion_level_difference;
-	int player_skill_partner_check;
-	int invite_request_check;
-	int skill_removetrap_type;
-	int disp_experience;
-	int disp_zeny;
-	int castle_defense_rate;
-	int backstab_bow_penalty;
-	int hp_rate;
-	int sp_rate;
-	int bone_drop;
-	int buyer_name;
-	int dancing_weaponswitch_fix;
-
-// eAthena additions
-	int night_at_start; // added by [Yor]
-	int day_duration; // added by [Yor]
-	int night_duration; // added by [Yor]
-	int ban_hack_trade; // added by [Yor]
-	int packet_ver_flag; // added by [Yor]
-	
-	int min_hair_style; // added by [MouseJstr]
-	int max_hair_style; // added by [MouseJstr]
-	int min_hair_color; // added by [MouseJstr]
-	int max_hair_color; // added by [MouseJstr]
-	int min_cloth_color; // added by [MouseJstr]
-	int max_cloth_color; // added by [MouseJstr]
-	int pet_hair_style; // added by [Skotlex]
-
-	int castrate_dex_scale; // added by [MouseJstr]
-	int area_size; // added by [MouseJstr]
-
-	int max_def, over_def_bonus; //added by [Skotlex]
-	
-	int zeny_from_mobs; // [Valaris]
-	int mobs_level_up; // [Valaris]
-	int mobs_level_up_exp_rate; // [Valaris]
-	int pk_min_level; // [celest]
-	int skill_steal_max_tries; //max steal skill tries on a mob. if 0, then w/o limit [Lupus]
-	int motd_type; // [celest]
-	int finding_ore_rate; // orn
-	int exp_calc_type;
-	int exp_bonus_attacker;
-	int exp_bonus_max_attacker;
-	int min_skill_delay_limit;
-	int default_walk_delay;
-	int no_skill_delay;
-	int attack_walk_delay;
-	int require_glory_guild;
-	int idle_no_share;
-	int party_update_interval;
-	int party_even_share_bonus;
-	int delay_battle_damage;
-	int hide_woe_damage;
-	int display_version;
-
-	int display_hallucination;	// [Skotlex]
-	int use_statpoint_table;	// [Skotlex]
-
-	int ignore_items_gender; //[Lupus]
-
-	int copyskill_restrict; // [Aru]
-	int berserk_cancels_buffs; // [Aru]
-	int debuff_on_logout; // Removes a few "official" negative Scs on logout. [Skotlex]
-	int mob_ai; //Configures various mob_ai settings to make them smarter or dumber(official). [Skotlex]
-	int hom_setting; //Configures various homunc settings which make them behave unlike normal characters.. [Skotlex]
-	int dynamic_mobs; // Dynamic Mobs [Wizputer] - battle_athena flag implemented by [random]
-	int mob_remove_damaged; // Dynamic Mobs - Remove mobs even if damaged [Wizputer]
-	int mob_remove_delay; // Dynamic Mobs - delay before removing mobs from a map [Skotlex]
-	int mob_active_time; //Duration through which mobs execute their Hard AI after players leave their area of sight.
-	int boss_active_time;
-
-	int show_hp_sp_drain, show_hp_sp_gain;	//[Skotlex]
-
-	int mob_npc_event_type; //Determines on who the npc_event is executed. [Skotlex]
-
-	int character_size; // if riders have size=2, and baby class riders size=1 [Lupus]
-	int mob_max_skilllvl; // Max possible skill level [Lupus]
-	int rare_drop_announce; // chance <= to show rare drops global announces
-
-	int retaliate_to_master;	//Whether when a mob is attacked by another mob, it will retaliate versus the mob or the mob's master. [Skotlex]
-
-	int duel_allow_pvp; // [LuzZza]
-	int duel_allow_gvg; // [LuzZza]
-	int duel_allow_teleport; // [LuzZza]
-	int duel_autoleave_when_die; // [LuzZza]
-	int duel_time_interval; // [LuzZza]
-	int duel_only_on_same_map; // [Toms]
-	
-	int skip_teleport_lv1_menu; // possibility to disable (skip) Teleport Lv1 menu, that have only two lines `Random` and `Cancel` [LuzZza]
-
-	int allow_skill_without_day; // [Komurka]
-	int allow_es_magic_pc; // [Skotlex]
-	int skill_wall_check; // [Skotlex]
-	int cell_stack_limit; // [Skotlex]
-	int skill_caster_check; // [Skotlex]
-	int sc_castcancel; // [Skotlex]
-	int pc_sc_def_rate; // [Skotlex]
-	int mob_sc_def_rate;
-	int pc_luk_sc_def;
-	int mob_luk_sc_def;
-	int pc_max_sc_def;
-	int mob_max_sc_def;
-
-	int sg_angel_skill_ratio;
-	int sg_miracle_skill_ratio;
-	int sg_miracle_skill_duration;
-	int autospell_stacking; //Enables autospell cards to stack. [Skotlex]
-	int override_mob_names; //Enables overriding spawn mob names with the mob_db names. [Skotlex]
-	int min_chat_delay; //Minimum time between client messages. [Skotlex]
-	int friend_auto_add; //When accepting friends, both get friended. [Skotlex]
-	int hvan_explosion_intimate;	// fix [albator]
-	int hom_rename;
-	int homunculus_show_growth ;	//[orn]
-	int homunculus_friendly_rate;
-	int quest_exp_rate;
-	int autotrade_mapflag;
-	int at_timeout;
-	int homunculus_autoloot;
-	int idle_no_autoloot;
-	int max_guild_alliance;
-	int ksprotection;
-	int auction_feeperhour;
-	int auction_maximumprice;
-	int homunculus_auto_vapor;	//Keep Homunculus from Vaporizing when master dies. [L0ne_W0lf]
-	int display_status_timers;	//Show or hide skill buff/delay timers in recent clients [Sara]
-	int skill_add_heal_rate;	//skills that bHealPower has effect on [Inkfish]
-	int eq_single_target_reflectable;
-	int invincible_nodamage;
-	int mob_slave_keep_target;
-	int autospell_check_range;	//Enable range check for autospell bonus. [L0ne_W0lf]
-	int client_reshuffle_dice;  // Reshuffle /dice
-	int client_sort_storage;
-	int feature_buying_store;
-	int feature_search_stores;
-	int searchstore_querydelay;
-	int searchstore_maxresults;
-	int display_party_name;
-	int cashshop_show_points;
-	int mail_show_status;
-	int client_limit_unit_lv;
-	int hom_max_level;
-	int hom_S_max_level;
-
-	// [BattleGround Settings]
-	int bg_update_interval;
-	int bg_short_damage_rate;
-	int bg_long_damage_rate;
-	int bg_weapon_damage_rate;
-	int bg_magic_damage_rate;
-	int bg_misc_damage_rate;
-	int bg_flee_penalty;
-
-	// rAthena
-	int max_third_parameter;
-	int max_baby_third_parameter;
-	int atcommand_max_stat_bypass;
-	int max_third_aspd;
-	int vcast_stat_scale;
-
-	int mvp_tomb_enabled;
-	
-	int atcommand_suggestions_enabled;
+extern struct Battle_Config {
+    int warp_point_debug;
+    int enable_critical;
+    int mob_critical_rate;
+    int critical_rate;
+    int enable_baseatk;
+    int enable_perfect_flee;
+    int cast_rate, delay_rate;
+    int delay_dependon_dex, delay_dependon_agi;
+    int sdelay_attack_enable;
+    int left_cardfix_to_right;
+    int skill_add_range;
+    int skill_out_range_consume;
+    int skill_amotion_leniency;
+    int skillrange_by_distance; //[Skotlex]
+    int use_weapon_skill_range; //[Skotlex]
+    int pc_damage_delay_rate;
+    int defnotenemy;
+    int vs_traps_bctall;
+    int traps_setting;
+    int summon_flora; //[Skotlex]
+    int clear_unit_ondeath; //[Skotlex]
+    int clear_unit_onwarp; //[Skotlex]
+    int random_monster_checklv;
+    int attr_recover;
+    int item_auto_get;
+    int flooritem_lifetime;
+    int item_first_get_time;
+    int item_second_get_time;
+    int item_third_get_time;
+    int mvp_item_first_get_time;
+    int mvp_item_second_get_time;
+    int mvp_item_third_get_time;
+    int base_exp_rate,job_exp_rate;
+    int drop_rate0item;
+    int death_penalty_type;
+    int death_penalty_base,death_penalty_job;
+    int pvp_exp;  // [MouseJstr]
+    int gtb_sc_immunity;
+    int zeny_penalty;
+    int restart_hp_rate;
+    int restart_sp_rate;
+    int mvp_exp_rate;
+    int mvp_hp_rate;
+    int monster_hp_rate;
+    int monster_max_aspd;
+    int view_range_rate;
+    int chase_range_rate;
+    int atc_spawn_quantity_limit;
+    int atc_slave_clone_limit;
+    int partial_name_scan;
+    int skillfree;
+    int skillup_limit;
+    int wp_rate;
+    int pp_rate;
+    int monster_active_enable;
+    int monster_damage_delay_rate;
+    int monster_loot_type;
+    int mob_skill_rate; //[Skotlex]
+    int mob_skill_delay;    //[Skotlex]
+    int mob_count_rate;
+    int no_spawn_on_player; //[Skotlex]
+    int force_random_spawn; //[Skotlex]
+    int mob_spawn_delay, plant_spawn_delay, boss_spawn_delay;   // [Skotlex]
+    int slaves_inherit_mode;
+    int slaves_inherit_speed;
+    int summons_trigger_autospells;
+    int pc_walk_delay_rate; //Adjusts can't walk delay after being hit for players. [Skotlex]
+    int walk_delay_rate; //Adjusts can't walk delay after being hit. [Skotlex]
+    int multihit_delay;  //Adjusts can't walk delay per hit on multi-hitting skills. [Skotlex]
+    int quest_skill_learn;
+    int quest_skill_reset;
+    int basic_skill_check;
+    int guild_emperium_check;
+    int guild_exp_limit;
+    int guild_max_castles;
+    int guild_skill_relog_delay;
+    int emergency_call;
+    int guild_aura;
+    int pc_invincible_time;
+
+    int pet_catch_rate;
+    int pet_rename;
+    int pet_friendly_rate;
+    int pet_hungry_delay_rate;
+    int pet_hungry_friendly_decrease;
+    int pet_status_support;
+    int pet_attack_support;
+    int pet_damage_support;
+    int pet_support_min_friendly;   //[Skotlex]
+    int pet_equip_min_friendly;
+    int pet_support_rate;
+    int pet_attack_exp_to_master;
+    int pet_attack_exp_rate;
+    int pet_lv_rate; //[Skotlex]
+    int pet_max_stats; //[Skotlex]
+    int pet_max_atk1; //[Skotlex]
+    int pet_max_atk2; //[Skotlex]
+    int pet_no_gvg; //Disables pets in gvg. [Skotlex]
+    int pet_equip_required;
+
+    int skill_min_damage;
+    int finger_offensive_type;
+    int heal_exp;
+    int max_heal_lv;
+    int max_heal; //Mitternacht
+    int resurrection_exp;
+    int shop_exp;
+    int combo_delay_rate;
+    int item_check;
+    int item_use_interval;  //[Skotlex]
+    int cashfood_use_interval;
+    int wedding_modifydisplay;
+    int wedding_ignorepalette;  //[Skotlex]
+    int xmas_ignorepalette; // [Valaris]
+    int summer_ignorepalette; // [Zephyrus]
+    int natural_healhp_interval;
+    int natural_healsp_interval;
+    int natural_heal_skill_interval;
+    int natural_heal_weight_rate;
+    int arrow_decrement;
+    int max_aspd;
+    int max_walk_speed; //Maximum walking speed after buffs [Skotlex]
+    int max_hp;
+    int max_sp;
+    int max_lv, aura_lv;
+    int max_parameter, max_baby_parameter;
+    int max_cart_weight;
+    int skill_log;
+    int battle_log;
+    int etc_log;
+    int save_clothcolor;
+    int undead_detect_type;
+    int auto_counter_type;
+    int min_hitrate;    //[Skotlex]
+    int max_hitrate;    //[Skotlex]
+    int agi_penalty_target;
+    int agi_penalty_type;
+    int agi_penalty_count;
+    int agi_penalty_num;
+    int vit_penalty_target;
+    int vit_penalty_type;
+    int vit_penalty_count;
+    int vit_penalty_num;
+    int weapon_defense_type;
+    int magic_defense_type;
+    int skill_reiteration;
+    int skill_nofootset;
+    int pc_cloak_check_type;
+    int monster_cloak_check_type;
+    int estimation_type;
+    int gvg_short_damage_rate;
+    int gvg_long_damage_rate;
+    int gvg_weapon_damage_rate;
+    int gvg_magic_damage_rate;
+    int gvg_misc_damage_rate;
+    int gvg_flee_penalty;
+    int pk_short_damage_rate;
+    int pk_long_damage_rate;
+    int pk_weapon_damage_rate;
+    int pk_magic_damage_rate;
+    int pk_misc_damage_rate;
+    int mob_changetarget_byskill;
+    int attack_direction_change;
+    int land_skill_limit;
+    int monster_class_change_recover;
+    int produce_item_name_input;
+    int display_skill_fail;
+    int chat_warpportal;
+    int mob_warp;
+    int dead_branch_active;
+    int vending_max_value;
+    int vending_over_max;
+    int vending_tax;
+    int show_steal_in_same_party;
+    int party_share_type;
+    int party_hp_mode;
+    int party_show_share_picker;
+    int show_picker_item_type;
+    int attack_attr_none;
+    int item_rate_mvp, item_rate_common, item_rate_common_boss, item_rate_card, item_rate_card_boss,
+        item_rate_equip, item_rate_equip_boss, item_rate_heal, item_rate_heal_boss, item_rate_use,
+        item_rate_use_boss, item_rate_treasure, item_rate_adddrop;
+
+    int logarithmic_drops;
+    int item_drop_common_min,item_drop_common_max;  // Added by TyrNemesis^
+    int item_drop_card_min,item_drop_card_max;
+    int item_drop_equip_min,item_drop_equip_max;
+    int item_drop_mvp_min,item_drop_mvp_max;    // End Addition
+    int item_drop_heal_min,item_drop_heal_max;  // Added by Valatris
+    int item_drop_use_min,item_drop_use_max;    //End
+    int item_drop_treasure_min,item_drop_treasure_max; //by [Skotlex]
+    int item_drop_adddrop_min,item_drop_adddrop_max; //[Skotlex]
+
+    int prevent_logout; // Added by RoVeRT
+
+    int alchemist_summon_reward;    // [Valaris]
+    int drops_by_luk;
+    int drops_by_luk2;
+    int equip_natural_break_rate;   //Base Natural break rate for attacks.
+    int equip_self_break_rate; //Natural & Penalty skills break rate
+    int equip_skill_break_rate; //Offensive skills break rate
+    int multi_level_up;
+    int max_exp_gain_rate; //Max amount of exp bar % you can get in one go.
+    int pk_mode;
+    int pk_level_range;
+
+    int manner_system; // end additions [Valaris]
+    int show_mob_info;
+
+    int gx_allhit;
+    int gx_disptype;
+    int devotion_level_difference;
+    int player_skill_partner_check;
+    int invite_request_check;
+    int skill_removetrap_type;
+    int disp_experience;
+    int disp_zeny;
+    int castle_defense_rate;
+    int backstab_bow_penalty;
+    int hp_rate;
+    int sp_rate;
+    int bone_drop;
+    int buyer_name;
+    int dancing_weaponswitch_fix;
+
+    // eAthena additions
+    int night_at_start; // added by [Yor]
+    int day_duration; // added by [Yor]
+    int night_duration; // added by [Yor]
+    int ban_hack_trade; // added by [Yor]
+    int packet_ver_flag; // added by [Yor]
+
+    int min_hair_style; // added by [MouseJstr]
+    int max_hair_style; // added by [MouseJstr]
+    int min_hair_color; // added by [MouseJstr]
+    int max_hair_color; // added by [MouseJstr]
+    int min_cloth_color; // added by [MouseJstr]
+    int max_cloth_color; // added by [MouseJstr]
+    int pet_hair_style; // added by [Skotlex]
+
+    int castrate_dex_scale; // added by [MouseJstr]
+    int area_size; // added by [MouseJstr]
+
+    int max_def, over_def_bonus; //added by [Skotlex]
+
+    int zeny_from_mobs; // [Valaris]
+    int mobs_level_up; // [Valaris]
+    int mobs_level_up_exp_rate; // [Valaris]
+    int pk_min_level; // [celest]
+    int skill_steal_max_tries; //max steal skill tries on a mob. if 0, then w/o limit [Lupus]
+    int motd_type; // [celest]
+    int finding_ore_rate; // orn
+    int exp_calc_type;
+    int exp_bonus_attacker;
+    int exp_bonus_max_attacker;
+    int min_skill_delay_limit;
+    int default_walk_delay;
+    int no_skill_delay;
+    int attack_walk_delay;
+    int require_glory_guild;
+    int idle_no_share;
+    int party_update_interval;
+    int party_even_share_bonus;
+    int delay_battle_damage;
+    int hide_woe_damage;
+    int display_version;
+
+    int display_hallucination;  // [Skotlex]
+    int use_statpoint_table;    // [Skotlex]
+
+    int ignore_items_gender; //[Lupus]
+
+    int copyskill_restrict; // [Aru]
+    int berserk_cancels_buffs; // [Aru]
+    int debuff_on_logout; // Removes a few "official" negative Scs on logout. [Skotlex]
+    int mob_ai; //Configures various mob_ai settings to make them smarter or dumber(official). [Skotlex]
+    int hom_setting; //Configures various homunc settings which make them behave unlike normal characters.. [Skotlex]
+    int dynamic_mobs; // Dynamic Mobs [Wizputer] - battle_athena flag implemented by [random]
+    int mob_remove_damaged; // Dynamic Mobs - Remove mobs even if damaged [Wizputer]
+    int mob_remove_delay; // Dynamic Mobs - delay before removing mobs from a map [Skotlex]
+    int mob_active_time; //Duration through which mobs execute their Hard AI after players leave their area of sight.
+    int boss_active_time;
+
+    int show_hp_sp_drain, show_hp_sp_gain;  //[Skotlex]
+
+    int mob_npc_event_type; //Determines on who the npc_event is executed. [Skotlex]
+
+    int character_size; // if riders have size=2, and baby class riders size=1 [Lupus]
+    int mob_max_skilllvl; // Max possible skill level [Lupus]
+    int rare_drop_announce; // chance <= to show rare drops global announces
+
+    int retaliate_to_master;    //Whether when a mob is attacked by another mob, it will retaliate versus the mob or the mob's master. [Skotlex]
+
+    int duel_allow_pvp; // [LuzZza]
+    int duel_allow_gvg; // [LuzZza]
+    int duel_allow_teleport; // [LuzZza]
+    int duel_autoleave_when_die; // [LuzZza]
+    int duel_time_interval; // [LuzZza]
+    int duel_only_on_same_map; // [Toms]
+
+    int skip_teleport_lv1_menu; // possibility to disable (skip) Teleport Lv1 menu, that have only two lines `Random` and `Cancel` [LuzZza]
+
+    int allow_skill_without_day; // [Komurka]
+    int allow_es_magic_pc; // [Skotlex]
+    int skill_wall_check; // [Skotlex]
+    int cell_stack_limit; // [Skotlex]
+    int skill_caster_check; // [Skotlex]
+    int sc_castcancel; // [Skotlex]
+    int pc_sc_def_rate; // [Skotlex]
+    int mob_sc_def_rate;
+    int pc_luk_sc_def;
+    int mob_luk_sc_def;
+    int pc_max_sc_def;
+    int mob_max_sc_def;
+
+    int sg_angel_skill_ratio;
+    int sg_miracle_skill_ratio;
+    int sg_miracle_skill_duration;
+    int autospell_stacking; //Enables autospell cards to stack. [Skotlex]
+    int override_mob_names; //Enables overriding spawn mob names with the mob_db names. [Skotlex]
+    int min_chat_delay; //Minimum time between client messages. [Skotlex]
+    int friend_auto_add; //When accepting friends, both get friended. [Skotlex]
+    int hvan_explosion_intimate;    // fix [albator]
+    int hom_rename;
+    int homunculus_show_growth ;    //[orn]
+    int homunculus_friendly_rate;
+    int quest_exp_rate;
+    int autotrade_mapflag;
+    int at_timeout;
+    int homunculus_autoloot;
+    int idle_no_autoloot;
+    int max_guild_alliance;
+    int ksprotection;
+    int auction_feeperhour;
+    int auction_maximumprice;
+    int homunculus_auto_vapor;  //Keep Homunculus from Vaporizing when master dies. [L0ne_W0lf]
+    int display_status_timers;  //Show or hide skill buff/delay timers in recent clients [Sara]
+    int skill_add_heal_rate;    //skills that bHealPower has effect on [Inkfish]
+    int eq_single_target_reflectable;
+    int invincible_nodamage;
+    int mob_slave_keep_target;
+    int autospell_check_range;  //Enable range check for autospell bonus. [L0ne_W0lf]
+    int client_reshuffle_dice;  // Reshuffle /dice
+    int client_sort_storage;
+    int feature_buying_store;
+    int feature_search_stores;
+    int searchstore_querydelay;
+    int searchstore_maxresults;
+    int display_party_name;
+    int cashshop_show_points;
+    int mail_show_status;
+    int client_limit_unit_lv;
+    int hom_max_level;
+    int hom_S_max_level;
+
+    // [BattleGround Settings]
+    int bg_update_interval;
+    int bg_short_damage_rate;
+    int bg_long_damage_rate;
+    int bg_weapon_damage_rate;
+    int bg_magic_damage_rate;
+    int bg_misc_damage_rate;
+    int bg_flee_penalty;
+
+    // rAthena
+    int max_third_parameter;
+    int max_baby_third_parameter;
+    int atcommand_max_stat_bypass;
+    int max_third_aspd;
+    int vcast_stat_scale;
+
+    int mvp_tomb_enabled;
+
+    int atcommand_suggestions_enabled;
     int min_npc_vending_distance;
-	int atcommand_mobinfo_type;
-	
-	int mob_size_influence; // Enable modifications on earned experience, drop rates and monster status depending on monster size. [mkbu95]
+    int atcommand_mobinfo_type;
+
+    int mob_size_influence; // Enable modifications on earned experience, drop rates and monster status depending on monster size. [mkbu95]
 } battle_config;
 
 void do_init_battle(void);
@@ -489,14 +488,14 @@ void do_final_battle(void);
 extern int battle_config_read(const char *cfgName);
 extern void battle_validate_conf(void);
 extern void battle_set_defaults(void);
-int battle_set_value(const char* w1, const char* w2);
-int battle_get_value(const char* w1);
+int battle_set_value(const char *w1, const char *w2);
+int battle_get_value(const char *w1);
 
 //
-struct block_list* battle_getenemyarea(struct block_list *src, int x, int y, int range, int type, int ignore_id);
+struct block_list *battle_getenemyarea(struct block_list *src, int x, int y, int range, int type, int ignore_id);
 /**
  * Royal Guard
  **/
-int battle_damage_area( struct block_list *bl, va_list ap);
+int battle_damage_area(struct block_list *bl, va_list ap);
 
 #endif /* _BATTLE_H_ */

+ 164 - 165
src/map/battleground.c

@@ -22,198 +22,198 @@
 #include <string.h>
 #include <stdio.h>
 
-static DBMap* bg_team_db; // int bg_id -> struct battleground_data*
+static DBMap *bg_team_db; // int bg_id -> struct battleground_data*
 static unsigned int bg_team_counter = 0; // Next bg_id
 
-struct battleground_data* bg_team_search(int bg_id)
-{ // Search a BG Team using bg_id
-	if( !bg_id ) return NULL;
-	return (struct battleground_data *)idb_get(bg_team_db, bg_id);
+struct battleground_data *bg_team_search(int bg_id) {
+    // Search a BG Team using bg_id
+    if (!bg_id) return NULL;
+    return (struct battleground_data *)idb_get(bg_team_db, bg_id);
 }
 
-struct map_session_data* bg_getavailablesd(struct battleground_data *bg)
-{
-	int i;
-	nullpo_retr(NULL, bg);
-	ARR_FIND(0, MAX_BG_MEMBERS, i, bg->members[i].sd != NULL);
-	return( i < MAX_BG_MEMBERS ) ? bg->members[i].sd : NULL;
+struct map_session_data *bg_getavailablesd(struct battleground_data *bg) {
+    int i;
+    nullpo_retr(NULL, bg);
+    ARR_FIND(0, MAX_BG_MEMBERS, i, bg->members[i].sd != NULL);
+    return(i < MAX_BG_MEMBERS) ? bg->members[i].sd : NULL;
 }
 
 int bg_team_delete(int bg_id)
-{ // Deletes BG Team from db
-	int i;
-	struct map_session_data *sd;
-	struct battleground_data *bg = bg_team_search(bg_id);
-
-	if( bg == NULL ) return 0;
-	for( i = 0; i < MAX_BG_MEMBERS; i++ )
-	{
-		if( (sd = bg->members[i].sd) == NULL )
-			continue;
-
-		bg_send_dot_remove(sd);
-		sd->bg_id = 0;
-	}
-	idb_remove(bg_team_db, bg_id);
-	return 1;
+{
+    // Deletes BG Team from db
+    int i;
+    struct map_session_data *sd;
+    struct battleground_data *bg = bg_team_search(bg_id);
+
+    if (bg == NULL) return 0;
+    for (i = 0; i < MAX_BG_MEMBERS; i++) {
+        if ((sd = bg->members[i].sd) == NULL)
+            continue;
+
+        bg_send_dot_remove(sd);
+        sd->bg_id = 0;
+    }
+    idb_remove(bg_team_db, bg_id);
+    return 1;
 }
 
 int bg_team_warp(int bg_id, unsigned short mapindex, short x, short y)
-{ // Warps a Team
-	int i;
-	struct battleground_data *bg = bg_team_search(bg_id);
-	if( bg == NULL ) return 0;
-	for( i = 0; i < MAX_BG_MEMBERS; i++ )
-		if( bg->members[i].sd != NULL ) pc_setpos(bg->members[i].sd, mapindex, x, y, CLR_TELEPORT);
-	return 1;
+{
+    // Warps a Team
+    int i;
+    struct battleground_data *bg = bg_team_search(bg_id);
+    if (bg == NULL) return 0;
+    for (i = 0; i < MAX_BG_MEMBERS; i++)
+        if (bg->members[i].sd != NULL) pc_setpos(bg->members[i].sd, mapindex, x, y, CLR_TELEPORT);
+    return 1;
 }
 
 int bg_send_dot_remove(struct map_session_data *sd)
 {
-	if( sd && sd->bg_id )
-		clif_bg_xy_remove(sd);
-	return 0;
+    if (sd && sd->bg_id)
+        clif_bg_xy_remove(sd);
+    return 0;
 }
 
 int bg_team_join(int bg_id, struct map_session_data *sd)
-{ // Player joins team
-	int i;
-	struct battleground_data *bg = bg_team_search(bg_id);
-	struct map_session_data *pl_sd;
+{
+    // Player joins team
+    int i;
+    struct battleground_data *bg = bg_team_search(bg_id);
+    struct map_session_data *pl_sd;
 
-	if( bg == NULL || sd == NULL || sd->bg_id ) return 0;
+    if (bg == NULL || sd == NULL || sd->bg_id) return 0;
 
-	ARR_FIND(0, MAX_BG_MEMBERS, i, bg->members[i].sd == NULL);
-	if( i == MAX_BG_MEMBERS ) return 0; // No free slots
+    ARR_FIND(0, MAX_BG_MEMBERS, i, bg->members[i].sd == NULL);
+    if (i == MAX_BG_MEMBERS) return 0;  // No free slots
 
-	sd->bg_id = bg_id;
-	bg->members[i].sd = sd;
-	bg->members[i].x = sd->bl.x;
-	bg->members[i].y = sd->bl.y;
-	bg->count++;
+    sd->bg_id = bg_id;
+    bg->members[i].sd = sd;
+    bg->members[i].x = sd->bl.x;
+    bg->members[i].y = sd->bl.y;
+    bg->count++;
 
-	guild_send_dot_remove(sd);
+    guild_send_dot_remove(sd);
 
-	for( i = 0; i < MAX_BG_MEMBERS; i++ )
-	{
-		if( (pl_sd = bg->members[i].sd) != NULL && pl_sd != sd )
-			clif_hpmeter_single(sd->fd, pl_sd->bl.id, pl_sd->battle_status.hp, pl_sd->battle_status.max_hp);
-	}
+    for (i = 0; i < MAX_BG_MEMBERS; i++) {
+        if ((pl_sd = bg->members[i].sd) != NULL && pl_sd != sd)
+            clif_hpmeter_single(sd->fd, pl_sd->bl.id, pl_sd->battle_status.hp, pl_sd->battle_status.max_hp);
+    }
 
-	clif_bg_hp(sd);
-	clif_bg_xy(sd);
-	return 1;
+    clif_bg_hp(sd);
+    clif_bg_xy(sd);
+    return 1;
 }
 
 int bg_team_leave(struct map_session_data *sd, int flag)
-{ // Single Player leaves team
-	int i, bg_id;
-	struct battleground_data *bg;
-	char output[128];
+{
+    // Single Player leaves team
+    int i, bg_id;
+    struct battleground_data *bg;
+    char output[128];
 
-	if( sd == NULL || !sd->bg_id )
-		return 0;
+    if (sd == NULL || !sd->bg_id)
+        return 0;
 
-	bg_send_dot_remove(sd);
-	bg_id = sd->bg_id;
-	sd->bg_id = 0;
+    bg_send_dot_remove(sd);
+    bg_id = sd->bg_id;
+    sd->bg_id = 0;
 
-	if( (bg = bg_team_search(bg_id)) == NULL )
-		return 0;
+    if ((bg = bg_team_search(bg_id)) == NULL)
+        return 0;
 
-	ARR_FIND(0, MAX_BG_MEMBERS, i, bg->members[i].sd == sd);
-	if( i < MAX_BG_MEMBERS ) // Removes member from BG
-		memset(&bg->members[i], 0, sizeof(bg->members[0]));
-	bg->count--;
+    ARR_FIND(0, MAX_BG_MEMBERS, i, bg->members[i].sd == sd);
+    if (i < MAX_BG_MEMBERS)  // Removes member from BG
+        memset(&bg->members[i], 0, sizeof(bg->members[0]));
+    bg->count--;
 
-	if( flag )
-		sprintf(output, "Server : %s has quit the game...", sd->status.name);
-	else
-		sprintf(output, "Server : %s is leaving the battlefield...", sd->status.name);
-	clif_bg_message(bg, 0, "Server", output, strlen(output) + 1);
+    if (flag)
+        sprintf(output, "Server : %s has quit the game...", sd->status.name);
+    else
+        sprintf(output, "Server : %s is leaving the battlefield...", sd->status.name);
+    clif_bg_message(bg, 0, "Server", output, strlen(output) + 1);
 
-	if( bg->logout_event[0] && flag )
-		npc_event(sd, bg->logout_event, 0);
+    if (bg->logout_event[0] && flag)
+        npc_event(sd, bg->logout_event, 0);
 
-	return bg->count;
+    return bg->count;
 }
 
 int bg_member_respawn(struct map_session_data *sd)
-{ // Respawn after killed
-	struct battleground_data *bg;
-	if( sd == NULL || !pc_isdead(sd) || !sd->bg_id || (bg = bg_team_search(sd->bg_id)) == NULL )
-		return 0;
-	if( bg->mapindex == 0 )
-		return 0; // Respawn not handled by Core
-	pc_setpos(sd, bg->mapindex, bg->x, bg->y, CLR_OUTSIGHT);
-	status_revive(&sd->bl, 1, 100);
-
-	return 1; // Warped
+{
+    // Respawn after killed
+    struct battleground_data *bg;
+    if (sd == NULL || !pc_isdead(sd) || !sd->bg_id || (bg = bg_team_search(sd->bg_id)) == NULL)
+        return 0;
+    if (bg->mapindex == 0)
+        return 0; // Respawn not handled by Core
+    pc_setpos(sd, bg->mapindex, bg->x, bg->y, CLR_OUTSIGHT);
+    status_revive(&sd->bl, 1, 100);
+
+    return 1; // Warped
 }
 
 int bg_create(unsigned short mapindex, short rx, short ry, const char *ev, const char *dev)
 {
-	struct battleground_data *bg;
-	bg_team_counter++;
-
-	CREATE(bg, struct battleground_data, 1);
-	bg->bg_id = bg_team_counter;
-	bg->count = 0;
-	bg->mapindex = mapindex;
-	bg->x = rx;
-	bg->y = ry;
-	safestrncpy(bg->logout_event, ev, sizeof(bg->logout_event));
-	safestrncpy(bg->die_event, dev, sizeof(bg->die_event));
-
-	memset(&bg->members, 0, sizeof(bg->members));
-	idb_put(bg_team_db, bg_team_counter, bg);
-
-	return bg->bg_id;
+    struct battleground_data *bg;
+    bg_team_counter++;
+
+    CREATE(bg, struct battleground_data, 1);
+    bg->bg_id = bg_team_counter;
+    bg->count = 0;
+    bg->mapindex = mapindex;
+    bg->x = rx;
+    bg->y = ry;
+    safestrncpy(bg->logout_event, ev, sizeof(bg->logout_event));
+    safestrncpy(bg->die_event, dev, sizeof(bg->die_event));
+
+    memset(&bg->members, 0, sizeof(bg->members));
+    idb_put(bg_team_db, bg_team_counter, bg);
+
+    return bg->bg_id;
 }
 
 int bg_team_get_id(struct block_list *bl)
 {
-	nullpo_ret(bl);
-	switch( bl->type )
-	{
-		case BL_PC:
-			return ((TBL_PC*)bl)->bg_id;
-		case BL_PET:
-			if( ((TBL_PET*)bl)->msd )
-				return ((TBL_PET*)bl)->msd->bg_id;
-			break;
-		case BL_MOB:
-		{
-			struct map_session_data *msd;
-			struct mob_data *md = (TBL_MOB*)bl;
-			if( md->special_state.ai && (msd = map_id2sd(md->master_id)) != NULL )
-				return msd->bg_id;
-			return md->bg_id;
-		}
-		case BL_HOM:
-			if( ((TBL_HOM*)bl)->master )
-				return ((TBL_HOM*)bl)->master->bg_id;
-			break;
-		case BL_MER:
-			if( ((TBL_MER*)bl)->master )
-				return ((TBL_MER*)bl)->master->bg_id;
-			break;
-		case BL_SKILL:
-			return ((TBL_SKILL*)bl)->group->bg_id;
-	}
-
-	return 0;
+    nullpo_ret(bl);
+    switch (bl->type) {
+        case BL_PC:
+            return ((TBL_PC *)bl)->bg_id;
+        case BL_PET:
+            if (((TBL_PET *)bl)->msd)
+                return ((TBL_PET *)bl)->msd->bg_id;
+            break;
+        case BL_MOB: {
+                struct map_session_data *msd;
+                struct mob_data *md = (TBL_MOB *)bl;
+                if (md->special_state.ai && (msd = map_id2sd(md->master_id)) != NULL)
+                    return msd->bg_id;
+                return md->bg_id;
+            }
+        case BL_HOM:
+            if (((TBL_HOM *)bl)->master)
+                return ((TBL_HOM *)bl)->master->bg_id;
+            break;
+        case BL_MER:
+            if (((TBL_MER *)bl)->master)
+                return ((TBL_MER *)bl)->master->bg_id;
+            break;
+        case BL_SKILL:
+            return ((TBL_SKILL *)bl)->group->bg_id;
+    }
+
+    return 0;
 }
 
 int bg_send_message(struct map_session_data *sd, const char *mes, int len)
 {
-	struct battleground_data *bg;
+    struct battleground_data *bg;
 
-	nullpo_ret(sd);
-	if( sd->bg_id == 0 || (bg = bg_team_search(sd->bg_id)) == NULL )
-		return 0;
-	clif_bg_message(bg, sd->bl.id, sd->status.name, mes, len);
-	return 0;
+    nullpo_ret(sd);
+    if (sd->bg_id == 0 || (bg = bg_team_search(sd->bg_id)) == NULL)
+        return 0;
+    clif_bg_message(bg, sd->bl.id, sd->status.name, mes, len);
+    return 0;
 }
 
 /**
@@ -221,38 +221,37 @@ int bg_send_message(struct map_session_data *sd, const char *mes, int len)
  */
 int bg_send_xy_timer_sub(DBKey key, DBData *data, va_list ap)
 {
-	struct battleground_data *bg = db_data2ptr(data);
-	struct map_session_data *sd;
-	int i;
-	nullpo_ret(bg);
-	for( i = 0; i < MAX_BG_MEMBERS; i++ )
-	{
-		if( (sd = bg->members[i].sd) == NULL )
-			continue;
-		if( sd->bl.x != bg->members[i].x || sd->bl.y != bg->members[i].y )
-		{ // xy update
-			bg->members[i].x = sd->bl.x;
-			bg->members[i].y = sd->bl.y;
-			clif_bg_xy(sd);
-		}
-	}
-	return 0;
+    struct battleground_data *bg = db_data2ptr(data);
+    struct map_session_data *sd;
+    int i;
+    nullpo_ret(bg);
+    for (i = 0; i < MAX_BG_MEMBERS; i++) {
+        if ((sd = bg->members[i].sd) == NULL)
+            continue;
+        if (sd->bl.x != bg->members[i].x || sd->bl.y != bg->members[i].y) {
+            // xy update
+            bg->members[i].x = sd->bl.x;
+            bg->members[i].y = sd->bl.y;
+            clif_bg_xy(sd);
+        }
+    }
+    return 0;
 }
 
 int bg_send_xy_timer(int tid, unsigned int tick, int id, intptr_t data)
 {
-	bg_team_db->foreach(bg_team_db, bg_send_xy_timer_sub, tick);
-	return 0;
+    bg_team_db->foreach(bg_team_db, bg_send_xy_timer_sub, tick);
+    return 0;
 }
 
 void do_init_battleground(void)
 {
-	bg_team_db = idb_alloc(DB_OPT_RELEASE_DATA);
-	add_timer_func_list(bg_send_xy_timer, "bg_send_xy_timer");
-	add_timer_interval(gettick() + battle_config.bg_update_interval, bg_send_xy_timer, 0, 0, battle_config.bg_update_interval);
+    bg_team_db = idb_alloc(DB_OPT_RELEASE_DATA);
+    add_timer_func_list(bg_send_xy_timer, "bg_send_xy_timer");
+    add_timer_interval(gettick() + battle_config.bg_update_interval, bg_send_xy_timer, 0, 0, battle_config.bg_update_interval);
 }
 
 void do_final_battleground(void)
 {
-	bg_team_db->destroy(bg_team_db, NULL);
+    bg_team_db->destroy(bg_team_db, NULL);
 }

+ 13 - 13
src/map/battleground.h

@@ -10,29 +10,29 @@
 #define MAX_BG_MEMBERS 30
 
 struct battleground_member_data {
-	unsigned short x, y;
-	struct map_session_data *sd;
-	unsigned afk : 1;
+    unsigned short x, y;
+    struct map_session_data *sd;
+    unsigned afk : 1;
 };
 
 struct battleground_data {
-	unsigned int bg_id;
-	unsigned char count;
-	struct battleground_member_data members[MAX_BG_MEMBERS];
-	// BG Cementery
-	unsigned short mapindex, x, y;
-	// Logout Event
-	char logout_event[EVENT_NAME_LENGTH];
-	char die_event[EVENT_NAME_LENGTH];
+    unsigned int bg_id;
+    unsigned char count;
+    struct battleground_member_data members[MAX_BG_MEMBERS];
+    // BG Cementery
+    unsigned short mapindex, x, y;
+    // Logout Event
+    char logout_event[EVENT_NAME_LENGTH];
+    char die_event[EVENT_NAME_LENGTH];
 };
 
 void do_init_battleground(void);
 void do_final_battleground(void);
 
-struct battleground_data* bg_team_search(int bg_id);
+struct battleground_data *bg_team_search(int bg_id);
 int bg_send_dot_remove(struct map_session_data *sd);
 int bg_team_get_id(struct block_list *bl);
-struct map_session_data* bg_getavailablesd(struct battleground_data *bg);
+struct map_session_data *bg_getavailablesd(struct battleground_data *bg);
 
 int bg_create(unsigned short mapindex, short rx, short ry, const char *ev, const char *dev);
 int bg_team_join(int bg_id, struct map_session_data *sd);

+ 398 - 406
src/map/buyingstore.c

@@ -20,16 +20,15 @@
 
 
 /// failure constants for clif functions
-enum e_buyingstore_failure
-{
-	BUYINGSTORE_CREATE               = 1,  // "Failed to open buying store."
-	BUYINGSTORE_CREATE_OVERWEIGHT    = 2,  // "Total amount of then possessed items exceeds the weight limit by %d. Please re-enter."
-	BUYINGSTORE_TRADE_BUYER_ZENY     = 3,  // "All items within the buy limit were purchased."
-	BUYINGSTORE_TRADE_BUYER_NO_ITEMS = 4,  // "All items were purchased."
-	BUYINGSTORE_TRADE_SELLER_FAILED  = 5,  // "The deal has failed."
-	BUYINGSTORE_TRADE_SELLER_COUNT   = 6,  // "The trade failed, because the entered amount of item %s is higher, than the buyer is willing to buy."
-	BUYINGSTORE_TRADE_SELLER_ZENY    = 7,  // "The trade failed, because the buyer is lacking required balance."
-	BUYINGSTORE_CREATE_NO_INFO       = 8,  // "No sale (purchase) information available."
+enum e_buyingstore_failure {
+    BUYINGSTORE_CREATE               = 1,  // "Failed to open buying store."
+    BUYINGSTORE_CREATE_OVERWEIGHT    = 2,  // "Total amount of then possessed items exceeds the weight limit by %d. Please re-enter."
+    BUYINGSTORE_TRADE_BUYER_ZENY     = 3,  // "All items within the buy limit were purchased."
+    BUYINGSTORE_TRADE_BUYER_NO_ITEMS = 4,  // "All items were purchased."
+    BUYINGSTORE_TRADE_SELLER_FAILED  = 5,  // "The deal has failed."
+    BUYINGSTORE_TRADE_SELLER_COUNT   = 6,  // "The trade failed, because the entered amount of item %s is higher, than the buyer is willing to buy."
+    BUYINGSTORE_TRADE_SELLER_ZENY    = 7,  // "The trade failed, because the buyer is lacking required balance."
+    BUYINGSTORE_CREATE_NO_INFO       = 8,  // "No sale (purchase) information available."
 };
 
 
@@ -40,434 +39,427 @@ static const short buyingstore_blankslots[MAX_SLOTS] = { 0 };  // used when chec
 /// Returns unique buying store id
 static unsigned int buyingstore_getuid(void)
 {
-	return buyingstore_nextid++;
+    return buyingstore_nextid++;
 }
 
 
-bool buyingstore_setup(struct map_session_data* sd, unsigned char slots)
+bool buyingstore_setup(struct map_session_data *sd, unsigned char slots)
 {
-	if( !battle_config.feature_buying_store || sd->state.vending || sd->state.buyingstore || sd->state.trading || slots == 0 )
-	{
-		return false;
-	}
-
-	if( sd->sc.data[SC_NOCHAT] && (sd->sc.data[SC_NOCHAT]->val1&MANNER_NOROOM) )
-	{// custom: mute limitation
-		return false;
-	}
-
-	if( map[sd->bl.m].flag.novending )
-	{// custom: no vending maps
-		clif_displaymessage(sd->fd, msg_txt(276)); // "You can't open a shop on this map"
-		return false;
-	}
-
-	if( map_getcell(sd->bl.m, sd->bl.x, sd->bl.y, CELL_CHKNOVENDING) )
-	{// custom: no vending cells
-		clif_displaymessage(sd->fd, msg_txt(204)); // "You can't open a shop on this cell."
-		return false;
-	}
-
-	if( slots > MAX_BUYINGSTORE_SLOTS )
-	{
-		ShowWarning("buyingstore_setup: Requested %d slots, but server supports only %d slots.\n", (int)slots, MAX_BUYINGSTORE_SLOTS);
-		slots = MAX_BUYINGSTORE_SLOTS;
-	}
-
-	sd->buyingstore.slots = slots;
-	clif_buyingstore_open(sd);
-
-	return true;
+    if (!battle_config.feature_buying_store || sd->state.vending || sd->state.buyingstore || sd->state.trading || slots == 0) {
+        return false;
+    }
+
+    if (sd->sc.data[SC_NOCHAT] && (sd->sc.data[SC_NOCHAT]->val1&MANNER_NOROOM)) {
+        // custom: mute limitation
+        return false;
+    }
+
+    if (map[sd->bl.m].flag.novending) {
+        // custom: no vending maps
+        clif_displaymessage(sd->fd, msg_txt(276)); // "You can't open a shop on this map"
+        return false;
+    }
+
+    if (map_getcell(sd->bl.m, sd->bl.x, sd->bl.y, CELL_CHKNOVENDING)) {
+        // custom: no vending cells
+        clif_displaymessage(sd->fd, msg_txt(204)); // "You can't open a shop on this cell."
+        return false;
+    }
+
+    if (slots > MAX_BUYINGSTORE_SLOTS) {
+        ShowWarning("buyingstore_setup: Requested %d slots, but server supports only %d slots.\n", (int)slots, MAX_BUYINGSTORE_SLOTS);
+        slots = MAX_BUYINGSTORE_SLOTS;
+    }
+
+    sd->buyingstore.slots = slots;
+    clif_buyingstore_open(sd);
+
+    return true;
 }
 
 
-void buyingstore_create(struct map_session_data* sd, int zenylimit, unsigned char result, const char* storename, const uint8* itemlist, unsigned int count)
+void buyingstore_create(struct map_session_data *sd, int zenylimit, unsigned char result, const char *storename, const uint8 *itemlist, unsigned int count)
 {
-	unsigned int i, weight, listidx;
-	struct item_data* id;
-
-	if( !result || count == 0 )
-	{// canceled, or no items
-		return;
-	}
-
-	if( !battle_config.feature_buying_store || pc_istrading(sd) || sd->buyingstore.slots == 0 || count > sd->buyingstore.slots || zenylimit <= 0 || zenylimit > sd->status.zeny || !storename[0] )
-	{// disabled or invalid input
-		sd->buyingstore.slots = 0;
-		clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
-		return;
-	}
-
-	if( !pc_can_give_items(sd) )
-	{// custom: GM is not allowed to buy (give zeny)
-		sd->buyingstore.slots = 0;
-		clif_displaymessage(sd->fd, msg_txt(246));
-		clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
-		return;
-	}
-
-	if( sd->sc.data[SC_NOCHAT] && (sd->sc.data[SC_NOCHAT]->val1&MANNER_NOROOM) )
-	{// custom: mute limitation
-		return;
-	}
-
-	if( map[sd->bl.m].flag.novending )
-	{// custom: no vending maps
-		clif_displaymessage(sd->fd, msg_txt(276)); // "You can't open a shop on this map"
-		return;
-	}
-
-	if( map_getcell(sd->bl.m, sd->bl.x, sd->bl.y, CELL_CHKNOVENDING) )
-	{// custom: no vending cells
-		clif_displaymessage(sd->fd, msg_txt(204)); // "You can't open a shop on this cell."
-		return;
-	}
-
-	weight = sd->weight;
-
-	// check item list
-	for( i = 0; i < count; i++ )
-	{// itemlist: <name id>.W <amount>.W <price>.L
-		unsigned short nameid, amount;
-		int price, idx;
-
-		nameid = RBUFW(itemlist,i*8+0);
-		amount = RBUFW(itemlist,i*8+2);
-		price  = RBUFL(itemlist,i*8+4);
-
-		if( ( id = itemdb_exists(nameid) ) == NULL || amount == 0 )
-		{// invalid input
-			break;
-		}
-
-		if( price <= 0 || price > BUYINGSTORE_MAX_PRICE )
-		{// invalid price: unlike vending, items cannot be bought at 0 Zeny
-			break;
-		}
-
-		if( !id->flag.buyingstore || !itemdb_cantrade_sub(id, pc_get_group_level(sd), pc_get_group_level(sd)) || ( idx = pc_search_inventory(sd, nameid) ) == -1 )
-		{// restrictions: allowed, no character-bound items and at least one must be owned
-			break;
-		}
-
-		if( sd->status.inventory[idx].amount+amount > BUYINGSTORE_MAX_AMOUNT )
-		{// too many items of same kind
-			break;
-		}
-
-		if( i )
-		{// duplicate check. as the client does this too, only malicious intent should be caught here
-			ARR_FIND( 0, i, listidx, sd->buyingstore.items[listidx].nameid == nameid );
-			if( listidx != i )
-			{// duplicate
-				ShowWarning("buyingstore_create: Found duplicate item on buying list (nameid=%hu, amount=%hu, account_id=%d, char_id=%d).\n", nameid, amount, sd->status.account_id, sd->status.char_id);
-				break;
-			}
-		}
-
-		weight+= id->weight*amount;
-		sd->buyingstore.items[i].nameid = nameid;
-		sd->buyingstore.items[i].amount = amount;
-		sd->buyingstore.items[i].price  = price;
-	}
-
-	if( i != count )
-	{// invalid item/amount/price
-		sd->buyingstore.slots = 0;
-		clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
-		return;
-	}
-
-	if( (sd->max_weight*90)/100 < weight )
-	{// not able to carry all wanted items without getting overweight (90%)
-		sd->buyingstore.slots = 0;
-		clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE_OVERWEIGHT, weight);
-		return;
-	}
-
-	// success
-	sd->state.buyingstore = true;
-	sd->buyer_id = buyingstore_getuid();
-	sd->buyingstore.zenylimit = zenylimit;
-	sd->buyingstore.slots = i;  // store actual amount of items
-	safestrncpy(sd->message, storename, sizeof(sd->message));
-	clif_buyingstore_myitemlist(sd);
-	clif_buyingstore_entry(sd);
+    unsigned int i, weight, listidx;
+    struct item_data *id;
+
+    if (!result || count == 0) {
+        // canceled, or no items
+        return;
+    }
+
+    if (!battle_config.feature_buying_store || pc_istrading(sd) || sd->buyingstore.slots == 0 || count > sd->buyingstore.slots || zenylimit <= 0 || zenylimit > sd->status.zeny || !storename[0]) {
+        // disabled or invalid input
+        sd->buyingstore.slots = 0;
+        clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
+        return;
+    }
+
+    if (!pc_can_give_items(sd)) {
+        // custom: GM is not allowed to buy (give zeny)
+        sd->buyingstore.slots = 0;
+        clif_displaymessage(sd->fd, msg_txt(246));
+        clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
+        return;
+    }
+
+    if (sd->sc.data[SC_NOCHAT] && (sd->sc.data[SC_NOCHAT]->val1&MANNER_NOROOM)) {
+        // custom: mute limitation
+        return;
+    }
+
+    if (map[sd->bl.m].flag.novending) {
+        // custom: no vending maps
+        clif_displaymessage(sd->fd, msg_txt(276)); // "You can't open a shop on this map"
+        return;
+    }
+
+    if (map_getcell(sd->bl.m, sd->bl.x, sd->bl.y, CELL_CHKNOVENDING)) {
+        // custom: no vending cells
+        clif_displaymessage(sd->fd, msg_txt(204)); // "You can't open a shop on this cell."
+        return;
+    }
+
+    weight = sd->weight;
+
+    // check item list
+    for (i = 0; i < count; i++) {
+        // itemlist: <name id>.W <amount>.W <price>.L
+        unsigned short nameid, amount;
+        int price, idx;
+
+        nameid = RBUFW(itemlist,i*8+0);
+        amount = RBUFW(itemlist,i*8+2);
+        price  = RBUFL(itemlist,i*8+4);
+
+        if ((id = itemdb_exists(nameid)) == NULL || amount == 0) {
+            // invalid input
+            break;
+        }
+
+        if (price <= 0 || price > BUYINGSTORE_MAX_PRICE) {
+            // invalid price: unlike vending, items cannot be bought at 0 Zeny
+            break;
+        }
+
+        if (!id->flag.buyingstore || !itemdb_cantrade_sub(id, pc_get_group_level(sd), pc_get_group_level(sd)) || (idx = pc_search_inventory(sd, nameid)) == -1) {
+            // restrictions: allowed, no character-bound items and at least one must be owned
+            break;
+        }
+
+        if (sd->status.inventory[idx].amount+amount > BUYINGSTORE_MAX_AMOUNT) {
+            // too many items of same kind
+            break;
+        }
+
+        if (i) {
+            // duplicate check. as the client does this too, only malicious intent should be caught here
+            ARR_FIND(0, i, listidx, sd->buyingstore.items[listidx].nameid == nameid);
+            if (listidx != i) {
+                // duplicate
+                ShowWarning("buyingstore_create: Found duplicate item on buying list (nameid=%hu, amount=%hu, account_id=%d, char_id=%d).\n", nameid, amount, sd->status.account_id, sd->status.char_id);
+                break;
+            }
+        }
+
+        weight+= id->weight*amount;
+        sd->buyingstore.items[i].nameid = nameid;
+        sd->buyingstore.items[i].amount = amount;
+        sd->buyingstore.items[i].price  = price;
+    }
+
+    if (i != count) {
+        // invalid item/amount/price
+        sd->buyingstore.slots = 0;
+        clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0);
+        return;
+    }
+
+    if ((sd->max_weight*90)/100 < weight) {
+        // not able to carry all wanted items without getting overweight (90%)
+        sd->buyingstore.slots = 0;
+        clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE_OVERWEIGHT, weight);
+        return;
+    }
+
+    // success
+    sd->state.buyingstore = true;
+    sd->buyer_id = buyingstore_getuid();
+    sd->buyingstore.zenylimit = zenylimit;
+    sd->buyingstore.slots = i;  // store actual amount of items
+    safestrncpy(sd->message, storename, sizeof(sd->message));
+    clif_buyingstore_myitemlist(sd);
+    clif_buyingstore_entry(sd);
 }
 
 
-void buyingstore_close(struct map_session_data* sd)
+void buyingstore_close(struct map_session_data *sd)
 {
-	if( sd->state.buyingstore )
-	{
-		// invalidate data
-		sd->state.buyingstore = false;
-		memset(&sd->buyingstore, 0, sizeof(sd->buyingstore));
-
-		// notify other players
-		clif_buyingstore_disappear_entry(sd);
-	}
+    if (sd->state.buyingstore) {
+        // invalidate data
+        sd->state.buyingstore = false;
+        memset(&sd->buyingstore, 0, sizeof(sd->buyingstore));
+
+        // notify other players
+        clif_buyingstore_disappear_entry(sd);
+    }
 }
 
 
-void buyingstore_open(struct map_session_data* sd, int account_id)
+void buyingstore_open(struct map_session_data *sd, int account_id)
 {
-	struct map_session_data* pl_sd;
-
-	if( !battle_config.feature_buying_store || pc_istrading(sd) )
-	{// not allowed to sell
-		return;
-	}
-
-	if( !pc_can_give_items(sd) )
-	{// custom: GM is not allowed to sell
-		clif_displaymessage(sd->fd, msg_txt(246));
-		return;
-	}
-
-	if( ( pl_sd = map_id2sd(account_id) ) == NULL || !pl_sd->state.buyingstore )
-	{// not online or not buying
-		return;
-	}
-
-	if( !searchstore_queryremote(sd, account_id) && ( sd->bl.m != pl_sd->bl.m || !check_distance_bl(&sd->bl, &pl_sd->bl, AREA_SIZE) ) )
-	{// out of view range
-		return;
-	}
-
-	// success
-	clif_buyingstore_itemlist(sd, pl_sd);
+    struct map_session_data *pl_sd;
+
+    if (!battle_config.feature_buying_store || pc_istrading(sd)) {
+        // not allowed to sell
+        return;
+    }
+
+    if (!pc_can_give_items(sd)) {
+        // custom: GM is not allowed to sell
+        clif_displaymessage(sd->fd, msg_txt(246));
+        return;
+    }
+
+    if ((pl_sd = map_id2sd(account_id)) == NULL || !pl_sd->state.buyingstore) {
+        // not online or not buying
+        return;
+    }
+
+    if (!searchstore_queryremote(sd, account_id) && (sd->bl.m != pl_sd->bl.m || !check_distance_bl(&sd->bl, &pl_sd->bl, AREA_SIZE))) {
+        // out of view range
+        return;
+    }
+
+    // success
+    clif_buyingstore_itemlist(sd, pl_sd);
 }
 
 
-void buyingstore_trade(struct map_session_data* sd, int account_id, unsigned int buyer_id, const uint8* itemlist, unsigned int count)
+void buyingstore_trade(struct map_session_data *sd, int account_id, unsigned int buyer_id, const uint8 *itemlist, unsigned int count)
 {
-	int zeny = 0;
-	unsigned int i, weight, listidx, k;
-	struct map_session_data* pl_sd;
-
-	if( count == 0 )
-	{// nothing to do
-		return;
-	}
-
-	if( !battle_config.feature_buying_store || pc_istrading(sd) )
-	{// not allowed to sell
-		clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
-		return;
-	}
-
-	if( !pc_can_give_items(sd) )
-	{// custom: GM is not allowed to sell
-		clif_displaymessage(sd->fd, msg_txt(246));
-		clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
-		return;
-	}
-
-	if( ( pl_sd = map_id2sd(account_id) ) == NULL || !pl_sd->state.buyingstore || pl_sd->buyer_id != buyer_id )
-	{// not online, not buying or not same store
-		clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
-		return;
-	}
-
-	if( !searchstore_queryremote(sd, account_id) && ( sd->bl.m != pl_sd->bl.m || !check_distance_bl(&sd->bl, &pl_sd->bl, AREA_SIZE) ) )
-	{// out of view range
-		clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
-		return;
-	}
-
-	searchstore_clearremote(sd);
-
-	if( pl_sd->status.zeny < pl_sd->buyingstore.zenylimit )
-	{// buyer lost zeny in the mean time? fix the limit
-		pl_sd->buyingstore.zenylimit = pl_sd->status.zeny;
-	}
-	weight = pl_sd->weight;
-
-	// check item list
-	for( i = 0; i < count; i++ )
-	{// itemlist: <index>.W <name id>.W <amount>.W
-		unsigned short nameid, amount;
-		int index;
-
-		index  = RBUFW(itemlist,i*6+0)-2;
-		nameid = RBUFW(itemlist,i*6+2);
-		amount = RBUFW(itemlist,i*6+4);
-
-		if( i )
-		{// duplicate check. as the client does this too, only malicious intent should be caught here
-			ARR_FIND( 0, i, k, RBUFW(itemlist,k*6+0)-2 == index );
-			if( k != i )
-			{// duplicate
-				ShowWarning("buyingstore_trade: Found duplicate item on selling list (prevnameid=%hu, prevamount=%hu, nameid=%hu, amount=%hu, account_id=%d, char_id=%d).\n",
-					RBUFW(itemlist,k*6+2), RBUFW(itemlist,k*6+4), nameid, amount, sd->status.account_id, sd->status.char_id);
-				clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
-				return;
-			}
-		}
-
-		if( index < 0 || index >= ARRAYLENGTH(sd->status.inventory) || sd->inventory_data[index] == NULL || sd->status.inventory[index].nameid != nameid || sd->status.inventory[index].amount < amount )
-		{// invalid input
-			clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
-			return;
-		}
-
-		if( sd->status.inventory[index].expire_time || !itemdb_cantrade(&sd->status.inventory[index], pc_get_group_level(sd), pc_get_group_level(pl_sd)) || memcmp(sd->status.inventory[index].card, buyingstore_blankslots, sizeof(buyingstore_blankslots)) )
-		{// non-tradable item
-			clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
-			return;
-		}
-
-		ARR_FIND( 0, pl_sd->buyingstore.slots, listidx, pl_sd->buyingstore.items[listidx].nameid == nameid );
-		if( listidx == pl_sd->buyingstore.slots || pl_sd->buyingstore.items[listidx].amount == 0 )
-		{// there is no such item or the buyer has already bought all of them
-			clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
-			return;
-		}
-
-		if( pl_sd->buyingstore.items[listidx].amount < amount )
-		{// buyer does not need that much of the item
-			clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_COUNT, nameid);
-			return;
-		}
-
-		if( pc_checkadditem(pl_sd, nameid, amount) == ADDITEM_OVERAMOUNT )
-		{// buyer does not have enough space for this item
-			clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
-			return;
-		}
-
-		if( amount*(unsigned int)sd->inventory_data[index]->weight > pl_sd->max_weight-weight )
-		{// normally this is not supposed to happen, as the total weight is
-		 // checked upon creation, but the buyer could have gained items
-			clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
-			return;
-		}
-		weight+= amount*sd->inventory_data[index]->weight;
-
-		if( amount*pl_sd->buyingstore.items[listidx].price > pl_sd->buyingstore.zenylimit-zeny )
-		{// buyer does not have enough zeny
-			clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_ZENY, nameid);
-			return;
-		}
-		zeny+= amount*pl_sd->buyingstore.items[listidx].price;
-	}
-
-	// process item list
-	for( i = 0; i < count; i++ )
-	{// itemlist: <index>.W <name id>.W <amount>.W
-		unsigned short nameid, amount;
-		int index;
-
-		index  = RBUFW(itemlist,i*6+0)-2;
-		nameid = RBUFW(itemlist,i*6+2);
-		amount = RBUFW(itemlist,i*6+4);
-
-		ARR_FIND( 0, pl_sd->buyingstore.slots, listidx, pl_sd->buyingstore.items[listidx].nameid == nameid );
-		zeny = amount*pl_sd->buyingstore.items[listidx].price;
-
-		// move item
-		pc_additem(pl_sd, &sd->status.inventory[index], amount, LOG_TYPE_BUYING_STORE);
-		pc_delitem(sd, index, amount, 1, 0, LOG_TYPE_BUYING_STORE);
-		pl_sd->buyingstore.items[listidx].amount-= amount;
-
-		// pay up
-		pc_payzeny(pl_sd, zeny, LOG_TYPE_BUYING_STORE, sd);
-		pc_getzeny(sd, zeny, LOG_TYPE_BUYING_STORE, pl_sd);
-		pl_sd->buyingstore.zenylimit-= zeny;
-
-		// notify clients
-		clif_buyingstore_delete_item(sd, index, amount, pl_sd->buyingstore.items[listidx].price);
-		clif_buyingstore_update_item(pl_sd, nameid, amount);
-	}
-
-	// check whether or not there is still something to buy
-	ARR_FIND( 0, pl_sd->buyingstore.slots, i, pl_sd->buyingstore.items[i].amount != 0 );
-	if( i == pl_sd->buyingstore.slots )
-	{// everything was bought
-		clif_buyingstore_trade_failed_buyer(pl_sd, BUYINGSTORE_TRADE_BUYER_NO_ITEMS);
-	}
-	else if( pl_sd->buyingstore.zenylimit == 0 )
-	{// zeny limit reached
-		clif_buyingstore_trade_failed_buyer(pl_sd, BUYINGSTORE_TRADE_BUYER_ZENY);
-	}
-	else
-	{// continue buying
-		return;
-	}
-
-	// cannot continue buying
-	buyingstore_close(pl_sd);
-
-	// remove auto-trader
-	if( pl_sd->state.autotrade )
-	{
-		map_quit(pl_sd);
-	}
+    int zeny = 0;
+    unsigned int i, weight, listidx, k;
+    struct map_session_data *pl_sd;
+
+    if (count == 0) {
+        // nothing to do
+        return;
+    }
+
+    if (!battle_config.feature_buying_store || pc_istrading(sd)) {
+        // not allowed to sell
+        clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
+        return;
+    }
+
+    if (!pc_can_give_items(sd)) {
+        // custom: GM is not allowed to sell
+        clif_displaymessage(sd->fd, msg_txt(246));
+        clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
+        return;
+    }
+
+    if ((pl_sd = map_id2sd(account_id)) == NULL || !pl_sd->state.buyingstore || pl_sd->buyer_id != buyer_id) {
+        // not online, not buying or not same store
+        clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
+        return;
+    }
+
+    if (!searchstore_queryremote(sd, account_id) && (sd->bl.m != pl_sd->bl.m || !check_distance_bl(&sd->bl, &pl_sd->bl, AREA_SIZE))) {
+        // out of view range
+        clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0);
+        return;
+    }
+
+    searchstore_clearremote(sd);
+
+    if (pl_sd->status.zeny < pl_sd->buyingstore.zenylimit) {
+        // buyer lost zeny in the mean time? fix the limit
+        pl_sd->buyingstore.zenylimit = pl_sd->status.zeny;
+    }
+    weight = pl_sd->weight;
+
+    // check item list
+    for (i = 0; i < count; i++) {
+        // itemlist: <index>.W <name id>.W <amount>.W
+        unsigned short nameid, amount;
+        int index;
+
+        index  = RBUFW(itemlist,i*6+0)-2;
+        nameid = RBUFW(itemlist,i*6+2);
+        amount = RBUFW(itemlist,i*6+4);
+
+        if (i) {
+            // duplicate check. as the client does this too, only malicious intent should be caught here
+            ARR_FIND(0, i, k, RBUFW(itemlist,k*6+0)-2 == index);
+            if (k != i) {
+                // duplicate
+                ShowWarning("buyingstore_trade: Found duplicate item on selling list (prevnameid=%hu, prevamount=%hu, nameid=%hu, amount=%hu, account_id=%d, char_id=%d).\n",
+                            RBUFW(itemlist,k*6+2), RBUFW(itemlist,k*6+4), nameid, amount, sd->status.account_id, sd->status.char_id);
+                clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
+                return;
+            }
+        }
+
+        if (index < 0 || index >= ARRAYLENGTH(sd->status.inventory) || sd->inventory_data[index] == NULL || sd->status.inventory[index].nameid != nameid || sd->status.inventory[index].amount < amount) {
+            // invalid input
+            clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
+            return;
+        }
+
+        if (sd->status.inventory[index].expire_time || !itemdb_cantrade(&sd->status.inventory[index], pc_get_group_level(sd), pc_get_group_level(pl_sd)) || memcmp(sd->status.inventory[index].card, buyingstore_blankslots, sizeof(buyingstore_blankslots))) {
+            // non-tradable item
+            clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
+            return;
+        }
+
+        ARR_FIND(0, pl_sd->buyingstore.slots, listidx, pl_sd->buyingstore.items[listidx].nameid == nameid);
+        if (listidx == pl_sd->buyingstore.slots || pl_sd->buyingstore.items[listidx].amount == 0) {
+            // there is no such item or the buyer has already bought all of them
+            clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
+            return;
+        }
+
+        if (pl_sd->buyingstore.items[listidx].amount < amount) {
+            // buyer does not need that much of the item
+            clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_COUNT, nameid);
+            return;
+        }
+
+        if (pc_checkadditem(pl_sd, nameid, amount) == ADDITEM_OVERAMOUNT) {
+            // buyer does not have enough space for this item
+            clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
+            return;
+        }
+
+        if (amount*(unsigned int)sd->inventory_data[index]->weight > pl_sd->max_weight-weight) {
+            // normally this is not supposed to happen, as the total weight is
+            // checked upon creation, but the buyer could have gained items
+            clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid);
+            return;
+        }
+        weight+= amount*sd->inventory_data[index]->weight;
+
+        if (amount*pl_sd->buyingstore.items[listidx].price > pl_sd->buyingstore.zenylimit-zeny) {
+            // buyer does not have enough zeny
+            clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_ZENY, nameid);
+            return;
+        }
+        zeny+= amount*pl_sd->buyingstore.items[listidx].price;
+    }
+
+    // process item list
+    for (i = 0; i < count; i++) {
+        // itemlist: <index>.W <name id>.W <amount>.W
+        unsigned short nameid, amount;
+        int index;
+
+        index  = RBUFW(itemlist,i*6+0)-2;
+        nameid = RBUFW(itemlist,i*6+2);
+        amount = RBUFW(itemlist,i*6+4);
+
+        ARR_FIND(0, pl_sd->buyingstore.slots, listidx, pl_sd->buyingstore.items[listidx].nameid == nameid);
+        zeny = amount*pl_sd->buyingstore.items[listidx].price;
+
+        // move item
+        pc_additem(pl_sd, &sd->status.inventory[index], amount, LOG_TYPE_BUYING_STORE);
+        pc_delitem(sd, index, amount, 1, 0, LOG_TYPE_BUYING_STORE);
+        pl_sd->buyingstore.items[listidx].amount-= amount;
+
+        // pay up
+        pc_payzeny(pl_sd, zeny, LOG_TYPE_BUYING_STORE, sd);
+        pc_getzeny(sd, zeny, LOG_TYPE_BUYING_STORE, pl_sd);
+        pl_sd->buyingstore.zenylimit-= zeny;
+
+        // notify clients
+        clif_buyingstore_delete_item(sd, index, amount, pl_sd->buyingstore.items[listidx].price);
+        clif_buyingstore_update_item(pl_sd, nameid, amount);
+    }
+
+    // check whether or not there is still something to buy
+    ARR_FIND(0, pl_sd->buyingstore.slots, i, pl_sd->buyingstore.items[i].amount != 0);
+    if (i == pl_sd->buyingstore.slots) {
+        // everything was bought
+        clif_buyingstore_trade_failed_buyer(pl_sd, BUYINGSTORE_TRADE_BUYER_NO_ITEMS);
+    } else if (pl_sd->buyingstore.zenylimit == 0) {
+        // zeny limit reached
+        clif_buyingstore_trade_failed_buyer(pl_sd, BUYINGSTORE_TRADE_BUYER_ZENY);
+    } else {
+        // continue buying
+        return;
+    }
+
+    // cannot continue buying
+    buyingstore_close(pl_sd);
+
+    // remove auto-trader
+    if (pl_sd->state.autotrade) {
+        map_quit(pl_sd);
+    }
 }
 
 
 /// Checks if an item is being bought in given player's buying store.
-bool buyingstore_search(struct map_session_data* sd, unsigned short nameid)
+bool buyingstore_search(struct map_session_data *sd, unsigned short nameid)
 {
-	unsigned int i;
+    unsigned int i;
 
-	if( !sd->state.buyingstore )
-	{// not buying
-		return false;
-	}
+    if (!sd->state.buyingstore) {
+        // not buying
+        return false;
+    }
 
-	ARR_FIND( 0, sd->buyingstore.slots, i, sd->buyingstore.items[i].nameid == nameid && sd->buyingstore.items[i].amount );
-	if( i == sd->buyingstore.slots )
-	{// not found
-		return false;
-	}
+    ARR_FIND(0, sd->buyingstore.slots, i, sd->buyingstore.items[i].nameid == nameid && sd->buyingstore.items[i].amount);
+    if (i == sd->buyingstore.slots) {
+        // not found
+        return false;
+    }
 
-	return true;
+    return true;
 }
 
 
 /// Searches for all items in a buyingstore, that match given ids, price and possible cards.
 /// @return Whether or not the search should be continued.
-bool buyingstore_searchall(struct map_session_data* sd, const struct s_search_store_search* s)
+bool buyingstore_searchall(struct map_session_data *sd, const struct s_search_store_search *s)
 {
-	unsigned int i, idx;
-	struct s_buyingstore_item* it;
-
-	if( !sd->state.buyingstore )
-	{// not buying
-		return true;
-	}
-
-	for( idx = 0; idx < s->item_count; idx++ )
-	{
-		ARR_FIND( 0, sd->buyingstore.slots, i, sd->buyingstore.items[i].nameid == s->itemlist[idx] && sd->buyingstore.items[i].amount );
-		if( i == sd->buyingstore.slots )
-		{// not found
-			continue;
-		}
-		it = &sd->buyingstore.items[i];
-
-		if( s->min_price && s->min_price > (unsigned int)it->price )
-		{// too low price
-			continue;
-		}
-
-		if( s->max_price && s->max_price < (unsigned int)it->price )
-		{// too high price
-			continue;
-		}
-
-		if( s->card_count )
-		{// ignore cards, as there cannot be any
-			;
-		}
-
-		if( !searchstore_result(s->search_sd, sd->buyer_id, sd->status.account_id, sd->message, it->nameid, it->amount, it->price, buyingstore_blankslots, 0) )
-		{// result set full
-			return false;
-		}
-	}
-
-	return true;
+    unsigned int i, idx;
+    struct s_buyingstore_item *it;
+
+    if (!sd->state.buyingstore) {
+        // not buying
+        return true;
+    }
+
+    for (idx = 0; idx < s->item_count; idx++) {
+        ARR_FIND(0, sd->buyingstore.slots, i, sd->buyingstore.items[i].nameid == s->itemlist[idx] && sd->buyingstore.items[i].amount);
+        if (i == sd->buyingstore.slots) {
+            // not found
+            continue;
+        }
+        it = &sd->buyingstore.items[i];
+
+        if (s->min_price && s->min_price > (unsigned int)it->price) {
+            // too low price
+            continue;
+        }
+
+        if (s->max_price && s->max_price < (unsigned int)it->price) {
+            // too high price
+            continue;
+        }
+
+        if (s->card_count) {
+            // ignore cards, as there cannot be any
+            ;
+        }
+
+        if (!searchstore_result(s->search_sd, sd->buyer_id, sd->status.account_id, sd->message, it->nameid, it->amount, it->price, buyingstore_blankslots, 0)) {
+            // result set full
+            return false;
+        }
+    }
+
+    return true;
 }

+ 15 - 17
src/map/buyingstore.h

@@ -8,26 +8,24 @@ struct s_search_store_search;
 
 #define MAX_BUYINGSTORE_SLOTS 5
 
-struct s_buyingstore_item
-{
-	int price;
-	unsigned short amount;
-	unsigned short nameid;
+struct s_buyingstore_item {
+    int price;
+    unsigned short amount;
+    unsigned short nameid;
 };
 
-struct s_buyingstore
-{
-	struct s_buyingstore_item items[MAX_BUYINGSTORE_SLOTS];
-	int zenylimit;
-	unsigned char slots;
+struct s_buyingstore {
+    struct s_buyingstore_item items[MAX_BUYINGSTORE_SLOTS];
+    int zenylimit;
+    unsigned char slots;
 };
 
-bool buyingstore_setup(struct map_session_data* sd, unsigned char slots);
-void buyingstore_create(struct map_session_data* sd, int zenylimit, unsigned char result, const char* storename, const uint8* itemlist, unsigned int count);
-void buyingstore_close(struct map_session_data* sd);
-void buyingstore_open(struct map_session_data* sd, int account_id);
-void buyingstore_trade(struct map_session_data* sd, int account_id, unsigned int buyer_id, const uint8* itemlist, unsigned int count);
-bool buyingstore_search(struct map_session_data* sd, unsigned short nameid);
-bool buyingstore_searchall(struct map_session_data* sd, const struct s_search_store_search* s);
+bool buyingstore_setup(struct map_session_data *sd, unsigned char slots);
+void buyingstore_create(struct map_session_data *sd, int zenylimit, unsigned char result, const char *storename, const uint8 *itemlist, unsigned int count);
+void buyingstore_close(struct map_session_data *sd);
+void buyingstore_open(struct map_session_data *sd, int account_id);
+void buyingstore_trade(struct map_session_data *sd, int account_id, unsigned int buyer_id, const uint8 *itemlist, unsigned int count);
+bool buyingstore_search(struct map_session_data *sd, unsigned short nameid);
+bool buyingstore_searchall(struct map_session_data *sd, const struct s_search_store_search *s);
 
 #endif  // _BUYINGSTORE_H_

+ 280 - 290
src/map/chat.c

@@ -24,144 +24,136 @@ int chat_triggerevent(struct chat_data *cd); // forward declaration
 
 /// Initializes a chatroom object (common functionality for both pc and npc chatrooms).
 /// Returns a chatroom object on success, or NULL on failure.
-static struct chat_data* chat_createchat(struct block_list* bl, const char* title, const char* pass, int limit, bool pub, int trigger, const char* ev, int zeny, int minLvl, int maxLvl)
-{
-	struct chat_data* cd;
-	nullpo_retr(NULL, bl);
-
-	cd = (struct chat_data *) aMalloc(sizeof(struct chat_data));
-
-	safestrncpy(cd->title, title, sizeof(cd->title));
-	safestrncpy(cd->pass, pass, sizeof(cd->pass));
-	cd->pub = pub;
-	cd->users = 0;
-	cd->limit = min(limit, ARRAYLENGTH(cd->usersd));
-	cd->trigger = trigger;
-	cd->zeny = zeny;
-	cd->minLvl = minLvl;
-	cd->maxLvl = maxLvl;
-	memset(cd->usersd, 0, sizeof(cd->usersd));
-	cd->owner = bl;
-	safestrncpy(cd->npc_event, ev, sizeof(cd->npc_event));
-
-	cd->bl.id   = map_get_new_object_id();
-	cd->bl.m    = bl->m;
-	cd->bl.x    = bl->x;
-	cd->bl.y    = bl->y;
-	cd->bl.type = BL_CHAT;
-	cd->bl.next = cd->bl.prev = NULL;
-
-	if( cd->bl.id == 0 )
-	{
-		aFree(cd);
-		cd = NULL;
-	}
-
-	map_addiddb(&cd->bl);
-
-	if( bl->type != BL_NPC )
-		cd->kick_list = idb_alloc(DB_OPT_BASE);
-	
-	return cd;
+static struct chat_data *chat_createchat(struct block_list *bl, const char *title, const char *pass, int limit, bool pub, int trigger, const char *ev, int zeny, int minLvl, int maxLvl) {
+    struct chat_data *cd;
+    nullpo_retr(NULL, bl);
+
+    cd = (struct chat_data *) aMalloc(sizeof(struct chat_data));
+
+    safestrncpy(cd->title, title, sizeof(cd->title));
+    safestrncpy(cd->pass, pass, sizeof(cd->pass));
+    cd->pub = pub;
+    cd->users = 0;
+    cd->limit = min(limit, ARRAYLENGTH(cd->usersd));
+    cd->trigger = trigger;
+    cd->zeny = zeny;
+    cd->minLvl = minLvl;
+    cd->maxLvl = maxLvl;
+    memset(cd->usersd, 0, sizeof(cd->usersd));
+    cd->owner = bl;
+    safestrncpy(cd->npc_event, ev, sizeof(cd->npc_event));
+
+    cd->bl.id   = map_get_new_object_id();
+    cd->bl.m    = bl->m;
+    cd->bl.x    = bl->x;
+    cd->bl.y    = bl->y;
+    cd->bl.type = BL_CHAT;
+    cd->bl.next = cd->bl.prev = NULL;
+
+    if (cd->bl.id == 0) {
+        aFree(cd);
+        cd = NULL;
+    }
+
+    map_addiddb(&cd->bl);
+
+    if (bl->type != BL_NPC)
+        cd->kick_list = idb_alloc(DB_OPT_BASE);
+
+    return cd;
 }
 
 /*==========================================
  * player chatroom creation
  *------------------------------------------*/
-int chat_createpcchat(struct map_session_data* sd, const char* title, const char* pass, int limit, bool pub)
+int chat_createpcchat(struct map_session_data *sd, const char *title, const char *pass, int limit, bool pub)
 {
-	struct chat_data* cd;
-	nullpo_ret(sd);
-
-	if( sd->chatID )
-		return 0; //Prevent people abusing the chat system by creating multiple chats, as pointed out by End of Exam. [Skotlex]
-
-	if( sd->state.vending || sd->state.buyingstore )
-	{// not chat, when you already have a store open
-		return 0;
-	}
-
-	if( map[sd->bl.m].flag.nochat )
-	{
-		clif_displaymessage(sd->fd, msg_txt(281));
-		return 0; //Can't create chatrooms on this map.
-	}
-
-	if( map_getcell(sd->bl.m,sd->bl.x,sd->bl.y,CELL_CHKNOCHAT) )
-	{
-		clif_displaymessage (sd->fd, msg_txt(665));
-		return 0;
-	}
-
-	pc_stop_walking(sd,1);
-
-	cd = chat_createchat(&sd->bl, title, pass, limit, pub, 0, "", 0, 1, MAX_LEVEL);
-	if( cd )
-	{
-		cd->users = 1;
-		cd->usersd[0] = sd;
-		pc_setchatid(sd,cd->bl.id);
-		clif_createchat(sd,0);
-		clif_dispchat(cd,0);
-	}
-	else
-		clif_createchat(sd,1);
-
-	return 0;
+    struct chat_data *cd;
+    nullpo_ret(sd);
+
+    if (sd->chatID)
+        return 0; //Prevent people abusing the chat system by creating multiple chats, as pointed out by End of Exam. [Skotlex]
+
+    if (sd->state.vending || sd->state.buyingstore) {
+        // not chat, when you already have a store open
+        return 0;
+    }
+
+    if (map[sd->bl.m].flag.nochat) {
+        clif_displaymessage(sd->fd, msg_txt(281));
+        return 0; //Can't create chatrooms on this map.
+    }
+
+    if (map_getcell(sd->bl.m,sd->bl.x,sd->bl.y,CELL_CHKNOCHAT)) {
+        clif_displaymessage(sd->fd, msg_txt(665));
+        return 0;
+    }
+
+    pc_stop_walking(sd,1);
+
+    cd = chat_createchat(&sd->bl, title, pass, limit, pub, 0, "", 0, 1, MAX_LEVEL);
+    if (cd) {
+        cd->users = 1;
+        cd->usersd[0] = sd;
+        pc_setchatid(sd,cd->bl.id);
+        clif_createchat(sd,0);
+        clif_dispchat(cd,0);
+    } else
+        clif_createchat(sd,1);
+
+    return 0;
 }
 
 /*==========================================
  * join an existing chatroom
  *------------------------------------------*/
-int chat_joinchat(struct map_session_data* sd, int chatid, const char* pass)
+int chat_joinchat(struct map_session_data *sd, int chatid, const char *pass)
 {
-	struct chat_data* cd;
+    struct chat_data *cd;
 
-	nullpo_ret(sd);
-	cd = (struct chat_data*)map_id2bl(chatid);
+    nullpo_ret(sd);
+    cd = (struct chat_data *)map_id2bl(chatid);
 
-	if( cd == NULL || cd->bl.type != BL_CHAT || cd->bl.m != sd->bl.m || sd->state.vending || sd->state.buyingstore || sd->chatID || ((cd->owner->type == BL_NPC) ? cd->users+1 : cd->users) >= cd->limit )
-	{
-		clif_joinchatfail(sd,0);
-		return 0;
-	}
+    if (cd == NULL || cd->bl.type != BL_CHAT || cd->bl.m != sd->bl.m || sd->state.vending || sd->state.buyingstore || sd->chatID || ((cd->owner->type == BL_NPC) ? cd->users+1 : cd->users) >= cd->limit) {
+        clif_joinchatfail(sd,0);
+        return 0;
+    }
 
-	if( !cd->pub && strncmp(pass, cd->pass, sizeof(cd->pass)) != 0 && !pc_has_permission(sd, PC_PERM_JOIN_ALL_CHAT) )
-	{
-		clif_joinchatfail(sd,1);
-		return 0;
-	}
+    if (!cd->pub && strncmp(pass, cd->pass, sizeof(cd->pass)) != 0 && !pc_has_permission(sd, PC_PERM_JOIN_ALL_CHAT)) {
+        clif_joinchatfail(sd,1);
+        return 0;
+    }
 
-	if( sd->status.base_level < cd->minLvl || sd->status.base_level > cd->maxLvl ) {
-		if(sd->status.base_level < cd->minLvl)
-			clif_joinchatfail(sd,5);
-		else
-			clif_joinchatfail(sd,6);
+    if (sd->status.base_level < cd->minLvl || sd->status.base_level > cd->maxLvl) {
+        if (sd->status.base_level < cd->minLvl)
+            clif_joinchatfail(sd,5);
+        else
+            clif_joinchatfail(sd,6);
 
-		return 0;
-	}
+        return 0;
+    }
 
-	if( sd->status.zeny < cd->zeny ) {
-		clif_joinchatfail(sd,4);
-		return 0;
-	}
+    if (sd->status.zeny < cd->zeny) {
+        clif_joinchatfail(sd,4);
+        return 0;
+    }
 
-	if( cd->owner->type != BL_NPC && idb_exists(cd->kick_list,sd->status.char_id) ) {
-		clif_joinchatfail(sd,2);//You have been kicked out of the room.
-		return 0;
-	}
+    if (cd->owner->type != BL_NPC && idb_exists(cd->kick_list,sd->status.char_id)) {
+        clif_joinchatfail(sd,2);//You have been kicked out of the room.
+        return 0;
+    }
 
-	pc_stop_walking(sd,1);
-	cd->usersd[cd->users] = sd;
-	cd->users++;
+    pc_stop_walking(sd,1);
+    cd->usersd[cd->users] = sd;
+    cd->users++;
 
-	pc_setchatid(sd,cd->bl.id);
+    pc_setchatid(sd,cd->bl.id);
 
     clif_joinchatok(sd, cd); //To the person who newly joined the list of all
-    clif_addchat(cd, sd); //Reports To the person who already in the chat 
-    clif_dispchat(cd, 0); //Reported number of changes to the people around 
+    clif_addchat(cd, sd); //Reports To the person who already in the chat
+    clif_dispchat(cd, 0); //Reported number of changes to the people around
 
-    chat_triggerevent(cd); //Event 
+    chat_triggerevent(cd); //Event
 
     return 0;
 }
@@ -170,215 +162,213 @@ int chat_joinchat(struct map_session_data* sd, int chatid, const char* pass)
 /*==========================================
  * leave a chatroom
  *------------------------------------------*/
-int chat_leavechat(struct map_session_data* sd, bool kicked)
+int chat_leavechat(struct map_session_data *sd, bool kicked)
 {
-	struct chat_data* cd;
-	int i;
-	int leavechar;
-
-	nullpo_retr(1, sd);
-
-	cd = (struct chat_data*)map_id2bl(sd->chatID);
-	if( cd == NULL )
-	{
-		pc_setchatid(sd, 0);
-		return 1;
-	}
-
-	ARR_FIND( 0, cd->users, i, cd->usersd[i] == sd );
-	if ( i == cd->users )
-	{	// Not found in the chatroom?
-		pc_setchatid(sd, 0);
-		return -1;
-	}
-
-	clif_leavechat(cd, sd, kicked);
-	pc_setchatid(sd, 0);
-	cd->users--;
-
-	leavechar = i;
-
-	for( i = leavechar; i < cd->users; i++ )
-		cd->usersd[i] = cd->usersd[i+1];
-
-
-	if( cd->users == 0 && cd->owner->type == BL_PC ) { // Delete empty chatroom
-		struct skill_unit* unit = NULL;
-		struct skill_unit_group* group = NULL;	
-
-		clif_clearchat(cd, 0);
-		db_destroy(cd->kick_list);
-		map_deliddb(&cd->bl);
-		map_delblock(&cd->bl);
-		map_freeblock(&cd->bl);
-		
-		unit = map_find_skill_unit_oncell(&sd->bl, sd->bl.x, sd->bl.y, AL_WARP, NULL, 0);
-		group = (unit != NULL) ? unit->group : NULL;
-		if (group != NULL)
-			ext_skill_unit_onplace(unit, &sd->bl, group->tick);
-
-		return 1;
-	}
-
-	if( leavechar == 0 && cd->owner->type == BL_PC )
-	{	// Set and announce new owner
-		cd->owner = (struct block_list*) cd->usersd[0];
-		clif_changechatowner(cd, cd->usersd[0]);
-		clif_clearchat(cd, 0);
-
-		//Adjust Chat location after owner has been changed.
-		map_delblock( &cd->bl );
-		cd->bl.x=cd->usersd[0]->bl.x;
-		cd->bl.y=cd->usersd[0]->bl.y;
-		map_addblock( &cd->bl );
-
-		clif_dispchat(cd,0);
-	}
-	else
-		clif_dispchat(cd,0); // refresh chatroom
-
-	return 0;
+    struct chat_data *cd;
+    int i;
+    int leavechar;
+
+    nullpo_retr(1, sd);
+
+    cd = (struct chat_data *)map_id2bl(sd->chatID);
+    if (cd == NULL) {
+        pc_setchatid(sd, 0);
+        return 1;
+    }
+
+    ARR_FIND(0, cd->users, i, cd->usersd[i] == sd);
+    if (i == cd->users) {
+        // Not found in the chatroom?
+        pc_setchatid(sd, 0);
+        return -1;
+    }
+
+    clif_leavechat(cd, sd, kicked);
+    pc_setchatid(sd, 0);
+    cd->users--;
+
+    leavechar = i;
+
+    for (i = leavechar; i < cd->users; i++)
+        cd->usersd[i] = cd->usersd[i+1];
+
+
+    if (cd->users == 0 && cd->owner->type == BL_PC) {  // Delete empty chatroom
+        struct skill_unit *unit = NULL;
+        struct skill_unit_group *group = NULL;
+
+        clif_clearchat(cd, 0);
+        db_destroy(cd->kick_list);
+        map_deliddb(&cd->bl);
+        map_delblock(&cd->bl);
+        map_freeblock(&cd->bl);
+
+        unit = map_find_skill_unit_oncell(&sd->bl, sd->bl.x, sd->bl.y, AL_WARP, NULL, 0);
+        group = (unit != NULL) ? unit->group : NULL;
+        if (group != NULL)
+            ext_skill_unit_onplace(unit, &sd->bl, group->tick);
+
+        return 1;
+    }
+
+    if (leavechar == 0 && cd->owner->type == BL_PC) {
+        // Set and announce new owner
+        cd->owner = (struct block_list *) cd->usersd[0];
+        clif_changechatowner(cd, cd->usersd[0]);
+        clif_clearchat(cd, 0);
+
+        //Adjust Chat location after owner has been changed.
+        map_delblock(&cd->bl);
+        cd->bl.x=cd->usersd[0]->bl.x;
+        cd->bl.y=cd->usersd[0]->bl.y;
+        map_addblock(&cd->bl);
+
+        clif_dispchat(cd,0);
+    } else
+        clif_dispchat(cd,0); // refresh chatroom
+
+    return 0;
 }
 
 /*==========================================
  * change a chatroom's owner
  *------------------------------------------*/
-int chat_changechatowner(struct map_session_data* sd, const char* nextownername)
+int chat_changechatowner(struct map_session_data *sd, const char *nextownername)
 {
-	struct chat_data* cd;
-	struct map_session_data* tmpsd;
-	int i;
+    struct chat_data *cd;
+    struct map_session_data *tmpsd;
+    int i;
 
-	nullpo_retr(1, sd);
+    nullpo_retr(1, sd);
 
-	cd = (struct chat_data*)map_id2bl(sd->chatID);
-	if( cd == NULL || (struct block_list*) sd != cd->owner )
-		return 1;
+    cd = (struct chat_data *)map_id2bl(sd->chatID);
+    if (cd == NULL || (struct block_list *) sd != cd->owner)
+        return 1;
 
-	ARR_FIND( 1, cd->users, i, strncmp(cd->usersd[i]->status.name, nextownername, NAME_LENGTH) == 0 );
-	if( i == cd->users )
-		return -1;  // name not found
+    ARR_FIND(1, cd->users, i, strncmp(cd->usersd[i]->status.name, nextownername, NAME_LENGTH) == 0);
+    if (i == cd->users)
+        return -1;  // name not found
 
-	// erase temporarily
-	clif_clearchat(cd,0);
+    // erase temporarily
+    clif_clearchat(cd,0);
 
-	// set new owner
-	cd->owner = (struct block_list*) cd->usersd[i];
-	clif_changechatowner(cd,cd->usersd[i]);
+    // set new owner
+    cd->owner = (struct block_list *) cd->usersd[i];
+    clif_changechatowner(cd,cd->usersd[i]);
 
-	// swap the old and new owners' positions
-	tmpsd = cd->usersd[i];
-	cd->usersd[i] = cd->usersd[0];
-	cd->usersd[0] = tmpsd;
+    // swap the old and new owners' positions
+    tmpsd = cd->usersd[i];
+    cd->usersd[i] = cd->usersd[0];
+    cd->usersd[0] = tmpsd;
 
-	// set the new chatroom position
-	map_delblock( &cd->bl );
-	cd->bl.x = cd->owner->x;
-	cd->bl.y = cd->owner->y;
-	map_addblock( &cd->bl );
+    // set the new chatroom position
+    map_delblock(&cd->bl);
+    cd->bl.x = cd->owner->x;
+    cd->bl.y = cd->owner->y;
+    map_addblock(&cd->bl);
 
-	// and display again
-	clif_dispchat(cd,0);
+    // and display again
+    clif_dispchat(cd,0);
 
-	return 0;
+    return 0;
 }
 
 /*==========================================
  * change a chatroom's status (title, etc)
  *------------------------------------------*/
-int chat_changechatstatus(struct map_session_data* sd, const char* title, const char* pass, int limit, bool pub)
+int chat_changechatstatus(struct map_session_data *sd, const char *title, const char *pass, int limit, bool pub)
 {
-	struct chat_data* cd;
+    struct chat_data *cd;
 
-	nullpo_retr(1, sd);
+    nullpo_retr(1, sd);
 
-	cd = (struct chat_data*)map_id2bl(sd->chatID);
-	if( cd==NULL || (struct block_list *)sd != cd->owner )
-		return 1;
+    cd = (struct chat_data *)map_id2bl(sd->chatID);
+    if (cd==NULL || (struct block_list *)sd != cd->owner)
+        return 1;
 
-	safestrncpy(cd->title, title, CHATROOM_TITLE_SIZE);
-	safestrncpy(cd->pass, pass, CHATROOM_PASS_SIZE);
-	cd->limit = min(limit, ARRAYLENGTH(cd->usersd));
-	cd->pub = pub;
+    safestrncpy(cd->title, title, CHATROOM_TITLE_SIZE);
+    safestrncpy(cd->pass, pass, CHATROOM_PASS_SIZE);
+    cd->limit = min(limit, ARRAYLENGTH(cd->usersd));
+    cd->pub = pub;
 
-	clif_changechatstatus(cd);
-	clif_dispchat(cd,0);
+    clif_changechatstatus(cd);
+    clif_dispchat(cd,0);
 
-	return 0;
+    return 0;
 }
 
 /*==========================================
  * kick an user from a chatroom
  *------------------------------------------*/
-int chat_kickchat(struct map_session_data* sd, const char* kickusername)
+int chat_kickchat(struct map_session_data *sd, const char *kickusername)
 {
-	struct chat_data* cd;
-	int i;
+    struct chat_data *cd;
+    int i;
 
-	nullpo_retr(1, sd);
+    nullpo_retr(1, sd);
 
-	cd = (struct chat_data *)map_id2bl(sd->chatID);
-	
-	if( cd==NULL || (struct block_list *)sd != cd->owner )
-		return -1;
+    cd = (struct chat_data *)map_id2bl(sd->chatID);
 
-	ARR_FIND( 0, cd->users, i, strncmp(cd->usersd[i]->status.name, kickusername, NAME_LENGTH) == 0 );
-	if( i == cd->users )
-		return -1;
+    if (cd==NULL || (struct block_list *)sd != cd->owner)
+        return -1;
 
-	if (pc_has_permission(cd->usersd[i], PC_PERM_NO_CHAT_KICK))
-		return 0; //gm kick protection [Valaris]
-	
-	idb_put(cd->kick_list,cd->usersd[i]->status.char_id,(void*)1);
+    ARR_FIND(0, cd->users, i, strncmp(cd->usersd[i]->status.name, kickusername, NAME_LENGTH) == 0);
+    if (i == cd->users)
+        return -1;
 
-	chat_leavechat(cd->usersd[i],1);
-	return 0;
+    if (pc_has_permission(cd->usersd[i], PC_PERM_NO_CHAT_KICK))
+        return 0; //gm kick protection [Valaris]
+
+    idb_put(cd->kick_list,cd->usersd[i]->status.char_id,(void *)1);
+
+    chat_leavechat(cd->usersd[i],1);
+    return 0;
 }
 
 /// Creates a chat room for the npc.
-int chat_createnpcchat(struct npc_data* nd, const char* title, int limit, bool pub, int trigger, const char* ev, int zeny, int minLvl, int maxLvl)
+int chat_createnpcchat(struct npc_data *nd, const char *title, int limit, bool pub, int trigger, const char *ev, int zeny, int minLvl, int maxLvl)
 {
-	struct chat_data* cd;
-	nullpo_ret(nd);
+    struct chat_data *cd;
+    nullpo_ret(nd);
 
-	if( nd->chat_id ) {
-		ShowError("chat_createnpcchat: npc '%s' already has a chatroom, cannot create new one!\n", nd->exname);
-		return 0;
-	}
+    if (nd->chat_id) {
+        ShowError("chat_createnpcchat: npc '%s' already has a chatroom, cannot create new one!\n", nd->exname);
+        return 0;
+    }
 
-	if( zeny > MAX_ZENY || maxLvl > MAX_LEVEL ) {
-		ShowError("chat_createnpcchat: npc '%s' has a required lvl or amount of zeny over the max limit!\n", nd->exname);
-		return 0;
-	}
+    if (zeny > MAX_ZENY || maxLvl > MAX_LEVEL) {
+        ShowError("chat_createnpcchat: npc '%s' has a required lvl or amount of zeny over the max limit!\n", nd->exname);
+        return 0;
+    }
 
-	cd = chat_createchat(&nd->bl, title, "", limit, pub, trigger, ev, zeny, minLvl, maxLvl);
+    cd = chat_createchat(&nd->bl, title, "", limit, pub, trigger, ev, zeny, minLvl, maxLvl);
 
-	if( cd ) {
-		nd->chat_id = cd->bl.id;
-		clif_dispchat(cd,0);
-	}
+    if (cd) {
+        nd->chat_id = cd->bl.id;
+        clif_dispchat(cd,0);
+    }
 
-	return 0;
+    return 0;
 }
 
 /// Removes the chatroom from the npc.
-int chat_deletenpcchat(struct npc_data* nd)
+int chat_deletenpcchat(struct npc_data *nd)
 {
-	struct chat_data *cd;
-	nullpo_ret(nd);
-
-	cd = (struct chat_data*)map_id2bl(nd->chat_id);
-	if( cd == NULL )
-		return 0;
-	
-	chat_npckickall(cd);
-	clif_clearchat(cd, 0);
-	map_deliddb(&cd->bl);
-	map_delblock(&cd->bl);
-	map_freeblock(&cd->bl);
-	nd->chat_id = 0;
-	
-	return 0;
+    struct chat_data *cd;
+    nullpo_ret(nd);
+
+    cd = (struct chat_data *)map_id2bl(nd->chat_id);
+    if (cd == NULL)
+        return 0;
+
+    chat_npckickall(cd);
+    clif_clearchat(cd, 0);
+    map_deliddb(&cd->bl);
+    map_delblock(&cd->bl);
+    map_freeblock(&cd->bl);
+    nd->chat_id = 0;
+
+    return 0;
 }
 
 /*==========================================
@@ -386,40 +376,40 @@ int chat_deletenpcchat(struct npc_data* nd)
  *------------------------------------------*/
 int chat_triggerevent(struct chat_data *cd)
 {
-	nullpo_ret(cd);
+    nullpo_ret(cd);
 
-	if( cd->users >= cd->trigger && cd->npc_event[0] )
-		npc_event_do(cd->npc_event);
-	return 0;
+    if (cd->users >= cd->trigger && cd->npc_event[0])
+        npc_event_do(cd->npc_event);
+    return 0;
 }
 
 /// Enables the event of the chat room.
 /// At most, 127 users are needed to trigger the event.
-int chat_enableevent(struct chat_data* cd)
+int chat_enableevent(struct chat_data *cd)
 {
-	nullpo_ret(cd);
+    nullpo_ret(cd);
 
-	cd->trigger &= 0x7f;
-	chat_triggerevent(cd);
-	return 0;
+    cd->trigger &= 0x7f;
+    chat_triggerevent(cd);
+    return 0;
 }
 
 /// Disables the event of the chat room
-int chat_disableevent(struct chat_data* cd)
+int chat_disableevent(struct chat_data *cd)
 {
-	nullpo_ret(cd);
+    nullpo_ret(cd);
 
-	cd->trigger |= 0x80;
-	return 0;
+    cd->trigger |= 0x80;
+    return 0;
 }
 
 /// Kicks all the users from the chat room.
-int chat_npckickall(struct chat_data* cd)
+int chat_npckickall(struct chat_data *cd)
 {
-	nullpo_ret(cd);
+    nullpo_ret(cd);
 
-	while( cd->users > 0 )
-		chat_leavechat(cd->usersd[cd->users-1],0);
+    while (cd->users > 0)
+        chat_leavechat(cd->usersd[cd->users-1],0);
 
-	return 0;
+    return 0;
 }

+ 25 - 25
src/map/chat.h

@@ -10,34 +10,34 @@ struct chat_data;
 
 
 struct chat_data {
-	struct block_list bl;            // data for this map object
-	char title[CHATROOM_TITLE_SIZE]; // room title 
-	char pass[CHATROOM_PASS_SIZE];   // password
-	bool pub;                        // private/public flag
-	uint8 users;                     // current user count
-	uint8 limit;                     // join limit
-	uint8 trigger;                   // number of users needed to trigger event
-	uint32 zeny;						 // required zeny to join
-	uint32 minLvl;					 // minimum base level to join
-	uint32 maxLvl;					 // maximum base level allowed to join
-	struct map_session_data* usersd[20];
-	struct block_list* owner;
-	char npc_event[EVENT_NAME_LENGTH];
-	DBMap* kick_list;				//DBMap of users who were kicked from this chat
+    struct block_list bl;            // data for this map object
+    char title[CHATROOM_TITLE_SIZE]; // room title
+    char pass[CHATROOM_PASS_SIZE];   // password
+    bool pub;                        // private/public flag
+    uint8 users;                     // current user count
+    uint8 limit;                     // join limit
+    uint8 trigger;                   // number of users needed to trigger event
+    uint32 zeny;                         // required zeny to join
+    uint32 minLvl;                   // minimum base level to join
+    uint32 maxLvl;                   // maximum base level allowed to join
+    struct map_session_data *usersd[20];
+    struct block_list *owner;
+    char npc_event[EVENT_NAME_LENGTH];
+    DBMap *kick_list;               //DBMap of users who were kicked from this chat
 };
 
 
-int chat_createpcchat(struct map_session_data* sd, const char* title, const char* pass, int limit, bool pub);
-int chat_joinchat(struct map_session_data* sd, int chatid, const char* pass);
-int chat_leavechat(struct map_session_data* sd, bool kicked);
-int chat_changechatowner(struct map_session_data* sd, const char* nextownername);
-int chat_changechatstatus(struct map_session_data* sd, const char* title, const char* pass, int limit, bool pub);
-int chat_kickchat(struct map_session_data* sd, const char* kickusername);
+int chat_createpcchat(struct map_session_data *sd, const char *title, const char *pass, int limit, bool pub);
+int chat_joinchat(struct map_session_data *sd, int chatid, const char *pass);
+int chat_leavechat(struct map_session_data *sd, bool kicked);
+int chat_changechatowner(struct map_session_data *sd, const char *nextownername);
+int chat_changechatstatus(struct map_session_data *sd, const char *title, const char *pass, int limit, bool pub);
+int chat_kickchat(struct map_session_data *sd, const char *kickusername);
 
-int chat_createnpcchat(struct npc_data* nd, const char* title, int limit, bool pub, int trigger, const char* ev, int zeny, int minLvl, int maxLvl);
-int chat_deletenpcchat(struct npc_data* nd);
-int chat_enableevent(struct chat_data* cd);
-int chat_disableevent(struct chat_data* cd);
-int chat_npckickall(struct chat_data* cd);
+int chat_createnpcchat(struct npc_data *nd, const char *title, int limit, bool pub, int trigger, const char *ev, int zeny, int minLvl, int maxLvl);
+int chat_deletenpcchat(struct npc_data *nd);
+int chat_enableevent(struct chat_data *cd);
+int chat_disableevent(struct chat_data *cd);
+int chat_npckickall(struct chat_data *cd);
 
 #endif /* _CHAT_H_ */

File diff suppressed because it is too large
+ 480 - 452
src/map/chrif.c


+ 19 - 19
src/map/chrif.h

@@ -9,19 +9,19 @@
 
 enum sd_state { ST_LOGIN, ST_LOGOUT, ST_MAPCHANGE };
 struct auth_node {
-	int account_id, char_id;
-	int login_id1, login_id2, sex, fd;
-	time_t expiration_time; // # of seconds 1/1/1970 (timestamp): Validity limit of the account (0 = unlimited)
-	struct map_session_data *sd;	//Data from logged on char.
-	struct mmo_charstatus *char_dat;	//Data from char server.
-	unsigned int node_created; //timestamp for node timeouts
-	enum sd_state state; //To track whether player was login in/out or changing maps.
+    int account_id, char_id;
+    int login_id1, login_id2, sex, fd;
+    time_t expiration_time; // # of seconds 1/1/1970 (timestamp): Validity limit of the account (0 = unlimited)
+    struct map_session_data *sd;    //Data from logged on char.
+    struct mmo_charstatus *char_dat;    //Data from char server.
+    unsigned int node_created; //timestamp for node timeouts
+    enum sd_state state; //To track whether player was login in/out or changing maps.
 };
 
-void chrif_setuserid(char* id);
-void chrif_setpasswd(char* pwd);
+void chrif_setuserid(char *id);
+void chrif_setpasswd(char *pwd);
 void chrif_checkdefaultlogin(void);
-int chrif_setip(const char* ip);
+int chrif_setip(const char *ip);
 void chrif_setport(uint16 port);
 
 int chrif_isconnected(void);
@@ -30,21 +30,21 @@ void chrif_check_shutdown(void);
 extern int chrif_connected;
 extern int other_mapserver_count;
 
-struct auth_node* chrif_search(int account_id);
-struct auth_node* chrif_auth_check(int account_id, int char_id, enum sd_state state);
+struct auth_node *chrif_search(int account_id);
+struct auth_node *chrif_auth_check(int account_id, int char_id, enum sd_state state);
 bool chrif_auth_delete(int account_id, int char_id, enum sd_state state);
-bool chrif_auth_finished(struct map_session_data* sd);
+bool chrif_auth_finished(struct map_session_data *sd);
 
-void chrif_authreq(struct map_session_data* sd);
+void chrif_authreq(struct map_session_data *sd);
 void chrif_authok(int fd);
 int chrif_scdata_request(int account_id, int char_id);
-int chrif_save(struct map_session_data* sd, int flag);
-int chrif_charselectreq(struct map_session_data* sd, uint32 s_ip);
-int chrif_changemapserver(struct map_session_data* sd, uint32 ip, uint16 port);
+int chrif_save(struct map_session_data *sd, int flag);
+int chrif_charselectreq(struct map_session_data *sd, uint32 s_ip);
+int chrif_changemapserver(struct map_session_data *sd, uint32 ip, uint16 port);
 
 int chrif_searchcharid(int char_id);
 int chrif_changeemail(int id, const char *actual_email, const char *new_email);
-int chrif_char_ask_name(int acc, const char* character_name, unsigned short operation_type, int year, int month, int day, int hour, int minute, int second);
+int chrif_char_ask_name(int acc, const char *character_name, unsigned short operation_type, int year, int month, int day, int hour, int minute, int second);
 int chrif_updatefamelist(struct map_session_data *sd);
 int chrif_buildfamelist(void);
 int chrif_save_scdata(struct map_session_data *sd);
@@ -59,7 +59,7 @@ int chrif_chardisconnect(struct map_session_data *sd);
 int chrif_divorce(int partner_id1, int partner_id2);
 
 int chrif_removefriend(int char_id, int friend_id);
-void chrif_send_report(char* buf, int len);
+void chrif_send_report(char *buf, int len);
 
 int do_final_chrif(void);
 int do_init_chrif(void);

File diff suppressed because it is too large
+ 442 - 444
src/map/clif.c


File diff suppressed because it is too large
+ 413 - 415
src/map/clif.h


+ 33 - 33
src/map/date.c

@@ -6,66 +6,66 @@
 
 int date_get_year(void)
 {
-	time_t t;
-	struct tm * lt;
-	t = time(NULL);
-	lt = localtime(&t);
-	return lt->tm_year+1900;
+    time_t t;
+    struct tm *lt;
+    t = time(NULL);
+    lt = localtime(&t);
+    return lt->tm_year+1900;
 }
 int date_get_month(void)
 {
-	time_t t;
-	struct tm * lt;
-	t = time(NULL);
-	lt = localtime(&t);
-	return lt->tm_mon+1;
+    time_t t;
+    struct tm *lt;
+    t = time(NULL);
+    lt = localtime(&t);
+    return lt->tm_mon+1;
 }
 int date_get_day(void)
 {
-	time_t t;
-	struct tm * lt;
-	t = time(NULL);
-	lt = localtime(&t);
-	return lt->tm_mday;
+    time_t t;
+    struct tm *lt;
+    t = time(NULL);
+    lt = localtime(&t);
+    return lt->tm_mday;
 }
 int date_get_hour(void)
 {
-	time_t t;
-	struct tm * lt;
-	t = time(NULL);
-	lt = localtime(&t);
-	return lt->tm_hour;
+    time_t t;
+    struct tm *lt;
+    t = time(NULL);
+    lt = localtime(&t);
+    return lt->tm_hour;
 }
 
 int date_get_min(void)
 {
-	time_t t;
-	struct tm * lt;
-	t = time(NULL);
-	lt = localtime(&t);
-	return lt->tm_min;
+    time_t t;
+    struct tm *lt;
+    t = time(NULL);
+    lt = localtime(&t);
+    return lt->tm_min;
 }
 
 int date_get_sec(void)
 {
-	time_t t;
-	struct tm * lt;
-	t = time(NULL);
-	lt = localtime(&t);
-	return lt->tm_sec;
+    time_t t;
+    struct tm *lt;
+    t = time(NULL);
+    lt = localtime(&t);
+    return lt->tm_sec;
 }
 
 int is_day_of_sun(void)
 {
-	return date_get_day()%2 == 0;
+    return date_get_day()%2 == 0;
 }
 
 int is_day_of_moon(void)
 {
-	return date_get_day()%2 == 1;
+    return date_get_day()%2 == 1;
 }
 
 int is_day_of_star(void)
 {
-	return date_get_day()%5 == 0;
+    return date_get_day()%5 == 0;
 }

+ 124 - 124
src/map/duel.c

@@ -19,157 +19,157 @@ int duel_count = 0;
 /*==========================================
  * Duel organizing functions [LuzZza]
  *------------------------------------------*/
-void duel_savetime(struct map_session_data* sd)
+void duel_savetime(struct map_session_data *sd)
 {
-	time_t timer;
-	struct tm *t;
-	
-	time(&timer);
-	t = localtime(&timer);
-	
-	pc_setglobalreg(sd, "PC_LAST_DUEL_TIME", t->tm_mday*24*60 + t->tm_hour*60 + t->tm_min);
+    time_t timer;
+    struct tm *t;
+
+    time(&timer);
+    t = localtime(&timer);
+
+    pc_setglobalreg(sd, "PC_LAST_DUEL_TIME", t->tm_mday*24*60 + t->tm_hour*60 + t->tm_min);
 }
 
-int duel_checktime(struct map_session_data* sd)
+int duel_checktime(struct map_session_data *sd)
 {
-	int diff;
-	time_t timer;
-	struct tm *t;
-	
-	time(&timer);
+    int diff;
+    time_t timer;
+    struct tm *t;
+
+    time(&timer);
     t = localtime(&timer);
-	
-	diff = t->tm_mday*24*60 + t->tm_hour*60 + t->tm_min - pc_readglobalreg(sd, "PC_LAST_DUEL_TIME");
-	
-	return !(diff >= 0 && diff < battle_config.duel_time_interval);
+
+    diff = t->tm_mday*24*60 + t->tm_hour*60 + t->tm_min - pc_readglobalreg(sd, "PC_LAST_DUEL_TIME");
+
+    return !(diff >= 0 && diff < battle_config.duel_time_interval);
 }
-static int duel_showinfo_sub(struct map_session_data* sd, va_list va)
+static int duel_showinfo_sub(struct map_session_data *sd, va_list va)
 {
-	struct map_session_data *ssd = va_arg(va, struct map_session_data*);
-	int *p = va_arg(va, int*);
-	char output[256];
-
-	if (sd->duel_group != ssd->duel_group) return 0;
-	
-	sprintf(output, "      %d. %s", ++(*p), sd->status.name);
-	clif_disp_onlyself(ssd, output, strlen(output));
-	return 1;
+    struct map_session_data *ssd = va_arg(va, struct map_session_data *);
+    int *p = va_arg(va, int *);
+    char output[256];
+
+    if (sd->duel_group != ssd->duel_group) return 0;
+
+    sprintf(output, "      %d. %s", ++(*p), sd->status.name);
+    clif_disp_onlyself(ssd, output, strlen(output));
+    return 1;
 }
 
-void duel_showinfo(const unsigned int did, struct map_session_data* sd)
+void duel_showinfo(const unsigned int did, struct map_session_data *sd)
 {
-	int p=0;
-	char output[256];
-
-	if(duel_list[did].max_players_limit > 0)
-		sprintf(output, msg_txt(370), //" -- Duels: %d/%d, Members: %d/%d, Max players: %d --"
-			did, duel_count,
-			duel_list[did].members_count,
-			duel_list[did].members_count + duel_list[did].invites_count,
-			duel_list[did].max_players_limit);
-	else
-		sprintf(output, msg_txt(371), //" -- Duels: %d/%d, Members: %d/%d --"
-			did, duel_count,
-			duel_list[did].members_count,
-			duel_list[did].members_count + duel_list[did].invites_count);
-
-	clif_disp_onlyself(sd, output, strlen(output));
-	map_foreachpc(duel_showinfo_sub, sd, &p);
+    int p=0;
+    char output[256];
+
+    if (duel_list[did].max_players_limit > 0)
+        sprintf(output, msg_txt(370), //" -- Duels: %d/%d, Members: %d/%d, Max players: %d --"
+                did, duel_count,
+                duel_list[did].members_count,
+                duel_list[did].members_count + duel_list[did].invites_count,
+                duel_list[did].max_players_limit);
+    else
+        sprintf(output, msg_txt(371), //" -- Duels: %d/%d, Members: %d/%d --"
+                did, duel_count,
+                duel_list[did].members_count,
+                duel_list[did].members_count + duel_list[did].invites_count);
+
+    clif_disp_onlyself(sd, output, strlen(output));
+    map_foreachpc(duel_showinfo_sub, sd, &p);
 }
 
-int duel_create(struct map_session_data* sd, const unsigned int maxpl)
+int duel_create(struct map_session_data *sd, const unsigned int maxpl)
 {
-	int i=1;
-	char output[256];
-	
-	while(duel_list[i].members_count > 0 && i < MAX_DUEL) i++;
-	if(i == MAX_DUEL) return 0;
-	
-	duel_count++;
-	sd->duel_group = i;
-	duel_list[i].members_count++;
-	duel_list[i].invites_count = 0;
-	duel_list[i].max_players_limit = maxpl;
-	
-	strcpy(output, msg_txt(372)); // " -- Duel has been created (@invite/@leave) --"
-	clif_disp_onlyself(sd, output, strlen(output));
-	
-	clif_map_property(sd, MAPPROPERTY_FREEPVPZONE);
-	//clif_misceffect2(&sd->bl, 159);
-	return i;
+    int i=1;
+    char output[256];
+
+    while (duel_list[i].members_count > 0 && i < MAX_DUEL) i++;
+    if (i == MAX_DUEL) return 0;
+
+    duel_count++;
+    sd->duel_group = i;
+    duel_list[i].members_count++;
+    duel_list[i].invites_count = 0;
+    duel_list[i].max_players_limit = maxpl;
+
+    strcpy(output, msg_txt(372)); // " -- Duel has been created (@invite/@leave) --"
+    clif_disp_onlyself(sd, output, strlen(output));
+
+    clif_map_property(sd, MAPPROPERTY_FREEPVPZONE);
+    //clif_misceffect2(&sd->bl, 159);
+    return i;
 }
 
-void duel_invite(const unsigned int did, struct map_session_data* sd, struct map_session_data* target_sd)
+void duel_invite(const unsigned int did, struct map_session_data *sd, struct map_session_data *target_sd)
 {
-	char output[256];
-
-	// " -- Player %s invites %s to duel --"
-	sprintf(output, msg_txt(373), sd->status.name, target_sd->status.name);
-	clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
-
-	target_sd->duel_invite = did;
-	duel_list[did].invites_count++;
-	
-	// "Blue -- Player %s invites you to PVP duel (@accept/@reject) --"
-	sprintf(output, msg_txt(374), sd->status.name);
-	clif_broadcast((struct block_list *)target_sd, output, strlen(output)+1, 0x10, SELF);
+    char output[256];
+
+    // " -- Player %s invites %s to duel --"
+    sprintf(output, msg_txt(373), sd->status.name, target_sd->status.name);
+    clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
+
+    target_sd->duel_invite = did;
+    duel_list[did].invites_count++;
+
+    // "Blue -- Player %s invites you to PVP duel (@accept/@reject) --"
+    sprintf(output, msg_txt(374), sd->status.name);
+    clif_broadcast((struct block_list *)target_sd, output, strlen(output)+1, 0x10, SELF);
 }
 
-static int duel_leave_sub(struct map_session_data* sd, va_list va)
+static int duel_leave_sub(struct map_session_data *sd, va_list va)
 {
-	int did = va_arg(va, int);
-	if (sd->duel_invite == did)
-		sd->duel_invite = 0;
-	return 0;
+    int did = va_arg(va, int);
+    if (sd->duel_invite == did)
+        sd->duel_invite = 0;
+    return 0;
 }
 
-void duel_leave(const unsigned int did, struct map_session_data* sd)
+void duel_leave(const unsigned int did, struct map_session_data *sd)
 {
-	char output[256];
-	
-	// " <- Player %s has left duel --"
-	sprintf(output, msg_txt(375), sd->status.name);
-	clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
-	
-	duel_list[did].members_count--;
-	
-	if(duel_list[did].members_count == 0) {
-		map_foreachpc(duel_leave_sub, did); 
-		duel_count--;
-	}
-	
-	sd->duel_group = 0;
-	duel_savetime(sd);
-	clif_map_property(sd, MAPPROPERTY_NOTHING);
+    char output[256];
+
+    // " <- Player %s has left duel --"
+    sprintf(output, msg_txt(375), sd->status.name);
+    clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
+
+    duel_list[did].members_count--;
+
+    if (duel_list[did].members_count == 0) {
+        map_foreachpc(duel_leave_sub, did);
+        duel_count--;
+    }
+
+    sd->duel_group = 0;
+    duel_savetime(sd);
+    clif_map_property(sd, MAPPROPERTY_NOTHING);
 }
 
-void duel_accept(const unsigned int did, struct map_session_data* sd)
+void duel_accept(const unsigned int did, struct map_session_data *sd)
 {
-	char output[256];
-	
-	duel_list[did].members_count++;
-	sd->duel_group = sd->duel_invite;
-	duel_list[did].invites_count--;
-	sd->duel_invite = 0;
-	
-	// " -> Player %s has accepted duel --"
-	sprintf(output, msg_txt(376), sd->status.name);
-	clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
-
-	clif_map_property(sd, MAPPROPERTY_FREEPVPZONE);
-	//clif_misceffect2(&sd->bl, 159);
+    char output[256];
+
+    duel_list[did].members_count++;
+    sd->duel_group = sd->duel_invite;
+    duel_list[did].invites_count--;
+    sd->duel_invite = 0;
+
+    // " -> Player %s has accepted duel --"
+    sprintf(output, msg_txt(376), sd->status.name);
+    clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
+
+    clif_map_property(sd, MAPPROPERTY_FREEPVPZONE);
+    //clif_misceffect2(&sd->bl, 159);
 }
 
-void duel_reject(const unsigned int did, struct map_session_data* sd)
+void duel_reject(const unsigned int did, struct map_session_data *sd)
 {
-	char output[256];
-	
-	// " -- Player %s has rejected duel --"
-	sprintf(output, msg_txt(377), sd->status.name);
-	clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
-	
-	duel_list[did].invites_count--;
-	sd->duel_invite = 0;
+    char output[256];
+
+    // " -- Player %s has rejected duel --"
+    sprintf(output, msg_txt(377), sd->status.name);
+    clif_disp_message(&sd->bl, output, strlen(output), DUEL_WOS);
+
+    duel_list[did].invites_count--;
+    sd->duel_invite = 0;
 }
 
 void do_final_duel(void)
@@ -178,5 +178,5 @@ void do_final_duel(void)
 
 void do_init_duel(void)
 {
-	memset(&duel_list[0], 0, sizeof(duel_list));
+    memset(&duel_list[0], 0, sizeof(duel_list));
 }

+ 10 - 10
src/map/duel.h

@@ -5,9 +5,9 @@
 #define _DUEL_H_
 
 struct duel {
-	int members_count;
-	int invites_count;
-	int max_players_limit;
+    int members_count;
+    int invites_count;
+    int max_players_limit;
 };
 
 #define MAX_DUEL 1024
@@ -15,13 +15,13 @@ extern struct duel duel_list[MAX_DUEL];
 extern int duel_count;
 
 //Duel functions // [LuzZza]
-int duel_create(struct map_session_data* sd, const unsigned int maxpl);
-void duel_invite(const unsigned int did, struct map_session_data* sd, struct map_session_data* target_sd);
-void duel_accept(const unsigned int did, struct map_session_data* sd);
-void duel_reject(const unsigned int did, struct map_session_data* sd);
-void duel_leave(const unsigned int did, struct map_session_data* sd);
-void duel_showinfo(const unsigned int did, struct map_session_data* sd);
-int duel_checktime(struct map_session_data* sd);
+int duel_create(struct map_session_data *sd, const unsigned int maxpl);
+void duel_invite(const unsigned int did, struct map_session_data *sd, struct map_session_data *target_sd);
+void duel_accept(const unsigned int did, struct map_session_data *sd);
+void duel_reject(const unsigned int did, struct map_session_data *sd);
+void duel_leave(const unsigned int did, struct map_session_data *sd);
+void duel_showinfo(const unsigned int did, struct map_session_data *sd);
+int duel_checktime(struct map_session_data *sd);
 
 void do_init_duel(void);
 void do_final_duel(void);

+ 744 - 714
src/map/elemental.c

@@ -39,785 +39,815 @@
 
 struct s_elemental_db elemental_db[MAX_ELEMENTAL_CLASS]; // Elemental Database
 
-int elemental_search_index(int class_) {
-	int i;
-	ARR_FIND(0, MAX_ELEMENTAL_CLASS, i, elemental_db[i].class_ == class_);
-	return (i == MAX_ELEMENTAL_CLASS)?-1:i;
+int elemental_search_index(int class_)
+{
+    int i;
+    ARR_FIND(0, MAX_ELEMENTAL_CLASS, i, elemental_db[i].class_ == class_);
+    return (i == MAX_ELEMENTAL_CLASS)?-1:i;
 }
 
-bool elemental_class(int class_) {
-	return (bool)(elemental_search_index(class_) > -1);
+bool elemental_class(int class_)
+{
+    return (bool)(elemental_search_index(class_) > -1);
 }
 
-struct view_data * elemental_get_viewdata(int class_) {
-	int i = elemental_search_index(class_);
-	if( i < 0 )
-		return 0;
-	
-	return &elemental_db[i].vd;
+struct view_data *elemental_get_viewdata(int class_) {
+    int i = elemental_search_index(class_);
+    if (i < 0)
+        return 0;
+
+    return &elemental_db[i].vd;
 }
 
-int elemental_create(struct map_session_data *sd, int class_, unsigned int lifetime) {
-	struct s_elemental ele;
-	struct s_elemental_db *db;
-	int i;
-	
-	nullpo_retr(1,sd);
-	
-	if( (i = elemental_search_index(class_)) < 0 )
-		return 0;
-	
-	db = &elemental_db[i];
-	memset(&ele,0,sizeof(struct s_elemental));
-	
-	ele.char_id = sd->status.char_id;
-	ele.class_ = class_;
-	ele.mode = EL_MODE_PASSIVE; // Initial mode
-	ele.hp = db->status.max_hp;
-	ele.sp = db->status.max_sp;
-	ele.life_time = lifetime;
-	
-	// Request Char Server to create this elemental
-	intif_elemental_create(&ele);
-	
-	return 1;
+int elemental_create(struct map_session_data *sd, int class_, unsigned int lifetime)
+{
+    struct s_elemental ele;
+    struct s_elemental_db *db;
+    int i;
+
+    nullpo_retr(1,sd);
+
+    if ((i = elemental_search_index(class_)) < 0)
+        return 0;
+
+    db = &elemental_db[i];
+    memset(&ele,0,sizeof(struct s_elemental));
+
+    ele.char_id = sd->status.char_id;
+    ele.class_ = class_;
+    ele.mode = EL_MODE_PASSIVE; // Initial mode
+    ele.hp = db->status.max_hp;
+    ele.sp = db->status.max_sp;
+    ele.life_time = lifetime;
+
+    // Request Char Server to create this elemental
+    intif_elemental_create(&ele);
+
+    return 1;
 }
 
-int elemental_get_lifetime(struct elemental_data *ed) {
-	const struct TimerData * td;
-	if( ed == NULL || ed->summon_timer == INVALID_TIMER )
-		return 0;
-	
-	td = get_timer(ed->summon_timer);
-	return (td != NULL) ? DIFF_TICK(td->tick, gettick()) : 0;
+int elemental_get_lifetime(struct elemental_data *ed)
+{
+    const struct TimerData *td;
+    if (ed == NULL || ed->summon_timer == INVALID_TIMER)
+        return 0;
+
+    td = get_timer(ed->summon_timer);
+    return (td != NULL) ? DIFF_TICK(td->tick, gettick()) : 0;
 }
 
-int elemental_save(struct elemental_data *ed) {
-	ed->elemental.hp = ed->battle_status.hp;
-	ed->elemental.sp = ed->battle_status.sp;
-	ed->elemental.life_time = elemental_get_lifetime(ed);
-	
-	intif_elemental_save(&ed->elemental);
-	return 1;
+int elemental_save(struct elemental_data *ed)
+{
+    ed->elemental.hp = ed->battle_status.hp;
+    ed->elemental.sp = ed->battle_status.sp;
+    ed->elemental.life_time = elemental_get_lifetime(ed);
+
+    intif_elemental_save(&ed->elemental);
+    return 1;
 }
 
-static int elemental_summon_end(int tid, unsigned int tick, int id, intptr_t data) {
-	struct map_session_data *sd;
-	struct elemental_data *ed;
-	
-	if( (sd = map_id2sd(id)) == NULL )
-		return 1;
-	if( (ed = sd->ed) == NULL )
-		return 1;
-	
-	if( ed->summon_timer != tid ) {
-		ShowError("elemental_summon_end %d != %d.\n", ed->summon_timer, tid);
-		return 0;
-	}
-	
-	ed->summon_timer = INVALID_TIMER;
-	elemental_delete(ed, 0); // Elemental's summon time is over.
-	
-	return 0;
+static int elemental_summon_end(int tid, unsigned int tick, int id, intptr_t data)
+{
+    struct map_session_data *sd;
+    struct elemental_data *ed;
+
+    if ((sd = map_id2sd(id)) == NULL)
+        return 1;
+    if ((ed = sd->ed) == NULL)
+        return 1;
+
+    if (ed->summon_timer != tid) {
+        ShowError("elemental_summon_end %d != %d.\n", ed->summon_timer, tid);
+        return 0;
+    }
+
+    ed->summon_timer = INVALID_TIMER;
+    elemental_delete(ed, 0); // Elemental's summon time is over.
+
+    return 0;
 }
 
-void elemental_summon_stop(struct elemental_data *ed) {
-	nullpo_retv(ed);
-	if( ed->summon_timer != INVALID_TIMER )
-		delete_timer(ed->summon_timer, elemental_summon_end);
-	ed->summon_timer = INVALID_TIMER;
+void elemental_summon_stop(struct elemental_data *ed)
+{
+    nullpo_retv(ed);
+    if (ed->summon_timer != INVALID_TIMER)
+        delete_timer(ed->summon_timer, elemental_summon_end);
+    ed->summon_timer = INVALID_TIMER;
 }
 
-int elemental_delete(struct elemental_data *ed, int reply) {
-	struct map_session_data *sd;
-	
-	nullpo_ret(ed);
-	
-	sd = ed->master;
-	ed->elemental.life_time = 0;
-	
-	elemental_clean_effect(ed);
-	elemental_summon_stop(ed);
-	
-	if( !sd )
-		return unit_free(&ed->bl, 0);
-	
-	sd->ed = NULL;
-	sd->status.ele_id = 0;
-	
-	return unit_remove_map(&ed->bl, 0);
+int elemental_delete(struct elemental_data *ed, int reply)
+{
+    struct map_session_data *sd;
+
+    nullpo_ret(ed);
+
+    sd = ed->master;
+    ed->elemental.life_time = 0;
+
+    elemental_clean_effect(ed);
+    elemental_summon_stop(ed);
+
+    if (!sd)
+        return unit_free(&ed->bl, 0);
+
+    sd->ed = NULL;
+    sd->status.ele_id = 0;
+
+    return unit_remove_map(&ed->bl, 0);
 }
 
-void elemental_summon_init(struct elemental_data *ed) {
-	if( ed->summon_timer == INVALID_TIMER )
-		ed->summon_timer = add_timer(gettick() + ed->elemental.life_time, elemental_summon_end, ed->master->bl.id, 0);
-	
-	ed->regen.state.block = 0;
+void elemental_summon_init(struct elemental_data *ed)
+{
+    if (ed->summon_timer == INVALID_TIMER)
+        ed->summon_timer = add_timer(gettick() + ed->elemental.life_time, elemental_summon_end, ed->master->bl.id, 0);
+
+    ed->regen.state.block = 0;
 }
 
-int elemental_data_received(struct s_elemental *ele, bool flag) {
-	struct map_session_data *sd;
-	struct elemental_data *ed;
-	struct s_elemental_db *db;
-	int i = elemental_search_index(ele->class_);
-	
-	if( (sd = map_charid2sd(ele->char_id)) == NULL )
-		return 0;
-	
-	if( !flag || i < 0 ) { // Not created - loaded - DB info
-		sd->status.ele_id = 0;
-		return 0;
-	}
-	
-	db = &elemental_db[i];
-	if( !sd->ed ) {	// Initialize it after first summon.
-		sd->ed = ed = (struct elemental_data*)aCalloc(1,sizeof(struct elemental_data));
-		ed->bl.type = BL_ELEM;
-		ed->bl.id = npc_get_new_npc_id();
-		ed->master = sd;
-		ed->db = db;
-		memcpy(&ed->elemental, ele, sizeof(struct s_elemental));
-		status_set_viewdata(&ed->bl, ed->elemental.class_);
-		ed->vd->head_mid = 10; // Why?
-		status_change_init(&ed->bl);
-		unit_dataset(&ed->bl);
-		ed->ud.dir = sd->ud.dir;
-		
-		ed->bl.m = sd->bl.m;
-		ed->bl.x = sd->bl.x;
-		ed->bl.y = sd->bl.y;
-		unit_calc_pos(&ed->bl, sd->bl.x, sd->bl.y, sd->ud.dir);
-		ed->bl.x = ed->ud.to_x;
-		ed->bl.y = ed->ud.to_y;
-		
-		map_addiddb(&ed->bl);
-		status_calc_elemental(ed,1);
-		ed->last_thinktime = gettick();
-		ed->summon_timer = INVALID_TIMER;
-		ed->battle_status.mode = ele->mode = EL_MODE_PASSIVE; // Initial mode.
-		elemental_summon_init(ed);
-	} else {
-		memcpy(&sd->ed->elemental, ele, sizeof(struct s_elemental));
-		ed = sd->ed;
-	}
-	
-	sd->status.ele_id = ele->elemental_id;
-	ed->battle_status.mode = ele->mode = EL_MODE_PASSIVE; // Initial mode.
-	
-	if( ed->bl.prev == NULL && sd->bl.prev != NULL ) {
-		map_addblock(&ed->bl);
-		clif_spawn(&ed->bl);
-		clif_elemental_info(sd);
-		clif_elemental_updatestatus(sd,SP_HP);
-		clif_hpmeter_single(sd->fd,ed->bl.id,ed->battle_status.hp,ed->battle_status.matk_max);
-		clif_elemental_updatestatus(sd,SP_SP);
-	}
-	
-	return 1;
+int elemental_data_received(struct s_elemental *ele, bool flag)
+{
+    struct map_session_data *sd;
+    struct elemental_data *ed;
+    struct s_elemental_db *db;
+    int i = elemental_search_index(ele->class_);
+
+    if ((sd = map_charid2sd(ele->char_id)) == NULL)
+        return 0;
+
+    if (!flag || i < 0) {  // Not created - loaded - DB info
+        sd->status.ele_id = 0;
+        return 0;
+    }
+
+    db = &elemental_db[i];
+    if (!sd->ed) {   // Initialize it after first summon.
+        sd->ed = ed = (struct elemental_data *)aCalloc(1,sizeof(struct elemental_data));
+        ed->bl.type = BL_ELEM;
+        ed->bl.id = npc_get_new_npc_id();
+        ed->master = sd;
+        ed->db = db;
+        memcpy(&ed->elemental, ele, sizeof(struct s_elemental));
+        status_set_viewdata(&ed->bl, ed->elemental.class_);
+        ed->vd->head_mid = 10; // Why?
+        status_change_init(&ed->bl);
+        unit_dataset(&ed->bl);
+        ed->ud.dir = sd->ud.dir;
+
+        ed->bl.m = sd->bl.m;
+        ed->bl.x = sd->bl.x;
+        ed->bl.y = sd->bl.y;
+        unit_calc_pos(&ed->bl, sd->bl.x, sd->bl.y, sd->ud.dir);
+        ed->bl.x = ed->ud.to_x;
+        ed->bl.y = ed->ud.to_y;
+
+        map_addiddb(&ed->bl);
+        status_calc_elemental(ed,1);
+        ed->last_thinktime = gettick();
+        ed->summon_timer = INVALID_TIMER;
+        ed->battle_status.mode = ele->mode = EL_MODE_PASSIVE; // Initial mode.
+        elemental_summon_init(ed);
+    } else {
+        memcpy(&sd->ed->elemental, ele, sizeof(struct s_elemental));
+        ed = sd->ed;
+    }
+
+    sd->status.ele_id = ele->elemental_id;
+    ed->battle_status.mode = ele->mode = EL_MODE_PASSIVE; // Initial mode.
+
+    if (ed->bl.prev == NULL && sd->bl.prev != NULL) {
+        map_addblock(&ed->bl);
+        clif_spawn(&ed->bl);
+        clif_elemental_info(sd);
+        clif_elemental_updatestatus(sd,SP_HP);
+        clif_hpmeter_single(sd->fd,ed->bl.id,ed->battle_status.hp,ed->battle_status.matk_max);
+        clif_elemental_updatestatus(sd,SP_SP);
+    }
+
+    return 1;
 }
 
-int elemental_clean_single_effect(struct elemental_data *ed, int skill_num) {
-	struct block_list *bl;
-	sc_type type = status_skill2sc(skill_num);
-	
-	nullpo_ret(ed);
-	
-	bl = battle_get_master(&ed->bl);
-	
-	if( type ) {
-		switch( type ) {
-				// Just remove status change.
-			case SC_PYROTECHNIC_OPTION:
-			case SC_HEATER_OPTION:
-			case SC_TROPIC_OPTION:
-			case SC_FIRE_CLOAK_OPTION:
-			case SC_AQUAPLAY_OPTION:
-			case SC_WATER_SCREEN_OPTION:
-			case SC_COOLER_OPTION:
-			case SC_CHILLY_AIR_OPTION:
-			case SC_GUST_OPTION:
-			case SC_WIND_STEP_OPTION:
-			case SC_BLAST_OPTION:
-			case SC_WATER_DROP_OPTION:
-			case SC_WIND_CURTAIN_OPTION:
-			case SC_WILD_STORM_OPTION:
-			case SC_PETROLOGY_OPTION:
-			case SC_SOLID_SKIN_OPTION:
-			case SC_CURSED_SOIL_OPTION:
-			case SC_STONE_SHIELD_OPTION:
-			case SC_UPHEAVAL_OPTION:
-			case SC_CIRCLE_OF_FIRE_OPTION:
-			case SC_TIDAL_WEAPON_OPTION:
-				if( bl ) status_change_end(bl,type,INVALID_TIMER);	// Master
-				status_change_end(&ed->bl,type-1,INVALID_TIMER);	// Elemental Spirit
-				break;
-			case SC_ZEPHYR:
-				if( bl ) status_change_end(bl,type,INVALID_TIMER);
-				break;
-			default:
-				ShowWarning("Invalid SC=%d in elemental_clean_single_effect\n",type);
-				break;
-		}
-	}
-	if( skill_get_unit_id(skill_num,0) )
-		skill_clear_unitgroup(&ed->bl);
-	
-	return 1;
+int elemental_clean_single_effect(struct elemental_data *ed, int skill_num)
+{
+    struct block_list *bl;
+    sc_type type = status_skill2sc(skill_num);
+
+    nullpo_ret(ed);
+
+    bl = battle_get_master(&ed->bl);
+
+    if (type) {
+        switch (type) {
+                // Just remove status change.
+            case SC_PYROTECHNIC_OPTION:
+            case SC_HEATER_OPTION:
+            case SC_TROPIC_OPTION:
+            case SC_FIRE_CLOAK_OPTION:
+            case SC_AQUAPLAY_OPTION:
+            case SC_WATER_SCREEN_OPTION:
+            case SC_COOLER_OPTION:
+            case SC_CHILLY_AIR_OPTION:
+            case SC_GUST_OPTION:
+            case SC_WIND_STEP_OPTION:
+            case SC_BLAST_OPTION:
+            case SC_WATER_DROP_OPTION:
+            case SC_WIND_CURTAIN_OPTION:
+            case SC_WILD_STORM_OPTION:
+            case SC_PETROLOGY_OPTION:
+            case SC_SOLID_SKIN_OPTION:
+            case SC_CURSED_SOIL_OPTION:
+            case SC_STONE_SHIELD_OPTION:
+            case SC_UPHEAVAL_OPTION:
+            case SC_CIRCLE_OF_FIRE_OPTION:
+            case SC_TIDAL_WEAPON_OPTION:
+                if (bl) status_change_end(bl,type,INVALID_TIMER);    // Master
+                status_change_end(&ed->bl,type-1,INVALID_TIMER);    // Elemental Spirit
+                break;
+            case SC_ZEPHYR:
+                if (bl) status_change_end(bl,type,INVALID_TIMER);
+                break;
+            default:
+                ShowWarning("Invalid SC=%d in elemental_clean_single_effect\n",type);
+                break;
+        }
+    }
+    if (skill_get_unit_id(skill_num,0))
+        skill_clear_unitgroup(&ed->bl);
+
+    return 1;
 }
 
-int elemental_clean_effect(struct elemental_data *ed) {
-	struct map_session_data *sd;
-	
-	nullpo_ret(ed);
-	
-	// Elemental side
-	status_change_end(&ed->bl, SC_TROPIC, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_HEATER, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_AQUAPLAY, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_COOLER, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_CHILLY_AIR, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_PYROTECHNIC, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_FIRE_CLOAK, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_WATER_DROP, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_WATER_SCREEN, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_GUST, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_WIND_STEP, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_BLAST, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_WIND_CURTAIN, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_WILD_STORM, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_PETROLOGY, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_SOLID_SKIN, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_CURSED_SOIL, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_STONE_SHIELD, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_UPHEAVAL, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_CIRCLE_OF_FIRE, INVALID_TIMER);
-	status_change_end(&ed->bl, SC_TIDAL_WEAPON, INVALID_TIMER);
-	
-	skill_clear_unitgroup(&ed->bl);
-	
-	if( (sd = ed->master) == NULL )
-		return 0;
-	
-	// Master side
-	status_change_end(&sd->bl, SC_TROPIC_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_HEATER_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_AQUAPLAY_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_COOLER_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_CHILLY_AIR_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_PYROTECHNIC_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_FIRE_CLOAK_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_WATER_DROP_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_WATER_SCREEN_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_GUST_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_WIND_STEP_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_BLAST_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_WATER_DROP_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_WIND_CURTAIN_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_WILD_STORM_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_ZEPHYR, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_WIND_STEP_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_PETROLOGY_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_SOLID_SKIN_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_CURSED_SOIL_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_STONE_SHIELD_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_UPHEAVAL_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_CIRCLE_OF_FIRE_OPTION, INVALID_TIMER);
-	status_change_end(&sd->bl, SC_TIDAL_WEAPON_OPTION, INVALID_TIMER);
-	
-	return 1;
+int elemental_clean_effect(struct elemental_data *ed)
+{
+    struct map_session_data *sd;
+
+    nullpo_ret(ed);
+
+    // Elemental side
+    status_change_end(&ed->bl, SC_TROPIC, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_HEATER, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_AQUAPLAY, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_COOLER, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_CHILLY_AIR, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_PYROTECHNIC, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_FIRE_CLOAK, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_WATER_DROP, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_WATER_SCREEN, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_GUST, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_WIND_STEP, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_BLAST, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_WIND_CURTAIN, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_WILD_STORM, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_PETROLOGY, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_SOLID_SKIN, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_CURSED_SOIL, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_STONE_SHIELD, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_UPHEAVAL, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_CIRCLE_OF_FIRE, INVALID_TIMER);
+    status_change_end(&ed->bl, SC_TIDAL_WEAPON, INVALID_TIMER);
+
+    skill_clear_unitgroup(&ed->bl);
+
+    if ((sd = ed->master) == NULL)
+        return 0;
+
+    // Master side
+    status_change_end(&sd->bl, SC_TROPIC_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_HEATER_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_AQUAPLAY_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_COOLER_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_CHILLY_AIR_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_PYROTECHNIC_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_FIRE_CLOAK_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_WATER_DROP_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_WATER_SCREEN_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_GUST_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_WIND_STEP_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_BLAST_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_WATER_DROP_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_WIND_CURTAIN_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_WILD_STORM_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_ZEPHYR, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_WIND_STEP_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_PETROLOGY_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_SOLID_SKIN_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_CURSED_SOIL_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_STONE_SHIELD_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_UPHEAVAL_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_CIRCLE_OF_FIRE_OPTION, INVALID_TIMER);
+    status_change_end(&sd->bl, SC_TIDAL_WEAPON_OPTION, INVALID_TIMER);
+
+    return 1;
 }
 
-int elemental_action(struct elemental_data *ed, struct block_list *bl, unsigned int tick) {
-	short skillnum, skilllv;
-	int i;
-	
-	nullpo_ret(ed);
-	nullpo_ret(bl);
-	
-	if( !ed->master )
-		return 0;
-	
-	if( ed->target_id )
-		elemental_unlocktarget(ed);	// Remove previous target.
-	
-	ARR_FIND(0, MAX_ELESKILLTREE, i, ed->db->skill[i].id && (ed->db->skill[i].mode&EL_SKILLMODE_AGGRESSIVE));
-	if( i == MAX_ELESKILLTREE )
-		return 0;
-	
-	skillnum = ed->db->skill[i].id;
-	skilllv = ed->db->skill[i].lv;
-	
-	if( elemental_skillnotok(skillnum, ed) )
-		return 0;
-	
-	if( ed->ud.skilltimer != INVALID_TIMER )
-		return 0;
-	else if( DIFF_TICK(tick, ed->ud.canact_tick) < 0 )
-		return 0;
-	
-	ed->target_id = ed->ud.skilltarget = bl->id;	// Set new target
-	ed->last_thinktime = tick;
-	
-	// Not in skill range.
-	if( !battle_check_range(&ed->bl,bl,skill_get_range(skillnum,skilllv)) ) {
-		// Try to walk to the target.
-		if( !unit_walktobl(&ed->bl, bl, skill_get_range(skillnum,skilllv), 2) )
-			elemental_unlocktarget(ed);
-		else {
-			// Walking, waiting to be in range. Client don't handle it, then we must handle it here.
-			int walk_dist = distance_bl(&ed->bl,bl) - skill_get_range(skillnum,skilllv);
-			ed->ud.skillid = skillnum;
-			ed->ud.skilllv = skilllv;
-			
-			if( skill_get_inf(skillnum) & INF_GROUND_SKILL )
-				ed->ud.skilltimer = add_timer( tick+status_get_speed(&ed->bl)*walk_dist, skill_castend_pos, ed->bl.id, 0 );
-			else
-				ed->ud.skilltimer = add_timer( tick+status_get_speed(&ed->bl)*walk_dist, skill_castend_id, ed->bl.id, 0 );
-		}
-		return 1;
-		
-	}
-	//Otherwise, just cast the skill.
-	if( skill_get_inf(skillnum) & INF_GROUND_SKILL )
-		unit_skilluse_pos(&ed->bl, bl->x, bl->y, skillnum, skilllv);
-	else
-		unit_skilluse_id(&ed->bl, bl->id, skillnum, skilllv);
-	
-	// Reset target.
-	ed->target_id = 0;
-	
-	return 1;
+int elemental_action(struct elemental_data *ed, struct block_list *bl, unsigned int tick)
+{
+    short skillnum, skilllv;
+    int i;
+
+    nullpo_ret(ed);
+    nullpo_ret(bl);
+
+    if (!ed->master)
+        return 0;
+
+    if (ed->target_id)
+        elemental_unlocktarget(ed); // Remove previous target.
+
+    ARR_FIND(0, MAX_ELESKILLTREE, i, ed->db->skill[i].id && (ed->db->skill[i].mode&EL_SKILLMODE_AGGRESSIVE));
+    if (i == MAX_ELESKILLTREE)
+        return 0;
+
+    skillnum = ed->db->skill[i].id;
+    skilllv = ed->db->skill[i].lv;
+
+    if (elemental_skillnotok(skillnum, ed))
+        return 0;
+
+    if (ed->ud.skilltimer != INVALID_TIMER)
+        return 0;
+    else if (DIFF_TICK(tick, ed->ud.canact_tick) < 0)
+        return 0;
+
+    ed->target_id = ed->ud.skilltarget = bl->id;    // Set new target
+    ed->last_thinktime = tick;
+
+    // Not in skill range.
+    if (!battle_check_range(&ed->bl,bl,skill_get_range(skillnum,skilllv))) {
+        // Try to walk to the target.
+        if (!unit_walktobl(&ed->bl, bl, skill_get_range(skillnum,skilllv), 2))
+            elemental_unlocktarget(ed);
+        else {
+            // Walking, waiting to be in range. Client don't handle it, then we must handle it here.
+            int walk_dist = distance_bl(&ed->bl,bl) - skill_get_range(skillnum,skilllv);
+            ed->ud.skillid = skillnum;
+            ed->ud.skilllv = skilllv;
+
+            if (skill_get_inf(skillnum) & INF_GROUND_SKILL)
+                ed->ud.skilltimer = add_timer(tick+status_get_speed(&ed->bl)*walk_dist, skill_castend_pos, ed->bl.id, 0);
+            else
+                ed->ud.skilltimer = add_timer(tick+status_get_speed(&ed->bl)*walk_dist, skill_castend_id, ed->bl.id, 0);
+        }
+        return 1;
+
+    }
+    //Otherwise, just cast the skill.
+    if (skill_get_inf(skillnum) & INF_GROUND_SKILL)
+        unit_skilluse_pos(&ed->bl, bl->x, bl->y, skillnum, skilllv);
+    else
+        unit_skilluse_id(&ed->bl, bl->id, skillnum, skilllv);
+
+    // Reset target.
+    ed->target_id = 0;
+
+    return 1;
 }
 
 /*===============================================================
  * Action that elemental perform after changing mode.
  * Activates one of the skills of the new mode.
  *-------------------------------------------------------------*/
-int elemental_change_mode_ack(struct elemental_data *ed, int mode) {
-	struct block_list *bl = &ed->master->bl;
-	short skillnum, skilllv;
-	int i;
-	
-	nullpo_ret(ed);
-	
-	if( !bl )
-		return 0;
-	
-	// Select a skill.
-	ARR_FIND(0, MAX_ELESKILLTREE, i, ed->db->skill[i].id && (ed->db->skill[i].mode&mode));
-	if( i == MAX_ELESKILLTREE )
-		return 0;
-	
-	skillnum = ed->db->skill[i].id;
-	skilllv = ed->db->skill[i].lv;
-	
-	if( elemental_skillnotok(skillnum, ed) )
-		return 0;
-	
-	if( ed->ud.skilltimer != INVALID_TIMER )
-		return 0;
-	else if( DIFF_TICK(gettick(), ed->ud.canact_tick) < 0 )
-		return 0;
-	
-	ed->target_id = bl->id;	// Set new target
-	ed->last_thinktime = gettick();
-	
-	if( skill_get_inf(skillnum) & INF_GROUND_SKILL )
-		unit_skilluse_pos(&ed->bl, bl->x, bl->y, skillnum, skilllv);
-	else
-		unit_skilluse_id(&ed->bl,bl->id,skillnum,skilllv);
-	
-	ed->target_id = 0;	// Reset target after casting the skill  to avoid continious attack.
-	
-	return 1;
+int elemental_change_mode_ack(struct elemental_data *ed, int mode)
+{
+    struct block_list *bl = &ed->master->bl;
+    short skillnum, skilllv;
+    int i;
+
+    nullpo_ret(ed);
+
+    if (!bl)
+        return 0;
+
+    // Select a skill.
+    ARR_FIND(0, MAX_ELESKILLTREE, i, ed->db->skill[i].id && (ed->db->skill[i].mode&mode));
+    if (i == MAX_ELESKILLTREE)
+        return 0;
+
+    skillnum = ed->db->skill[i].id;
+    skilllv = ed->db->skill[i].lv;
+
+    if (elemental_skillnotok(skillnum, ed))
+        return 0;
+
+    if (ed->ud.skilltimer != INVALID_TIMER)
+        return 0;
+    else if (DIFF_TICK(gettick(), ed->ud.canact_tick) < 0)
+        return 0;
+
+    ed->target_id = bl->id; // Set new target
+    ed->last_thinktime = gettick();
+
+    if (skill_get_inf(skillnum) & INF_GROUND_SKILL)
+        unit_skilluse_pos(&ed->bl, bl->x, bl->y, skillnum, skilllv);
+    else
+        unit_skilluse_id(&ed->bl,bl->id,skillnum,skilllv);
+
+    ed->target_id = 0;  // Reset target after casting the skill  to avoid continious attack.
+
+    return 1;
 }
 
 /*===============================================================
  * Change elemental mode.
  *-------------------------------------------------------------*/
-int elemental_change_mode(struct elemental_data *ed, int mode) {
-	nullpo_ret(ed);
-	
-	// Remove target
-	elemental_unlocktarget(ed);
-	
-	// Removes the effects of the previous mode.
-	if(ed->elemental.mode != mode ) elemental_clean_effect(ed);
-	
-	ed->battle_status.mode = ed->elemental.mode = mode;
-	
-	// Normalize elemental mode to elemental skill mode.
-	if( mode == EL_MODE_AGGRESSIVE ) mode = EL_SKILLMODE_AGGRESSIVE;	// Aggressive spirit mode -> Aggressive spirit skill.
-	else if( mode == EL_MODE_ASSIST ) mode = EL_SKILLMODE_ASSIST;		// Assist spirit mode -> Assist spirit skill.
-	else mode = EL_SKILLMODE_PASIVE;									// Passive spirit mode -> Passive spirit skill.
-	
-	// Use a skill inmediately after every change mode.
-	if( mode != EL_SKILLMODE_AGGRESSIVE )
-		elemental_change_mode_ack(ed,mode);
-	return 1;
+int elemental_change_mode(struct elemental_data *ed, int mode)
+{
+    nullpo_ret(ed);
+
+    // Remove target
+    elemental_unlocktarget(ed);
+
+    // Removes the effects of the previous mode.
+    if (ed->elemental.mode != mode) elemental_clean_effect(ed);
+
+    ed->battle_status.mode = ed->elemental.mode = mode;
+
+    // Normalize elemental mode to elemental skill mode.
+    if (mode == EL_MODE_AGGRESSIVE) mode = EL_SKILLMODE_AGGRESSIVE;  // Aggressive spirit mode -> Aggressive spirit skill.
+    else if (mode == EL_MODE_ASSIST) mode = EL_SKILLMODE_ASSIST;         // Assist spirit mode -> Assist spirit skill.
+    else mode = EL_SKILLMODE_PASIVE;                                    // Passive spirit mode -> Passive spirit skill.
+
+    // Use a skill inmediately after every change mode.
+    if (mode != EL_SKILLMODE_AGGRESSIVE)
+        elemental_change_mode_ack(ed,mode);
+    return 1;
 }
 
-void elemental_heal(struct elemental_data *ed, int hp, int sp) {
-	if( hp )
-		clif_elemental_updatestatus(ed->master, SP_HP);
-	if( sp )
-		clif_elemental_updatestatus(ed->master, SP_SP);
+void elemental_heal(struct elemental_data *ed, int hp, int sp)
+{
+    if (hp)
+        clif_elemental_updatestatus(ed->master, SP_HP);
+    if (sp)
+        clif_elemental_updatestatus(ed->master, SP_SP);
 }
 
-int elemental_dead(struct elemental_data *ed) {
-	elemental_delete(ed, 1);
-	return 0;
+int elemental_dead(struct elemental_data *ed)
+{
+    elemental_delete(ed, 1);
+    return 0;
 }
 
-int elemental_unlocktarget(struct elemental_data *ed) {
-	nullpo_ret(ed);
-	
-	ed->target_id = 0;
-	elemental_stop_attack(ed);
-	elemental_stop_walking(ed,1);
-	return 0;
+int elemental_unlocktarget(struct elemental_data *ed)
+{
+    nullpo_ret(ed);
+
+    ed->target_id = 0;
+    elemental_stop_attack(ed);
+    elemental_stop_walking(ed,1);
+    return 0;
 }
 
-int elemental_skillnotok(int skillid, struct elemental_data *ed) {
-	int i = skill_get_index(skillid);
-	nullpo_retr(1,ed);
-	
-	if (i == 0)
-		return 1; // invalid skill id
-		
-	return skillnotok(skillid, ed->master);
+int elemental_skillnotok(int skillid, struct elemental_data *ed)
+{
+    int i = skill_get_index(skillid);
+    nullpo_retr(1,ed);
+
+    if (i == 0)
+        return 1; // invalid skill id
+
+    return skillnotok(skillid, ed->master);
 }
 
-int elemental_set_target( struct map_session_data *sd, struct block_list *bl ) {
-	struct elemental_data *ed = sd->ed;
-	
-	nullpo_ret(ed);
-	nullpo_ret(bl);
-	
-	if( ed->bl.m != bl->m || !check_distance_bl(&ed->bl, bl, ed->db->range2) )
-		return 0;
-	
-	if( !status_check_skilluse(&ed->bl, bl, 0, 0) )
-		return 0;
-	
-	if( ed->target_id == 0 )
-		ed->target_id = bl->id;
-	
-	return 1;
+int elemental_set_target(struct map_session_data *sd, struct block_list *bl)
+{
+    struct elemental_data *ed = sd->ed;
+
+    nullpo_ret(ed);
+    nullpo_ret(bl);
+
+    if (ed->bl.m != bl->m || !check_distance_bl(&ed->bl, bl, ed->db->range2))
+        return 0;
+
+    if (!status_check_skilluse(&ed->bl, bl, 0, 0))
+        return 0;
+
+    if (ed->target_id == 0)
+        ed->target_id = bl->id;
+
+    return 1;
 }
 
-static int elemental_ai_sub_timer_activesearch(struct block_list *bl, va_list ap) {
-	struct elemental_data *ed;
-	struct block_list **target;
-	int dist;
-	
-	nullpo_ret(bl);
-	
-	ed = va_arg(ap,struct elemental_data *);
-	target = va_arg(ap,struct block_list**);
-	
-	//If can't seek yet, not an enemy, or you can't attack it, skip.
-	if( (*target) == bl || !status_check_skilluse(&ed->bl, bl, 0, 0) )
-		return 0;
-	
-	if( battle_check_target(&ed->bl,bl,BCT_ENEMY) <= 0 )
-		return 0;
-	
-	switch( bl->type ) {
-		case BL_PC:
-			if( !map_flag_vs(ed->bl.m) )
-				return 0;
-		default:
-			dist = distance_bl(&ed->bl, bl);
-			if( ((*target) == NULL || !check_distance_bl(&ed->bl, *target, dist)) && battle_check_range(&ed->bl,bl,ed->db->range2) ) { //Pick closest target?
-				(*target) = bl;
-				ed->target_id = bl->id;
-				ed->min_chase = dist + ed->db->range3;
-				if( ed->min_chase > AREA_SIZE )
-					ed->min_chase = AREA_SIZE;
-				return 1;
-			}
-			break;
-	}
-	return 0;
+static int elemental_ai_sub_timer_activesearch(struct block_list *bl, va_list ap)
+{
+    struct elemental_data *ed;
+    struct block_list **target;
+    int dist;
+
+    nullpo_ret(bl);
+
+    ed = va_arg(ap,struct elemental_data *);
+    target = va_arg(ap,struct block_list **);
+
+    //If can't seek yet, not an enemy, or you can't attack it, skip.
+    if ((*target) == bl || !status_check_skilluse(&ed->bl, bl, 0, 0))
+        return 0;
+
+    if (battle_check_target(&ed->bl,bl,BCT_ENEMY) <= 0)
+        return 0;
+
+    switch (bl->type) {
+        case BL_PC:
+            if (!map_flag_vs(ed->bl.m))
+                return 0;
+        default:
+            dist = distance_bl(&ed->bl, bl);
+            if (((*target) == NULL || !check_distance_bl(&ed->bl, *target, dist)) && battle_check_range(&ed->bl,bl,ed->db->range2)) {  //Pick closest target?
+                (*target) = bl;
+                ed->target_id = bl->id;
+                ed->min_chase = dist + ed->db->range3;
+                if (ed->min_chase > AREA_SIZE)
+                    ed->min_chase = AREA_SIZE;
+                return 1;
+            }
+            break;
+    }
+    return 0;
 }
 
-static int elemental_ai_sub_timer(struct elemental_data *ed, struct map_session_data *sd, unsigned int tick) {
-	struct block_list *target = NULL;
-	int master_dist, view_range, mode;
-	
-	nullpo_ret(ed);
-	nullpo_ret(sd);
-	
-	if( ed->bl.prev == NULL || sd == NULL || sd->bl.prev == NULL )
-		return 0;
-	
-	if( DIFF_TICK(tick,ed->last_thinktime) < MIN_ELETHINKTIME )
-		return 0;
-	
-	ed->last_thinktime = tick;
-	
-	if( ed->ud.skilltimer != INVALID_TIMER )
-		return 0;
-	
-	if( ed->ud.walktimer != INVALID_TIMER && ed->ud.walkpath.path_pos <= 2 )
-		return 0; //No thinking when you just started to walk.
-	
-	if(ed->ud.walkpath.path_pos < ed->ud.walkpath.path_len && ed->ud.target == sd->bl.id)
-		return 0; //No thinking until be near the master.
-	
-	if( ed->sc.count && ed->sc.data[SC_BLIND] )
-		view_range = 3;
-	else
-		view_range = ed->db->range2;
-	
-	mode = status_get_mode(&ed->bl);
-	
-	master_dist = distance_bl(&sd->bl, &ed->bl);
-	if( master_dist > AREA_SIZE ) {	// Master out of vision range.
-		elemental_unlocktarget(ed);
-		unit_warp(&ed->bl,sd->bl.m,sd->bl.x,sd->bl.y,CLR_TELEPORT);
-		return 0;
-	} else if( master_dist > MAX_ELEDISTANCE ) {	// Master too far, chase.
-		short x = sd->bl.x, y = sd->bl.y;
-		if( ed->target_id )
-			elemental_unlocktarget(ed);
-		if( ed->ud.walktimer != INVALID_TIMER && ed->ud.target == sd->bl.id )
-			return 0; //Already walking to him
-		if( DIFF_TICK(tick, ed->ud.canmove_tick) < 0 )
-			return 0; //Can't move yet.
-		if( map_search_freecell(&ed->bl, sd->bl.m, &x, &y, MIN_ELEDISTANCE, MIN_ELEDISTANCE, 1) 
-		   && unit_walktoxy(&ed->bl, x, y, 0) )
-			return 0;
-	}
-	
-	if( mode == EL_MODE_AGGRESSIVE ) {
-		target = map_id2bl(ed->ud.target);
-		
-		if( !target )
-			map_foreachinrange(elemental_ai_sub_timer_activesearch, &ed->bl, view_range, BL_CHAR, ed, &target, status_get_mode(&ed->bl));
-		
-		if( !target ) { //No targets available.
-			elemental_unlocktarget(ed);
-			return 1;
-		}
-		
-		if( battle_check_range(&ed->bl,target,view_range) && rnd()%100 < 2 ) { // 2% chance to cast attack skill.
-			if(	elemental_action(ed,target,tick) )
-				return 1;
-		}
-		
-		//Attempt to attack.
-		//At this point we know the target is attackable, we just gotta check if the range matches.
-		if( ed->ud.target == target->id && ed->ud.attacktimer != INVALID_TIMER ) //Already locked.
-			return 1;
-		
-		if( battle_check_range(&ed->bl, target, ed->base_status.rhw.range) ) {//Target within range, engage
-			unit_attack(&ed->bl,target->id,1);
-			return 1;
-		}
-		
-		//Follow up if possible.
-		if( !unit_walktobl(&ed->bl, target, ed->base_status.rhw.range, 2) )
-			elemental_unlocktarget(ed);
-	}
-	
-	return 0;
+static int elemental_ai_sub_timer(struct elemental_data *ed, struct map_session_data *sd, unsigned int tick)
+{
+    struct block_list *target = NULL;
+    int master_dist, view_range, mode;
+
+    nullpo_ret(ed);
+    nullpo_ret(sd);
+
+    if (ed->bl.prev == NULL || sd == NULL || sd->bl.prev == NULL)
+        return 0;
+
+    if (DIFF_TICK(tick,ed->last_thinktime) < MIN_ELETHINKTIME)
+        return 0;
+
+    ed->last_thinktime = tick;
+
+    if (ed->ud.skilltimer != INVALID_TIMER)
+        return 0;
+
+    if (ed->ud.walktimer != INVALID_TIMER && ed->ud.walkpath.path_pos <= 2)
+        return 0; //No thinking when you just started to walk.
+
+    if (ed->ud.walkpath.path_pos < ed->ud.walkpath.path_len && ed->ud.target == sd->bl.id)
+        return 0; //No thinking until be near the master.
+
+    if (ed->sc.count && ed->sc.data[SC_BLIND])
+        view_range = 3;
+    else
+        view_range = ed->db->range2;
+
+    mode = status_get_mode(&ed->bl);
+
+    master_dist = distance_bl(&sd->bl, &ed->bl);
+    if (master_dist > AREA_SIZE) {   // Master out of vision range.
+        elemental_unlocktarget(ed);
+        unit_warp(&ed->bl,sd->bl.m,sd->bl.x,sd->bl.y,CLR_TELEPORT);
+        return 0;
+    } else if (master_dist > MAX_ELEDISTANCE) {  // Master too far, chase.
+        short x = sd->bl.x, y = sd->bl.y;
+        if (ed->target_id)
+            elemental_unlocktarget(ed);
+        if (ed->ud.walktimer != INVALID_TIMER && ed->ud.target == sd->bl.id)
+            return 0; //Already walking to him
+        if (DIFF_TICK(tick, ed->ud.canmove_tick) < 0)
+            return 0; //Can't move yet.
+        if (map_search_freecell(&ed->bl, sd->bl.m, &x, &y, MIN_ELEDISTANCE, MIN_ELEDISTANCE, 1)
+            && unit_walktoxy(&ed->bl, x, y, 0))
+            return 0;
+    }
+
+    if (mode == EL_MODE_AGGRESSIVE) {
+        target = map_id2bl(ed->ud.target);
+
+        if (!target)
+            map_foreachinrange(elemental_ai_sub_timer_activesearch, &ed->bl, view_range, BL_CHAR, ed, &target, status_get_mode(&ed->bl));
+
+        if (!target) {  //No targets available.
+            elemental_unlocktarget(ed);
+            return 1;
+        }
+
+        if (battle_check_range(&ed->bl,target,view_range) && rnd()%100 < 2) {  // 2% chance to cast attack skill.
+            if (elemental_action(ed,target,tick))
+                return 1;
+        }
+
+        //Attempt to attack.
+        //At this point we know the target is attackable, we just gotta check if the range matches.
+        if (ed->ud.target == target->id && ed->ud.attacktimer != INVALID_TIMER)  //Already locked.
+            return 1;
+
+        if (battle_check_range(&ed->bl, target, ed->base_status.rhw.range)) { //Target within range, engage
+            unit_attack(&ed->bl,target->id,1);
+            return 1;
+        }
+
+        //Follow up if possible.
+        if (!unit_walktobl(&ed->bl, target, ed->base_status.rhw.range, 2))
+            elemental_unlocktarget(ed);
+    }
+
+    return 0;
 }
 
-static int elemental_ai_sub_foreachclient(struct map_session_data *sd, va_list ap) {
-	unsigned int tick = va_arg(ap,unsigned int);
-	if(sd->status.ele_id && sd->ed)
-		elemental_ai_sub_timer(sd->ed,sd,tick);
-	
-	return 0;
+static int elemental_ai_sub_foreachclient(struct map_session_data *sd, va_list ap)
+{
+    unsigned int tick = va_arg(ap,unsigned int);
+    if (sd->status.ele_id && sd->ed)
+        elemental_ai_sub_timer(sd->ed,sd,tick);
+
+    return 0;
 }
 
-static int elemental_ai_timer(int tid, unsigned int tick, int id, intptr_t data) {
-	map_foreachpc(elemental_ai_sub_foreachclient,tick);
-	return 0;
+static int elemental_ai_timer(int tid, unsigned int tick, int id, intptr_t data)
+{
+    map_foreachpc(elemental_ai_sub_foreachclient,tick);
+    return 0;
 }
 
-int read_elementaldb(void) {
-	FILE *fp;
-	char line[1024], *p;
-	char *str[26];
-	int i, j = 0, k = 0, ele;
-	struct s_elemental_db *db;
-	struct status_data *status;
-	
-	sprintf(line, "%s/%s", db_path, "elemental_db.txt");
-	memset(elemental_db,0,sizeof(elemental_db));
-	
-	fp = fopen(line, "r");
-	if( !fp ) {
-		ShowError("read_elementaldb : can't read elemental_db.txt\n");
-		return -1;
-	}
-	
-	while( fgets(line, sizeof(line), fp) && j < MAX_ELEMENTAL_CLASS ) {
-		k++;
-		if( line[0] == '/' && line[1] == '/' )
-			continue;
-		
-		if( line[0] == '\0' || line[0] == '\n' || line[0] == '\r')
-			continue;
-		
-		i = 0;
-		p = strtok(line, ",");
-		while( p != NULL && i < 26 ) {
-			str[i++] = p;
-			p = strtok(NULL, ",");
-		}
-		if( i < 26 ) {
-			ShowError("read_elementaldb : Incorrect number of columns at elemental_db.txt line %d.\n", k);
-			continue;
-		}
-		
-		db = &elemental_db[j];
-		db->class_ = atoi(str[0]);
-		strncpy(db->sprite, str[1], NAME_LENGTH);
-		strncpy(db->name, str[2], NAME_LENGTH);
-		db->lv = atoi(str[3]);
-		
-		status = &db->status;
-		db->vd.class_ = db->class_;
-		
-		status->max_hp = atoi(str[4]);
-		status->max_sp = atoi(str[5]);
-		status->rhw.range = atoi(str[6]);
-		status->rhw.atk = atoi(str[7]);
-		status->rhw.atk2 = status->rhw.atk + atoi(str[8]);
-		status->def = atoi(str[9]);
-		status->mdef = atoi(str[10]);
-		status->str = atoi(str[11]);
-		status->agi = atoi(str[12]);
-		status->vit = atoi(str[13]);
-		status->int_ = atoi(str[14]);
-		status->dex = atoi(str[15]);
-		status->luk = atoi(str[16]);
-		db->range2 = atoi(str[17]);
-		db->range3 = atoi(str[18]);
-		status->size = atoi(str[19]);
-		status->race = atoi(str[20]);
-		
-		ele = atoi(str[21]);
-		status->def_ele = ele%10;
-		status->ele_lv = ele/20;
-		if( status->def_ele >= ELE_MAX ) {
-			ShowWarning("Elemental %d has invalid element type %d (max element is %d)\n", db->class_, status->def_ele, ELE_MAX - 1);
-			status->def_ele = ELE_NEUTRAL;
-		}
-		if( status->ele_lv < 1 || status->ele_lv > 4 ) {
-			ShowWarning("Elemental %d has invalid element level %d (max is 4)\n", db->class_, status->ele_lv);
-			status->ele_lv = 1;
-		}
-		
-		status->aspd_rate = 1000;
-		status->speed = atoi(str[22]);
-		status->adelay = atoi(str[23]);
-		status->amotion = atoi(str[24]);
-		status->dmotion = atoi(str[25]);
-		
-		j++;
-	}
-	
-	fclose(fp);
-	ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' elementals in '"CL_WHITE"db/elemental_db.txt"CL_RESET"'.\n",j);
-	
-	return 0;
+int read_elementaldb(void)
+{
+    FILE *fp;
+    char line[1024], *p;
+    char *str[26];
+    int i, j = 0, k = 0, ele;
+    struct s_elemental_db *db;
+    struct status_data *status;
+
+    sprintf(line, "%s/%s", db_path, "elemental_db.txt");
+    memset(elemental_db,0,sizeof(elemental_db));
+
+    fp = fopen(line, "r");
+    if (!fp) {
+        ShowError("read_elementaldb : can't read elemental_db.txt\n");
+        return -1;
+    }
+
+    while (fgets(line, sizeof(line), fp) && j < MAX_ELEMENTAL_CLASS) {
+        k++;
+        if (line[0] == '/' && line[1] == '/')
+            continue;
+
+        if (line[0] == '\0' || line[0] == '\n' || line[0] == '\r')
+            continue;
+
+        i = 0;
+        p = strtok(line, ",");
+        while (p != NULL && i < 26) {
+            str[i++] = p;
+            p = strtok(NULL, ",");
+        }
+        if (i < 26) {
+            ShowError("read_elementaldb : Incorrect number of columns at elemental_db.txt line %d.\n", k);
+            continue;
+        }
+
+        db = &elemental_db[j];
+        db->class_ = atoi(str[0]);
+        strncpy(db->sprite, str[1], NAME_LENGTH);
+        strncpy(db->name, str[2], NAME_LENGTH);
+        db->lv = atoi(str[3]);
+
+        status = &db->status;
+        db->vd.class_ = db->class_;
+
+        status->max_hp = atoi(str[4]);
+        status->max_sp = atoi(str[5]);
+        status->rhw.range = atoi(str[6]);
+        status->rhw.atk = atoi(str[7]);
+        status->rhw.atk2 = status->rhw.atk + atoi(str[8]);
+        status->def = atoi(str[9]);
+        status->mdef = atoi(str[10]);
+        status->str = atoi(str[11]);
+        status->agi = atoi(str[12]);
+        status->vit = atoi(str[13]);
+        status->int_ = atoi(str[14]);
+        status->dex = atoi(str[15]);
+        status->luk = atoi(str[16]);
+        db->range2 = atoi(str[17]);
+        db->range3 = atoi(str[18]);
+        status->size = atoi(str[19]);
+        status->race = atoi(str[20]);
+
+        ele = atoi(str[21]);
+        status->def_ele = ele%10;
+        status->ele_lv = ele/20;
+        if (status->def_ele >= ELE_MAX) {
+            ShowWarning("Elemental %d has invalid element type %d (max element is %d)\n", db->class_, status->def_ele, ELE_MAX - 1);
+            status->def_ele = ELE_NEUTRAL;
+        }
+        if (status->ele_lv < 1 || status->ele_lv > 4) {
+            ShowWarning("Elemental %d has invalid element level %d (max is 4)\n", db->class_, status->ele_lv);
+            status->ele_lv = 1;
+        }
+
+        status->aspd_rate = 1000;
+        status->speed = atoi(str[22]);
+        status->adelay = atoi(str[23]);
+        status->amotion = atoi(str[24]);
+        status->dmotion = atoi(str[25]);
+
+        j++;
+    }
+
+    fclose(fp);
+    ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' elementals in '"CL_WHITE"db/elemental_db.txt"CL_RESET"'.\n",j);
+
+    return 0;
 }
 
-int read_elemental_skilldb(void) {
-	FILE *fp;
-	char line[1024], *p;
-	char *str[4];
-	struct s_elemental_db *db;
-	int i, j = 0, k = 0, class_;
-	int skillid, skilllv, skillmode;
-	
-	sprintf(line, "%s/%s", db_path, "elemental_skill_db.txt");
-	fp = fopen(line, "r");
-	if( !fp ) {
-		ShowError("read_elemental_skilldb : can't read elemental_skill_db.txt\n");
-		return -1;
-	}
-	
-	while( fgets(line, sizeof(line), fp) ) {
-		k++;
-		if( line[0] == '/' && line[1] == '/' )
-			continue;
-
-		if( line[0] == '\0' || line[0] == '\n' || line[0] == '\r')
-			continue; 
-		
-		i = 0;
-		p = strtok(line, ",");
-		while( p != NULL && i < 4 ) {
-			str[i++] = p;
-			p = strtok(NULL, ",");
-		}
-		if( i < 4 ) {
-			ShowError("read_elemental_skilldb : Incorrect number of columns at elemental_skill_db.txt line %d.\n", k);
-			continue;
-		}
-		
-		class_ = atoi(str[0]);
-		ARR_FIND(0, MAX_ELEMENTAL_CLASS, i, class_ == elemental_db[i].class_);
-		if( i == MAX_ELEMENTAL_CLASS ) {
-			ShowError("read_elemental_skilldb : Class not found in elemental_db for skill entry, line %d.\n", k);
-			continue;
-		}
-		
-		skillid = atoi(str[1]);
-		if( skillid < EL_SKILLBASE || skillid >= EL_SKILLBASE + MAX_ELEMENTALSKILL ) {
-			ShowError("read_elemental_skilldb : Skill out of range, line %d.\n", k);
-			continue;
-		}
-		
-		db = &elemental_db[i];
-		skilllv = atoi(str[2]);
-		
-		skillmode = atoi(str[3]);
-		if( skillmode < EL_SKILLMODE_PASIVE || skillmode > EL_SKILLMODE_AGGRESSIVE ) {
-			ShowError("read_elemental_skilldb : Skillmode out of range, line %d.\n",k);
-			continue;
-		}
-		ARR_FIND( 0, MAX_ELESKILLTREE, i, db->skill[i].id == 0 || db->skill[i].id == skillid );
-		if( i == MAX_ELESKILLTREE ) {
-			ShowWarning("Unable to load skill %d into Elemental %d's tree. Maximum number of skills per elemental has been reached.\n", skillid, class_);
-			continue;
-		}
-		db->skill[i].id = skillid;
-		db->skill[i].lv = skilllv;
-		db->skill[i].mode = skillmode;
-		j++;
-	}
-	
-	fclose(fp);
-	ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' entries in '"CL_WHITE"db/elemental_skill_db.txt"CL_RESET"'.\n",j);
-	return 0;
+int read_elemental_skilldb(void)
+{
+    FILE *fp;
+    char line[1024], *p;
+    char *str[4];
+    struct s_elemental_db *db;
+    int i, j = 0, k = 0, class_;
+    int skillid, skilllv, skillmode;
+
+    sprintf(line, "%s/%s", db_path, "elemental_skill_db.txt");
+    fp = fopen(line, "r");
+    if (!fp) {
+        ShowError("read_elemental_skilldb : can't read elemental_skill_db.txt\n");
+        return -1;
+    }
+
+    while (fgets(line, sizeof(line), fp)) {
+        k++;
+        if (line[0] == '/' && line[1] == '/')
+            continue;
+
+        if (line[0] == '\0' || line[0] == '\n' || line[0] == '\r')
+            continue;
+
+        i = 0;
+        p = strtok(line, ",");
+        while (p != NULL && i < 4) {
+            str[i++] = p;
+            p = strtok(NULL, ",");
+        }
+        if (i < 4) {
+            ShowError("read_elemental_skilldb : Incorrect number of columns at elemental_skill_db.txt line %d.\n", k);
+            continue;
+        }
+
+        class_ = atoi(str[0]);
+        ARR_FIND(0, MAX_ELEMENTAL_CLASS, i, class_ == elemental_db[i].class_);
+        if (i == MAX_ELEMENTAL_CLASS) {
+            ShowError("read_elemental_skilldb : Class not found in elemental_db for skill entry, line %d.\n", k);
+            continue;
+        }
+
+        skillid = atoi(str[1]);
+        if (skillid < EL_SKILLBASE || skillid >= EL_SKILLBASE + MAX_ELEMENTALSKILL) {
+            ShowError("read_elemental_skilldb : Skill out of range, line %d.\n", k);
+            continue;
+        }
+
+        db = &elemental_db[i];
+        skilllv = atoi(str[2]);
+
+        skillmode = atoi(str[3]);
+        if (skillmode < EL_SKILLMODE_PASIVE || skillmode > EL_SKILLMODE_AGGRESSIVE) {
+            ShowError("read_elemental_skilldb : Skillmode out of range, line %d.\n",k);
+            continue;
+        }
+        ARR_FIND(0, MAX_ELESKILLTREE, i, db->skill[i].id == 0 || db->skill[i].id == skillid);
+        if (i == MAX_ELESKILLTREE) {
+            ShowWarning("Unable to load skill %d into Elemental %d's tree. Maximum number of skills per elemental has been reached.\n", skillid, class_);
+            continue;
+        }
+        db->skill[i].id = skillid;
+        db->skill[i].lv = skilllv;
+        db->skill[i].mode = skillmode;
+        j++;
+    }
+
+    fclose(fp);
+    ShowStatus("Done reading '"CL_WHITE"%d"CL_RESET"' entries in '"CL_WHITE"db/elemental_skill_db.txt"CL_RESET"'.\n",j);
+    return 0;
 }
 
-void reload_elementaldb(void) {
-	read_elementaldb();
-	reload_elemental_skilldb();
+void reload_elementaldb(void)
+{
+    read_elementaldb();
+    reload_elemental_skilldb();
 }
 
-void reload_elemental_skilldb(void) {
-	read_elemental_skilldb();
+void reload_elemental_skilldb(void)
+{
+    read_elemental_skilldb();
 }
 
-int do_init_elemental(void) {
-	read_elementaldb();
-	read_elemental_skilldb();
-	
-	add_timer_func_list(elemental_ai_timer,"elemental_ai_timer");
-	add_timer_interval(gettick()+MIN_ELETHINKTIME,elemental_ai_timer,0,0,MIN_ELETHINKTIME);
-	
-	return 0;
+int do_init_elemental(void)
+{
+    read_elementaldb();
+    read_elemental_skilldb();
+
+    add_timer_func_list(elemental_ai_timer,"elemental_ai_timer");
+    add_timer_interval(gettick()+MIN_ELETHINKTIME,elemental_ai_timer,0,0,MIN_ELETHINKTIME);
+
+    return 0;
 }
 
-void do_final_elemental(void) {
-	return;
+void do_final_elemental(void)
+{
+    return;
 }

+ 28 - 28
src/map/elemental.h

@@ -20,44 +20,44 @@
 #define EL_SKILLMODE_AGGRESSIVE 0x4
 
 struct elemental_skill {
-	unsigned short id, lv;
-	short mode;
+    unsigned short id, lv;
+    short mode;
 };
 
 struct s_elemental_db {
-	int class_;
-	char sprite[NAME_LENGTH], name[NAME_LENGTH];
-	unsigned short lv;
-	short range2, range3;
-	struct status_data status;
-	struct view_data vd;
-	struct elemental_skill skill[MAX_ELESKILLTREE];
+    int class_;
+    char sprite[NAME_LENGTH], name[NAME_LENGTH];
+    unsigned short lv;
+    short range2, range3;
+    struct status_data status;
+    struct view_data vd;
+    struct elemental_skill skill[MAX_ELESKILLTREE];
 };
 
 extern struct s_elemental_db elemental_db[MAX_ELEMENTAL_CLASS];
 
 struct elemental_data {
-	struct block_list bl;
-	struct unit_data ud;
-	struct view_data *vd;
-	struct status_data base_status, battle_status;
-	struct status_change sc;
-	struct regen_data regen;
-	
-	struct s_elemental_db *db;
-	struct s_elemental elemental;
-	
-	struct map_session_data *master;
-	int summon_timer;
-	int skill_timer;
-	
-	unsigned last_thinktime, last_linktime;
-	short min_chase;
-	int target_id, attacked_id;
+    struct block_list bl;
+    struct unit_data ud;
+    struct view_data *vd;
+    struct status_data base_status, battle_status;
+    struct status_change sc;
+    struct regen_data regen;
+
+    struct s_elemental_db *db;
+    struct s_elemental elemental;
+
+    struct map_session_data *master;
+    int summon_timer;
+    int skill_timer;
+
+    unsigned last_thinktime, last_linktime;
+    short min_chase;
+    int target_id, attacked_id;
 };
 
 bool elemental_class(int class_);
-struct view_data * elemental_get_viewdata(int class_);
+struct view_data *elemental_get_viewdata(int class_);
 
 int elemental_create(struct map_session_data *sd, int class_, unsigned int lifetime);
 int elemental_data_received(struct s_elemental *ele, bool flag);
@@ -76,7 +76,7 @@ int elemental_get_lifetime(struct elemental_data *ed);
 
 int elemental_unlocktarget(struct elemental_data *ed);
 int elemental_skillnotok(int skillid, struct elemental_data *ed);
-int elemental_set_target( struct map_session_data *sd, struct block_list *bl );
+int elemental_set_target(struct map_session_data *sd, struct block_list *bl);
 int elemental_clean_single_effect(struct elemental_data *ed, int skill_num);
 int elemental_clean_effect(struct elemental_data *ed);
 int elemental_action(struct elemental_data *ed, struct block_list *bl, unsigned int tick);

File diff suppressed because it is too large
+ 402 - 421
src/map/guild.c


+ 13 - 13
src/map/guild.h

@@ -15,12 +15,12 @@ struct mob_data;
 
 //For quick linking to a guardian's info. [Skotlex]
 struct guardian_data {
-	int number; //0-MAX_GUARDIANS-1 = Guardians. MAX_GUARDIANS = Emperium.
-	int guild_id;
-	int emblem_id;
-	int guardup_lv; //Level of GD_GUARDUP skill.
-	char guild_name[NAME_LENGTH];
-	struct guild_castle* castle;
+    int number; //0-MAX_GUARDIANS-1 = Guardians. MAX_GUARDIANS = Emperium.
+    int guild_id;
+    int emblem_id;
+    int guardup_lv; //Level of GD_GUARDUP skill.
+    char guild_name[NAME_LENGTH];
+    struct guild_castle *castle;
 };
 
 int guild_skill_get_max(int id);
@@ -35,8 +35,8 @@ struct guild *guild_search(int guild_id);
 struct guild *guild_searchname(char *str);
 struct guild_castle *guild_castle_search(int gcid);
 
-struct guild_castle* guild_mapname2gc(const char* mapname);
-struct guild_castle* guild_mapindex2gc(short mapindex);
+struct guild_castle *guild_mapname2gc(const char *mapname);
+struct guild_castle *guild_mapindex2gc(short mapindex);
 
 struct map_session_data *guild_getavailablesd(struct guild *g);
 int guild_getindex(struct guild *g,int account_id,int char_id);
@@ -55,18 +55,18 @@ int guild_reply_invite(struct map_session_data *sd,int guild_id,int flag);
 void guild_member_joined(struct map_session_data *sd);
 int guild_member_added(int guild_id,int account_id,int char_id,int flag);
 int guild_leave(struct map_session_data *sd,int guild_id,
-	int account_id,int char_id,const char *mes);
+                int account_id,int char_id,const char *mes);
 int guild_member_withdraw(int guild_id,int account_id,int char_id,int flag,
-	const char *name,const char *mes);
+                          const char *name,const char *mes);
 int guild_expulsion(struct map_session_data *sd,int guild_id,
-	int account_id,int char_id,const char *mes);
-int guild_skillup(struct map_session_data* sd, int skill_num);
+                    int account_id,int char_id,const char *mes);
+int guild_skillup(struct map_session_data *sd, int skill_num);
 void guild_block_skill(struct map_session_data *sd, int time);
 int guild_reqalliance(struct map_session_data *sd,struct map_session_data *tsd);
 int guild_reply_reqalliance(struct map_session_data *sd,int account_id,int flag);
 int guild_alliance(int guild_id1,int guild_id2,int account_id1,int account_id2);
 int guild_allianceack(int guild_id1,int guild_id2,int account_id1,int account_id2,
-	int flag,const char *name1,const char *name2);
+                      int flag,const char *name1,const char *name2);
 int guild_delalliance(struct map_session_data *sd,int guild_id,int flag);
 int guild_opposition(struct map_session_data *sd,struct map_session_data *tsd);
 int guild_check_alliance(int guild_id1, int guild_id2, int flag);

Some files were not shown because too many files changed in this diff