File: JFS.cpp

package info (click to toggle)
holotz-castle 1.3.14-9
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 14,632 kB
  • ctags: 4,120
  • sloc: cpp: 21,634; makefile: 160
file content (1254 lines) | stat: -rw-r--r-- 26,488 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
/*
 *  JLib - Jacob's Library.
 *  Copyright (C) 2003, 2004  Juan Carlos Seijo Prez
 * 
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 * 
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 * 
 *  You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the Free
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 *  Juan Carlos Seijo Prez
 *  jacob@mainreactor.net
 */

/** Sistema de ficheros virtual.
 * @file    JFS.cpp
 * @author  Juan Carlos Seijo Prez
 * @date    23/12/2003
 * @version 0.0.1 - 23/12/2003 - Primera versin.
 */

#include <JLib/Util/JFS.h>

// Carga la cabecera
u32 JResourceHeader::Load(JRW &f)
{
  if (0 != f.ReadLE32(&id) &&
			0 != f.ReadLE32(&pid) &&
      0 != f.ReadLE32(&type) &&
      0 != f.ReadLE32(&size) &&
      0 != f.ReadLE32(&flags))
  {
    return 0;
  }

  return 1;
}

// Salva la cebecera
u32 JResourceHeader::Save(JRW &f)
{
  if (0 != f.WriteLE32(&id) &&
			0 != f.WriteLE32(&pid) &&
      0 != f.WriteLE32(&type) &&
      0 != f.WriteLE32(&size) &&
      0 != f.WriteLE32(&flags))
  {
    return 0;
  }

  return 1;
}

u32 JResource::TypeOf(const char *filename)
{
	const int size = 13;
	const char *prefix[size] = {".txt",
															".c",
															".cpp",
															".h",
															".png",
															".tga",
															".jpg",
															".bmp",
															".xpm",
															".wav",
															".spr",
															".ttf",
															".jfs"};
	
	
	u32 types[size] = {JRES_TEXT,
										 JRES_TEXT,
										 JRES_TEXT,
										 JRES_TEXT,
										 JRES_IMAGE,
										 JRES_IMAGE,
										 JRES_IMAGE,
										 JRES_IMAGE,
										 JRES_IMAGE,
										 JRES_SOUND,
										 JRES_IMAGESPRITE,
										 JRES_FONT,
										 JRES_RESOURCEBLOCK};

	for (int i = 0; i < size; ++i)
	{
		if (strstr(filename, prefix[i]))
		{
			return types[i];
		}
	}

	return JRES_BINARY;
}

// Carga el recurso.
u32 JResource::Load(JRW &f, JLoadSave *where)
{
  u32 resp = 0;

  if (0 == (resp |= where->Load(f)))
  {
    loaded = true;
    data = where;
  }

  return resp;
}

bool JFS::ResizeAt(u32 offset, u32 numBytes)
{
	u32 orgPos = resFile.Tell();

	// TODO: Ver si hace falta
	resFile.Close();
	//resFile.Destroy();

	JFile f;
	
	if (!f.Open(resFilename, "r+b"))
	{
		perror("JFS::ResizeAt - No se pudo abrir el fichero");
		return false;
	}

	//	printf("Resizeando en byte %d, %d bytes\n", offset, numBytes);
	if (!f.ResizeAt(offset, numBytes))
	{
		perror("No se pudo cambiar el tamao del fichero");
		f.Close();

		// Deja el jrw como estaba
		resFile.Create(resFilename, "r+b");
		resFile.Seek(orgPos, SEEK_SET);

		return false;
	}
	
	orgPos = f.Pos();
	f.Close();

	// Deja el jrw listo para escribir
	if (!resFile.Create(resFilename, "r+b"))
	{
		perror("JFS::ResizeAt - No se pudo volver a crear e jrw");
		return false;
	}

	resFile.Seek(orgPos, SEEK_SET);

	return true;
}

// Carga la cabecera del fichero
s32 JFS::LoadHeader()
{
	resFile.Seek(0, SEEK_SET);

	// Lee la cabecera
	char ident[9];
	if (!resFile.Read(ident, 8))
	{
		fprintf(stderr, "No se pudo leer la cabecera del fichero %s\n", resFilename.Str());
		return -1;
	}

	ident[8] = '\0';
	
	if (strcmp(ident, JRES_JFS_FILE) != 0)
	{
		fprintf(stderr, "%s no es un fichero JFS\n", resFilename.Str());
		return -2;
	}

	u8 major, minor;
	if (!resFile.Read(&major, 1) || !resFile.Read(&minor, 1))
	{
		fprintf(stderr, "No se pudo leer la versin de %s\n", resFilename.Str());
		return -3;
	}
	
	fprintf(stderr, "%s versin %d.%d\n", ident, major, minor);

	return 0;
}

// Salva la cabecera del fichero
s32 JFS::SaveHeader()
{
	resFile.Seek(0, SEEK_SET);

	// Escribe la cabecera
	if (!resFile.Write(JRES_JFS_FILE, 8))
	{
		fprintf(stderr, "No se pudo leer la cabecera del fichero %s\n", resFilename.Str());
		return -1;
	}

	u8 major = JRES_JFS_MAJOR, minor = JRES_JFS_MINOR;
	if (!resFile.Write(&major, 1) || !resFile.Write(&minor, 1))
	{
		fprintf(stderr, "No se pudo leer la versin de %s\n", resFilename.Str());
		return -3;
	}
	
	fprintf(stderr, "Salvado %s, %s versin %d.%d\n", resFilename.Str(), JRES_JFS_FILE, major, minor);

	return 0;
}

// Carga el ndice de recursos
s32 JFS::LoadIndex()
{
	resFile.Seek(0, SEEK_END);
	fprintf(stderr, "Fin de fichero en %d\n", resFile.Tell());

	// Lee el ndice al final del fichero
	resFile.Seek(-8, SEEK_END);
	fprintf(stderr, "Tamao del ndice en %d\n", resFile.Tell());

	u32 indexSize, indexCount;
	if (!resFile.ReadLE32(&indexSize) || !resFile.ReadLE32(&indexCount))
	{
		fprintf(stderr, "No se pudo cargar el ndice\n");
		return -1;
	}

	resFile.Seek(-indexSize - 8, SEEK_END);

	index.resize(indexCount, 0);
	
	for (u32 i = 0; i < indexCount; ++i)
	{
		index[i] = new JFSIndexEntry;
		if (!index[i])
		{
			// No hay memoria
			return -2;
		} 
		
		index[i]->res = new JResource;

		if (!index[i]->res ||
				!resFile.ReadLE32(&index[i]->offset) ||
				!fprintf(stderr, "Leo en %d el offset %d\n", resFile.Tell() - 4, index[i]->offset) ||
				(0 != index[i]->name.Load(resFile)) ||
				(0 != index[i]->res->Header().Load(resFile)))
		{
			// Error al cargar la entrada
			return -3;
		}
	}

	return 0;
}

// Salva el ndice de recursos
s32 JFS::SaveIndex()
{
	// Escribe el ndice a partir del final del ltimo recurso
	resFile.Seek(index[index.size() - 1]->offset + index[index.size() - 1]->res->Size(), SEEK_SET);
	
	fprintf(stderr, "index[index.size() - 1]->offset = %d, index[index.size() - 1]->res->Header().size = %d\n", index[index.size() - 1]->offset, index[index.size() - 1]->res->Header().size);

	u32 curPos = resFile.Tell();
	
	for (u32 i = 0; i < index.size(); ++i)
	{
		fprintf(stderr, "Escribo offset %d en %d, ", index[i]->offset, resFile.Tell());

		if (!index[i] || !resFile.WriteLE32(&index[i]->offset) ||
				(0 != index[i]->name.Save(resFile)) ||
				(0 != index[i]->res->Header().Save(resFile)))
		{
			return -1;
		}

		fprintf(stderr, "acabo en %d\n", resFile.Tell());
	}
	
	u32 indexSize = resFile.Tell() - curPos;
	u32 indexCount = index.size();
	
	curPos = resFile.Tell();
	resFile.Seek(0, SEEK_END);
	fprintf(stderr, "Fin de fichero est en %d\n", resFile.Tell());

	fprintf(stderr, "Escribo indexSize en %d como %d\n", resFile.Tell(), indexSize);

	if (0 == resFile.WriteLE32(&indexSize) || 0 == resFile.WriteLE32(&indexCount))
	{
		fprintf(stderr, "OOops, hubo un fallo gordo no se pudo salvar el tamao o el count\n");
		return -2;
	}

	fprintf(stderr, "Fin de fichero en %d\n", resFile.Tell());

	return 0;
}

// Carga el fichero de recursos
s32 JFS::Load()
{
	s32 ret = 0;

	if (0 != (ret = LoadHeader()))
	{
		fprintf(stderr, "Error cargando la cabecera\n");
		return ret;
	}

	if (0 != (ret = LoadIndex()))
	{
		fprintf(stderr, "Error cargando el ndice\n");
		return ret;
	}

	return 0;
}

// Carga el recurso dado.
u32 JFS::Load(u32 id, JLoadSave *where)
{
	if (id < index.size() && where)
	{
		if (index[id] && index[id]->res)
		{
			if (index[id]->res->data)
			{
				// Ya cargado
				return 1;
			}

			// Se posiciona para cargar el recurso
			resFile.Seek(index[id]->offset, SEEK_SET);
			index[id]->res->data = where;

			return where->Load(resFile);
		}		
	}
	
	// Id o lugar de carga no vlidos
	return 2;
}

// Devuelve el recurso pedido
JLoadSave * JFS::Get(const JString &_name)
{
	for (u32 i = 0;  i < index.size(); ++i)
	{
		if (index[i] && index[i]->name == _name)
		{
			if (index[i]->res)
			{
				return index[i]->res->data;
			}

			// Encontrado pero no cargado
			return 0;
		}
	}

  return 0;
}

// Devuelve el recurso pedido
JLoadSave * JFS::Get(u32 id)
{
	if (id < index.size() && index[id] && index[id]->res)
	{
		return index[id]->res->data;
	}

  return 0;
}

// Borra el recurso dado
bool JFS::Delete(JString &_name)
{
//   JResource *res;
//   bool found = false;

//   for (it->FirstInBranch(); !found && it->HasNext(); it->Next())
//   {
//     res = it->Data();
//     if (res->Type() != JRES_RESOURCEBLOCK && _name == res->Name())
//     {
//       found = true;
//       it->RemoveNode();
//     }
//   }

//   if (found)
//   {
//     return true;
//   }

  return false;
}

u32 JFS::AddToIndex(u32 offset, const JString &name, JResource *res)
{
	if (!res || res->header.id > index.size())
	{
		// ndice fuera de rango o no hay recurso
		return 1;
	}

	JFSIndexEntry *e = new JFSIndexEntry;
	e->offset = offset;
	e->name = name;
	e->res = res;
	
	if (res->header.id == index.size())
	{
		fprintf(stderr, "\n+++ AddToIndex: Al final\n");
		// caso especial, va al final y no hay que ajustar nada
		index.push_back(e);
		return 0;
	}

	fprintf(stderr, "\n+++ AddToIndex: Entre medias\n");

	std::vector<JFSIndexEntry *>::iterator itt = index.begin();
	itt += res->header.id;
	index.insert(itt, e);

	// Actualiza los ndices posteriores
	for (u32 i = res->header.id + 1; i < index.size(); ++i)
	{
		fprintf(stderr, "\n+++ AddToIndex: Actualizo el id de %d\n", i);
		++index[i]->res->Header().id;
	}
		
	return 0;
}

s32 JFS::AddTreeResource(JResource *res)
{
	// Aade el recurso al rbol. Si el nodo actual es un bloque lo hace dentro de l, tras el ltimo nodo;
	// si es un recurso de otro tipo, lo inserta tras l.
	if (it->Data())
	{
		fprintf(stderr, "\nAddTreeResource: El nodo ya tiene datos!\n");
		return -1;
	}
	
	it->Data(res);

	// Asigna el identificador
	if (it->node->prev)
	{
		if (it->node->prev->child)
		{
			// Si el anterior tiene hijos, el id es el prximo al ltimo de la rama
			JTree<JResource *>::Iterator *itTmp = NewIterator(it->node->prev->child);

			do
			{
				itTmp->LastInBranch();
			} while (itTmp->Child());
			
			res->Header().id = itTmp->node->data->Header().id + 1;
			//			fprintf(stderr, "Asigno id de hijo del anterior %d %s\n", itTmp->node->data->Header().id + 1, index[itTmp->node->data->Header().id]->name.Str());

			delete itTmp;
		}
		else
		{
			//			fprintf(stderr, "Asigno id de hijo del anterior %d %s\n", it->node->prev->data->Header().id + 1, index[it->node->prev->data->Header().id]->name.Str());
			res->Header().id = it->node->prev->data->Header().id + 1;
		}
	}
	else
	{
		res->Header().id = it->node->parent->data->Header().id + 1;
	}

	res->Header().pid = it->node->parent->data->Header().id;

	return 0;
}

s32 JFS::AddResource(const char *filename, u32 flags)
{
	JFile importFile;
	
	if (!importFile.Open(filename, "r+b"))
	{
		perror ("No se pudo abrir el fichero a importar");
		return -1;
	}

	// Aade un nuevo recurso al rbol, AddTreeResource calcula su id y su pid
	JResource *res = new JResource;

	if (0 != AddTreeResource(res))
	{
		fprintf(stderr, "No se pudo aadir el nodo al rbol.\n");
		delete res;

		return -2;
	}

	// Estos valores no los conoce AddTreeResource
	res->Header().type = JResource::TypeOf(filename);
	res->Header().flags = flags;

	// El offset es el del elemento con el id anterior
	u32 offset = index[res->Header().id-1]->offset + index[res->Header().id-1]->res->Size();

	fprintf(stderr, "AddResource: offset anterior %d + size anterior %d + hdr size %d\n", index[res->Header().id-1]->offset, index[res->Header().id-1]->res->Size(), index[res->Header().id-1]->res->header.Size());
	fprintf(stderr, "AddResource: Por tanto offset %d\n", offset);

	// Carga el buffer con los datos a salvar
	if (importFile.Size())
	{
		u8 *buff = new u8[importFile.Size()];

		if (!buff)
		{
			fprintf(stderr, "No hay memoria para importar el fichero\n");
			return -3;
		}

		if (0 == importFile.Read(buff, importFile.Size()))
		{
			fprintf(stderr, "Error al leer los datos del fichero a importar\n");
			delete[] buff;
			return -4;
		}

		if (JFS_COMPRESSED(res))
		{
			// Los datos deben comprimirse. Hay que hacerlo en memoria pues no sabemos a priori
			// cunto ocuparn
			u32 sizeComp, size;
      unsigned long sizeUL, sizeCompUL;
			size = importFile.Size();
      sizeUL = size;

      // Zlib header says it can be computed with compressBounds but if so, it fails to compress2.
      // ZLib manual says that it must be 0.1% plus 12 bytes larger 8-?
			sizeComp = compressBound(size);
      sizeCompUL = sizeComp;
      
      printf("---> sizeComp es %lu, (uLongf*)&sizeComp es %lu\n", sizeUL, *((uLongf*)&sizeUL));

			unsigned char *buffComp = new unsigned char[sizeComp + 8];
	
			if (!buffComp)
			{
				delete[] buff;
				return -5;
			}
		
      s32 ret;
			if (Z_OK != (ret = compress2((Bytef*)buffComp, (uLongf*)&sizeCompUL, (Bytef*)buff, sizeUL, compressionLevel)))
			{
        printf("ret=%d, Z_MEM_ERROR=%d, Z_BUF_ERROR=%d, Z_STREAM_ERROR=%d\n", ret, Z_MEM_ERROR, Z_BUF_ERROR, Z_STREAM_ERROR);
				delete[] buff;
				delete[] buffComp;
				return -6;
			}

      sizeComp = (u32)sizeCompUL;

			res->Header().size = sizeof(size) + sizeof(sizeComp) + sizeComp;

			// Hace crecer el fichero de recursos desde la posicin posterior al recurso actual.
			if (!ResizeAt(offset, res->Size()))
			{
				delete[] buff;
				delete[] buffComp;
				return -7;
			}
		
			// Tamao original + Tamao comprimido + datos comprimidos
			// Esto lo guarda en el formato que espera ZRead al cargar
			if (0 == resFile.WriteLE32(&size) || 0 == resFile.WriteLE32(&sizeComp) ||
					0 == resFile.Write(buffComp, sizeComp))
			{
				delete[] buff;
				delete[] buffComp;
				return -8;
			}
		
			delete[] buffComp;
		}
		else
		{
			res->Header().size = importFile.Size();

			if (!ResizeAt(offset, res->Size()))
			{
				delete[] buff;
				return -10;
			}

			if (0 == resFile.Write(buff, res->Header().size))
			{
				delete[] buff;
				return -11;
			}
		}

		delete[] buff;
	}
	else
	{
		// Fichero vaco
		res->Header().size = 0;
	}

	// Aade la entrada nueva al ndice y ajusta las entradas por detrs
	AddToIndex(offset, filename, res);

	return 0;
}

s32 JFS::AddBlock(const char *name)
{
	// Aade el recurso al rbol. Si el nodo actual es un bloque lo hace dentro de l, tras el ltimo nodo;
	// si es un recurso de otro tipo, lo inserta tras l.
	JResource *res = new JResource;

	if (0 != AddTreeResource(res))
	{
		fprintf(stderr, "Error al aadir un bloque al rbol.\n");
		delete res;

		return -1;
	}

	// Esta informacin no la conoce AddTreeBlock
	res->header.type = JRES_RESOURCEBLOCK;
	res->header.flags = JRES_FLAGS_BLOCK_OPENED;
	res->header.size = 0;

	// El offset es el del elemento con el id anterior
	u32 offset = index[res->header.id-1]->offset + index[res->header.id-1]->res->Size();

	// Hace crecer el fichero de recursos desde la posicin posterior al recurso actual.
	if (!ResizeAt(offset, res->Size()))
	{
		fprintf(stderr, "Error al hacer resize!\n");
		return -10;
	}

  fprintf(stderr, "Aado al ndice el bloque.\n");

	// Aade la entrada nueva al ndice y ajusta las entradas por detrs
	AddToIndex(offset, name, res);

	return 0;
}

s32 JFS::BuildTree()
{
	if (!index.size())
	{
		// No hay ndice
		fprintf(stderr, "BuildTree: No hay un ndice cargado!\n");
		return -1;
	}

	// Borra todo el rbol
	it->Root();
	it->RemoveNode();
	
	if (it->Data())
	{
		delete it->Data();
		it->Data(0);
	}
	
	// Organiza los recursos en forma de rbol
	u32 i;
	u32 pid = 0;

	for (i = 0; i < index.size() - 1; ++i)
	{
		it->Data(index[i]->res);
		pid = index[i + 1]->res->Header().pid;

		if (index[i]->res->Header().type == JRES_RESOURCEBLOCK && pid == index[i]->res->Header().id)
		{
			// Recurso actual es bloque y tiene hijos
			it->AddBranchGo(0);
		}
		else
		if (pid == index[i]->res->Header().pid)
		{
			// Siguiente recurso al mismo nivel que el actual
			it->AddNodeGo(0);
		}
		else
		{
			while (it->Parent() && it->node->data->header.pid != pid)
			{}
			
			it->LastInBranch();
			it->AddNodeGo(0);
		}
	}
	
	it->Data(index[i]->res);
	
	return 0;
}

s32 JFS::Open(const char *_name, bool edit)
{
	if (!_name || ! JFile::Exists(_name))
	{
		// Nombre nulo o no exists el fichero
		return -1;
	}

	char str[4096];
	getcwd(str, sizeof(str));
	
	resFilename = str;
	resFilename += "/";
	resFilename += _name;
	
	if (!resFile.Create(resFilename, "r+b"))
	{
		// No se pudo abrir el fichero
		return -2;
	}
	
	if (0 != Load())
	{
		return -3;
	}

	if (it)
	{
		delete it;
	}
	
	it = NewIterator();
	it->Data(0);

	return BuildTree();
}

s32 JFS::Create(const char *_name)
{
	if (!_name)
	{
		// Nombre nulo
		return -1;
	}

	char str[4096];
	getcwd(str, sizeof(str));
	
	resFilename = str;
	resFilename += "/";
	resFilename += _name;
	
	if (!resFile.Create(resFilename, "w+b"))
	{
		// No se pudo abrir el fichero
		return -2;
	}
	
	if (0 != SaveHeader())
	{
		// No se pudo salvar la cabecera
		return -3;
	}

	// ndice vaco inicialmente
	u32 indexSize = 0, indexCount = 0;
	if (0 == resFile.WriteLE32(&indexSize) || 
			0 == resFile.WriteLE32(&indexCount))
	{
		return -4;
	}

	// Adicin manual del primer recurso
	root->data = new JResource;
	root->data->header.id = 0;
	root->data->header.pid = 0;
	root->data->header.type = JRES_RESOURCEBLOCK;
	root->data->header.flags = JRES_FLAGS_BLOCK_OPENED;
	root->data->header.size = 0;
	
	// El offset es el tamao de la cabecera
	u32 offset = JRES_JFS_HEADER_SIZE;

	// Hace crecer el fichero de recursos desde la posicin posterior al recurso actual.
	if (!ResizeAt(offset, root->data->Size()))
	{
		return -10;
	}
		
	AddToIndex(JRES_JFS_HEADER_SIZE, _name, root->data);
	
	SaveIndex();

	if (it)
	{
		delete it;
	}
	
	it = NewIterator();
	
	return 0;
}

s32 JFS::Import(const char *filename, JTree<JResource *>::Node *where, bool after)
{
	static s32 depth = 0;
	fprintf(stderr, "Recursin %d, size es %d importo %s\n", depth, Size(), filename);
	
	char str[256];
	getcwd(str, 256);
	printf("CWD es %s\n", str);

	if (!filename || resFilename == "")
	{
		return -2;
	}

	if (depth == 0)
	{
		if (it)
		{
			delete it;
		}

		// Si nos dan un nodo (se asume que es de este rbol) mueve el iterador interno a esa posicin,
		// si no, se posicionar el iterador al comienzo del rbol
		it = NewIterator(where);
	}

	printf("Depth es %d!\n", depth);

	if (JFile::IsDir(filename))
	{
		if (depth == 0)
		{
			if (JFS_BLOCKOPENED(it->Data()) || it->node == root)
			{
				printf("Aado rama inicial!\n");

				// Si es un bloque abierto o root
				if (it->Child())
				{
					// Tiene ya elementos, inserta antes del primero
					it->AddNodeGo(0, false);
				}
				else
				{
					// No tiene elementos, aade uno dentro
					it->AddBranchGo(0);
				}
			}
			else
			{
				printf("Aado nodo inicial!\n");

				// Bloque cerrado distinto de root o nodo, lo aade tras ste
				it->AddNodeGo(0, after);
			}
		}

		++depth;

		AddBlock(filename);
		fprintf(stderr, "Importando directorio: %*c%s\n", it->node->depth+1, '.', filename);

		s32 n, k;

		// Si es un directorio lo importa recursivamente
		struct dirent **namelist;
		n = scandir(filename, &namelist, 0, alphasort);

		if (n < 0)
		{
			perror("scandir");
			it->Parent();
			--depth;
			return -1;
		}
		
		s32 num = 0;

		if (n > 0)
		{
			chdir(filename);
			getcwd(str, 256);
			printf("CWD es %s\n", str);

			// Aade una entrada vaca para el primer elemento del directorio
			printf("Aado rama nueva al directorio!\n");
			it->AddBranchGo(0);

			// index[itt->node->data->Header().id]->name.Str()

			k = 0;
			while (k < n)
			{
				if (JFile::IsFile(namelist[k]->d_name) || (JFile::IsDir(namelist[k]->d_name) && (0 != strcmp(namelist[k]->d_name, ".") && 0 != strcmp(namelist[k]->d_name, ".."))))
				{
					++num;

					// Procesa recursivamente sus elementos
					printf("Voy a importar %s\n", namelist[k]->d_name);
					Import(namelist[k]->d_name);
					it->AddNodeGo(0);
				}
				free(namelist[k]);
				
				++k;
			}
			printf("No hay ms elementos en %s\n", filename);

			// el ltimo nodo (o la rama si el directorio estaba vaco) est vaco, lo borra
			if (it->Data())
			{
				printf("Horror, FALLO!!\n");
			}
			else
			{
				it->RemoveNode();
			}
			
			free(namelist);
			chdir("..");
			getcwd(str, 256);
			printf("CWD es %s\n", str);
		}

		//		printf("it->Parent()\n");
		if (num)
		{
			// Slo pasa al padre si se importaron elementos del directorio pues si no
			// ya estamos en el padre tras hacer RemoveNode
			it->Parent();
		}
	}
	else if (JFile::IsFile(filename))
	{
		if (depth == 0)
		{
			if (JFS_BLOCKOPENED(it->Data()) || it->node == root)
			{
				printf("Aado rama!\n");

				// Si es un bloque abierto o root
				if (it->Child())
				{
					// Tiene ya elementos, inserta antes del primero
					it->AddNodeGo(0, false);
				}
				else
				{
					// No tiene elementos, aade uno dentro
					it->AddBranchGo(0);
				}
			}
			else
			{
				printf("Aado nodo!\n");

				// Bloque cerrado distinto de root o nodo, lo aade tras ste
				it->AddNodeGo(0, after);
			}
		}

		++depth;

		s32 ret = AddResource(filename, defaultFlags);

		fprintf(stderr, "Importando archivo: %s depth=%d, Addresource()=%d\n", filename, it->node->depth, ret);
	}

	if (!it->Data())
	{
		printf("-----> Nodo vaco, lo quito!! <-----\n");
		it->RemoveNode();
	}

	--depth;
	
	if (depth == 0)
	{
		// tras la ltima entrada actualiza el ndice en disco
		return SaveIndex();
	}
	
	return 0;
}

s32 JFS::Export()
{
	JString dirName;
	int i = 1;
	
	// Busca un subdirectorio que no exista para exportar
	do
	{
		dirName.Format("export%d", i++);
	}	while(JFile::Exists(dirName));
	
// 	char str[256];
// 	getcwd(str, 256);
// 	printf("Estoy en %s\n", str);
// 	printf("Creo %s\n", dirName.Str());

#ifndef _WIN32
	if (0 != mkdir(dirName, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
#else
	if (0 != mkdir(dirName))
#endif //_WIN32
	{
		perror("Error creating export base directory");
		return -1;
	}
	
	chdir(dirName);
	
	// No exporta el nodo raz
	u32 id, lastPid;
	for (id = 1, lastPid = 0; id < index.size(); ++id)
	{
		//		printf("Lastpid es %s, cur.pid es %s\n", index[lastPid]->name.Str(), index[index[id]->res->Header().pid]->name.Str());

		while (lastPid && lastPid >= index[id]->res->Header().pid)
		{
			// Sube un directorio hasta que el padre sea el mismo que el del recurso actual
			//			getcwd(str, 256);
			//			printf("Estoy en %s\n", str);
			chdir("..");
			lastPid = index[lastPid]->res->Header().pid;
			//getcwd(str, 256);
			//printf("Subo a %s\n", str);
		}
		//printf("Ahora lastpid es %s, cur.pid es %s\n", index[lastPid]->name.Str(), index[index[id]->res->Header().pid]->name.Str());

		if (JFS_IS_BLOCK(index[id]->res))
		{
			// Bloque, slo crea un directorio
			dirName = index[id]->name;

			//printf("Creo %s\n", dirName.Str());

#ifndef _WIN32
	    if (0 != mkdir(dirName, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
#else
	    if (0 != mkdir(dirName))
#endif //_WIN32
			{
				perror("Error creating directory");
				printf("%s\n", dirName.Str());
				return -1;
			}

			int ret = chdir(dirName);

			//getcwd(str, 256);
			//printf("Cambio a %s\n", str);

			if (ret != 0)
			{
				perror("chdir fall");
			}
			else
			{
				// Cambio de padre
				lastPid = index[id]->res->Header().pid;
			}
		}
		else
		{
			//char str[256];
			//getcwd(str, 256);
			//printf("Estoy en %s\n", str);
		
			//printf("Creo archivo %s size es %d\n", index[id]->name.Str(), index[id]->res->Header().size);

			// Abre el fichero de destino
			JFile f;
			if (!f.Open(index[id]->name, "w+b"))
			{
				return -3;
			}
			
			// Fichero regular (pronto tambin links... :)
			// Este es el mismo cdigo que para cargar un recurso
			resFile.Seek(index[id]->offset, SEEK_SET);
		
			if (index[id]->res->Header().size)
			{
				u8 *buff;
				u32 size;

				// Lee los datos desde el formato adecuado
				if (JFS_COMPRESSED(index[id]->res))
				{
					if (0 == (size = resFile.ZRead(&buff)))
					{
						fprintf(stderr, "JFS::Export - Error reading compressed resource\n");
						delete[] buff;
						
						return -4;
					}
				}
				else
				{
					size = index[id]->res->Header().size;
					buff = new u8[size];
					
					if (0 == resFile.Read(buff, size))
					{
						fprintf(stderr, "JFS::Export - Error reading resource\n");
						delete[] buff;
						
						return -5;
					}
				}


				// Escribe el fichero de destino
				if (!f.Write(buff, size))
				{
					delete[] buff;
					return -6;
				}

				delete[] buff;
			}
		}
	}

	while (lastPid && lastPid > 0)
	{
		// Sube un directorio hasta que el padre sea el mismo que el del recurso actual
		//getcwd(str, 256);
		//printf("FIN: Estoy en %s\n", str);
		chdir("..");
		lastPid = index[lastPid]->res->Header().pid;
		//getcwd(str, 256);
		//printf("FIN: Cambio a %s\n", str);
	}
	
	chdir("..");
	//getcwd(str, 256);
	//printf(".. a %s\n", str);
	chdir("..");
	//getcwd(str, 256);
	//printf("2 .. a %s\n", str);
	
	return 0;
}

const JString JFS::FilenameFromId(const char *name)
{
	JString ret = name;
	ret.Lowercase();
	s32 dotPos = ret.FindLast('_');

	// Pone el punto de la extensin (esto no funciona en id's que provengan de archivos con espacios sin extensin)
	if (dotPos >= 0)
	{
		ret[dotPos] = '.';
	}

	return ret;
}

const JString JFS::IdFromFilename(const char *name)
{
	JString ret;
	if (prefix.Length())
	{
		ret = prefix + "_" + name;
	}
	else
	{
		ret = name;
	}

	ret.Uppercase();
	ret.Replace(' ', '_');
	ret.Replace('.', '_');
	ret.Replace('-', '_');
	
	return ret;
}

bool JFS::ExportIndex(const char *filename)
{
	JTextFile f;
	if (!f.Open(filename, "w+b"))
	{
		perror("JFS::ExportIndex");
		return false;
	}
	
	if (!f.PrintLine(JRES_JFS_EXPORT_VERSION) ||
			!f.PrintLine(JRES_JFS_EXPORT_WARNING) ||
			!f.PrintLine(JRES_JFS_EXPORT_BEGIN"\n"))
	{
		perror("JFS::ExportIndex");
		return false;
	}
	
	char str[4096];
	JString exportName;
	s32 j = 0;

	for (u32 i = 0; i < index.size(); ++i)
	{
		exportName = IdFromFilename(index[i]->name.Str());

		j = index[i]->res->Header().pid;

		while (j > 0)
		{
			exportName = IdFromFilename(index[j]->name.Str()) + ("_" + exportName);
			j = index[j]->res->Header().pid;
		} 

		snprintf(str, sizeof(str), "#define %-40s %d", exportName.Str(), i);
		if (!f.PrintLine(str))
		{
			perror("JFS::ExportIndex");
			return false;
		}
	}

	if (!f.PrintLine("\n"JRES_JFS_EXPORT_END))
	{
		perror("JFS::ExportIndex");
		return false;
	}
	
	return true;
}