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
#include "gate/gatemain.h"
#include "gate/files.h"
#include "gate/results.h"
#include "gate/applications.h"
#include "gate/debugging.h"
#include "gate/strings.h"
#include "gate/console.h"
#include "gate/environments.h"
#include "gate/system/storagedrives.h"
#include "gate/tech/filesystems.h"

#if defined(GATE_COMPILER_MSVC) && defined(GATE_LEAK_DETECTION) && defined(GATE_SYS_WIN) && !defined(GATE_SYS_WINCE) && (GATE_ARCH != GATE_ARCH_ARM32) && (GATE_ARCH != GATE_ARCH_ARM64)
#	include <vld.h>
#endif

typedef struct storedrv_args_class
{
    gate_bool_t		list;
    gate_string_t	read_storagedrive_uid;
    gate_string_t	write_storagedrive_uid;
    gate_string_t	writeverify_storagedrive_uid;
    gate_int64_t	block_index;
    gate_int64_t	block_count;
    gate_string_t	file_path;
    gate_int64_t	file_offset;
    gate_string_t	fat_list;
    gate_string_t	fat_read;
    gate_string_t	fat_path;
    gate_bool_t		image;
    gate_bool_t		show_help;
} storedrv_args_t;

static storedrv_args_t storedrv_args;
static gate_app_option_t storedrv_options[] =
{
    GATE_APP_OPTION_INIT_STATIC("list", GATE_APP_OPTION_TYPE_SWITCH, &storedrv_args.list, "L", "list", "Lists all storage drives"),
    GATE_APP_OPTION_INIT_STATIC("read", GATE_APP_OPTION_TYPE_STRING, &storedrv_args.read_storagedrive_uid, "R", "read_storagedrive_uid", "Reads blocks from storage drive with given UID"),
    GATE_APP_OPTION_INIT_STATIC("write", GATE_APP_OPTION_TYPE_STRING, &storedrv_args.write_storagedrive_uid, "W", "write_storagedrive_uid", "Writes blocks to storage drive with given UID"),
    GATE_APP_OPTION_INIT_STATIC("writeverify", GATE_APP_OPTION_TYPE_STRING, &storedrv_args.writeverify_storagedrive_uid, "WV", "writeverify_storagedrive_uid", "Writes to all blocks of drive with given UID and verifies afterwards"),
    GATE_APP_OPTION_INIT_STATIC("block", GATE_APP_OPTION_TYPE_I64, &storedrv_args.block_index, "B", "block_index", "Block index where drive operation starts"),
    GATE_APP_OPTION_INIT_STATIC("count", GATE_APP_OPTION_TYPE_I64, &storedrv_args.block_count, "C", "block_count", "Amount of drive blocks to process"),
    GATE_APP_OPTION_INIT_STATIC("file", GATE_APP_OPTION_TYPE_STRING, &storedrv_args.file_path, "F", "file_path", "Path to file to read or write data"),
    GATE_APP_OPTION_INIT_STATIC("offset", GATE_APP_OPTION_TYPE_I64, &storedrv_args.file_offset, "O", "file_offset", "Byte offset in target file where operation starts"),
    GATE_APP_OPTION_INIT_STATIC("fatlist", GATE_APP_OPTION_TYPE_STRING, &storedrv_args.fat_list, "FL", "read_storagedrive_uid", "List root entries of a FAT filesystem"),
    GATE_APP_OPTION_INIT_STATIC("fatread", GATE_APP_OPTION_TYPE_STRING, &storedrv_args.fat_read, "FR", "read_storagedrive_uid", "Reads a file in a FAT filesystem"),
    GATE_APP_OPTION_INIT_STATIC("fatpath", GATE_APP_OPTION_TYPE_STRING, &storedrv_args.fat_path, "FP", "fat_filepath", "Path to FAT file to access"),
    GATE_APP_OPTION_INIT_STATIC("image", GATE_APP_OPTION_TYPE_SWITCH, &storedrv_args.image, "I", "use_image", "Use image file path instead of storage UID"),

    GATE_APP_OPTION_INIT_STATIC("help", GATE_APP_OPTION_TYPE_SWITCH, &storedrv_args.show_help, "?", "show_help", "Shows help")
};
static gate_size_t storedrv_options_count = sizeof(storedrv_options) / sizeof(storedrv_options[0]);

static void release_storedrv_args(storedrv_args_t* args)
{
    args->list = false;
    gate_string_release(&args->read_storagedrive_uid);
    gate_string_release(&args->write_storagedrive_uid);
    args->block_index = 0;
    args->block_count = 0;
    gate_string_release(&args->file_path);
    args->show_help = false;
}

static gate_bool_t smart_attribs_callback(
    gate_storagedrive_t const* drive, gate_enumint_t attrib_type,
    gate_int64_t const* values, gate_size_t values_count,
    char const* const* texts, gate_size_t texts_count, void* user_param)
{
    gate_stream_t* strm = (gate_stream_t*)user_param;
    char buffer[32];
    gate_strbuilder_t builder;
    gate_uint8_t id = 0;
    gate_uint16_t raw_high = 0;
    gate_uint32_t raw_low = 0;
    gate_uint64_t curvalue = 0;
    gate_uint64_t worstvalue = 0;
    gate_uint64_t thresvalue = 0;
    char const* info_text = NULL;

    GATE_UNUSED_ARG(drive);
    GATE_UNUSED_ARG(attrib_type);

    if (texts_count > 0) info_text = texts[0];

    if (values_count > GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_ID) id = (gate_uint8_t)values[GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_ID];
    if (values_count > GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_RAW) raw_high = (gate_uint16_t)((gate_uint64_t)values[GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_RAW] >> 32);
    if (values_count > GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_RAW) raw_low = (gate_uint32_t)((gate_uint64_t)values[GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_RAW] & 0xffffffff);
    if (values_count > GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_VALUE) curvalue = (gate_uint64_t)values[GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_VALUE];
    if (values_count > GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_WORST) worstvalue = (gate_uint64_t)values[GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_WORST];
    if (values_count > GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_THRESHOLD) thresvalue = (gate_uint64_t)values[GATE_STORAGEDRIVE_ATTRIBINDEX_SMART_THRESHOLD];

    gate_strbuilder_create_static(&builder, buffer, sizeof(buffer), 0);
    gate_str_print_uint(&buffer[0], 16, curvalue, 3);
    buffer[3] = '/';
    gate_str_print_uint(&buffer[4], 16, worstvalue, 3);
    buffer[7] = '/';
    gate_str_print_uint(&buffer[8], 16, thresvalue, 3);
    buffer[11] = '/';
    gate_str_print_hex_uint16(&buffer[12], 5, raw_high, false);
    gate_str_print_hex_uint32(&buffer[16], 9, raw_low, false);

    gate_stream_print(strm,
        GATE_PRINT_CSTR, "\t\t",
        GATE_PRINT_H8, id,
        GATE_PRINT_CSTR, ": ",
        GATE_PRINT_CSTR, buffer,
        GATE_PRINT_CSTR, "\t",
        GATE_PRINT_CSTR, info_text,
        GATE_PRINT_NEWLINE,
        GATE_PRINT_END);

    return true;
}

static gate_bool_t list_callback(gate_storagedrive_t const* drive, void* user_param)
{
    gate_console_t* con = gate_console();
    gate_stream_t* strm = (gate_stream_t*)con;
    char const* drive_type_text = "Unknown";

    GATE_UNUSED_ARG(user_param);

    switch (drive->drivetype)
    {
    case GATE_STORAGEDRIVE_TYPE_STANDARD:	drive_type_text = "Default"; break;
    case GATE_STORAGEDRIVE_TYPE_ROM:		drive_type_text = "ROM"; break;
    case GATE_STORAGEDRIVE_TYPE_REMOVABLE:	drive_type_text = "Removable"; break;
    case GATE_STORAGEDRIVE_TYPE_VIRTUAL:	drive_type_text = "Virtual"; break;
    }

    gate_stream_print(strm,
        GATE_PRINT_CSTR, drive->uid, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "          Name:\t", GATE_PRINT_CSTR, drive->name, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "          Path:\t", GATE_PRINT_CSTR, drive->path, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "        Device:\t", GATE_PRINT_CSTR, drive->devicepath, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "         Index:\t", GATE_PRINT_UI32, drive->deviceindex, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "          Type:\t", GATE_PRINT_CSTR, drive_type_text, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "    Blockcount:\t", GATE_PRINT_UI64, drive->blockcount, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "     Blocksize:\t", GATE_PRINT_UI64, drive->blocksize, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "          Size:\t", GATE_PRINT_UI64, drive->size, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "       Product:\t", GATE_PRINT_CSTR, drive->productname, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "        Vendor:\t", GATE_PRINT_CSTR, drive->vendor, GATE_PRINT_NEWLINE,
        GATE_PRINT_CSTR, "        Serial:\t", GATE_PRINT_CSTR, drive->serial, GATE_PRINT_NEWLINE,
        GATE_PRINT_END);

    if (GATE_STORAGEDRIVE_TYPE_STANDARD == drive->drivetype)
    {
        gate_stream_print(strm,
            GATE_PRINT_CSTR, "    S.M.A.R.T.:\tID: VAL/WST/THR/RAW", GATE_PRINT_NEWLINE,
            GATE_PRINT_END);
        gate_storagedrive_queryattribs(drive, GATE_STORAGEDRIVE_ATTRIBTYPE_SMART, &smart_attribs_callback, strm);
    }
    return true;
}

static gate_result_t read_drive_blocks(
    gate_storagedrive_t const* drive, gate_int64_t start_block, gate_int64_t block_count,
    gate_string_t const* out_file, gate_int64_t file_offset)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_console_t* con = gate_console();
    gate_stream_t* strm = (gate_stream_t*)con;
    gate_filestream_t* out_filestream = NULL;
    gate_stream_t* out_stream = NULL;
    gate_controlstream_t* in_stream = NULL;
    gate_int64_t ndx;
    gate_int64_t start_pos;
    gate_uint64_t total_bytes_processed = 0;
    gate_size_t bytes_processed;
    char local_buffer[4096];
    char* copy_buffer = NULL;
    gate_size_t copy_buffer_len = (gate_size_t)drive->blocksize;

    do
    {
        if (copy_buffer_len > sizeof(local_buffer))
        {
            copy_buffer = (char*)gate_mem_alloc(copy_buffer_len);
            if (NULL == copy_buffer)
            {
                gate_console_println_err(con, "Failed to allocate copy buffer");
                ret = GATE_RESULT_OUTOFMEMORY;
                break;
            }
        }
        else
        {
            copy_buffer = &local_buffer[0];
        }

        if ((start_block < 0) || (start_block >= (gate_int64_t)drive->blockcount))
        {
            gate_console_println_err(con, "Start block out of bounds");
            ret = GATE_RESULT_INVALIDARG;
            break;
        }
        if (block_count == 0)
        {
            block_count = (gate_int64_t)drive->blockcount - start_block;
        }

        /* open storage drive input stream: */
        ret = gate_storagedrive_openstream(drive, GATE_STREAM_OPEN_READ, &in_stream);
        if (GATE_FAILED(ret))
        {
            gate_console_println_err(con, "Failed to open storage drive input stream");
            break;
        }

        start_pos = start_block * (gate_int64_t)drive->blocksize;
        ret = gate_stream_seek(in_stream, start_pos, GATE_STREAM_SEEK_BEGIN, NULL);
        if (GATE_FAILED(ret))
        {
            gate_console_println_err(con, "Failed to move storage drive input stream to start position");
            break;
        }

        if (gate_string_is_empty(out_file))
        {
            /* use stdout in case no file was provided: */
            out_stream = strm;
            gate_object_retain(out_stream);
        }
        else
        {
            /* open file output stream: */
            ret = gate_file_openstream(out_file,
                (file_offset == 0) ? GATE_STREAM_OPEN_WRITE : GATE_STREAM_OPEN_APPENDREADWRITE,
                &out_filestream);
            out_stream = (gate_stream_t*)out_filestream;
            if (GATE_FAILED(ret))
            {
                gate_console_println_err(con, "Failed to open file output stream");
                break;
            }
            if (file_offset > 0)
            {
                ret = gate_stream_seek(out_filestream, file_offset, GATE_STREAM_SEEK_BEGIN, &file_offset);
            }
            else if (file_offset < 0)
            {
                ret = gate_stream_seek(out_filestream, file_offset, GATE_STREAM_SEEK_END, &file_offset);
            }
            if (GATE_FAILED(ret))
            {
                gate_console_println_err(con, "Failed to seek target position in file output stream");
                break;
            }
        }

        for (ndx = 0; ndx < block_count; ++ndx)
        {
            ret = gate_stream_read(in_stream, copy_buffer, copy_buffer_len, &bytes_processed);
            if (GATE_FAILED(ret))
            {
                gate_console_println_err(con, "Failed to read from storage drive input stream");
                break;
            }
            if (bytes_processed == 0)
            {
                gate_console_println_err(con, "End of storage drive input stream reached");
                ret = GATE_RESULT_ENDOFSTREAM;
                break;
            }

            ret = gate_stream_write_block(out_stream, copy_buffer, bytes_processed, &bytes_processed);
            if (GATE_FAILED(ret))
            {
                gate_console_println_err(con, "Failed to write to file output stream");
                break;
            }
            total_bytes_processed += bytes_processed;
        }

        if (GATE_FAILED(ret))
        {
            gate_console_print_err_num(con, (gate_int64_t)total_bytes_processed);
            gate_console_println_err(con, " bytes transferred");
        }
    } while (0);

    if (copy_buffer && copy_buffer != &local_buffer[0])
    {
        gate_mem_dealloc(copy_buffer);
    }
    if (out_stream)
    {
        gate_object_release(out_stream);
    }
    if (in_stream)
    {
        gate_object_release(in_stream);
    }

    return ret;
}

static void fill_block(char* ptr_block, gate_size_t const blocklen, gate_uint64_t const block_id)
{
    static gate_size_t const chunklen = sizeof(block_id);
    gate_size_t const cnt = blocklen / chunklen;
    gate_size_t ndx;

    gate_mem_clear(ptr_block, blocklen);
    for (ndx = 0; ndx != cnt; ++ndx)
    {
        gate_mem_copy(ptr_block, &block_id, chunklen);
        ptr_block += chunklen;
    }
}

static gate_result_t writeverify_drive_blocks(gate_storagedrive_t const* drive)
{
    gate_result_t result = GATE_RESULT_FAILED;
    unsigned blocks = 1;
    unsigned try_blocks;
    unsigned ndx;
    unsigned const block_size = (unsigned)drive->blocksize;
    gate_size_t buffer_size;
    char* ptr_buffer = NULL;
    char* ptr_checkbuffer = NULL;
    gate_uint64_t block_id = 0;
    gate_controlstream_t* stream = NULL;
    gate_size_t processed;
    gate_stream_t* con = gate_console_stream();


    while (blocks < 32)
    {
        try_blocks = blocks * 2;
        if (0 != drive->blockcount % try_blocks)
        {
            break;
        }
        blocks = try_blocks;
    }

    do
    {
        buffer_size = (gate_size_t)block_size * blocks;
        ptr_buffer = gate_mem_alloc(buffer_size);
        if (!ptr_buffer)
        {
            result = GATE_RESULT_OUTOFMEMORY;
            break;
        }
        ptr_checkbuffer = gate_mem_alloc(buffer_size);
        if (!ptr_buffer)
        {
            result = GATE_RESULT_OUTOFMEMORY;
            break;
        }

        result = gate_storagedrive_openstream(drive, GATE_STREAM_OPEN_WRITE, &stream);
        GATE_BREAK_IF_FAILED(result);

        gate_stream_print(con,
            GATE_PRINT_CSTR, "Writing data to all blocks of device:", GATE_PRINT_NEWLINE,
            GATE_PRINT_END);

        block_id = 0;
        while (block_id < drive->blockcount)
        {
            gate_stream_print(con,
                GATE_PRINT_CR,
                GATE_PRINT_CSTR, "Writing block #",
                GATE_PRINT_UI64, (block_id + 1),
                GATE_PRINT_CSTR, " of ",
                GATE_PRINT_UI64, drive->blockcount,
                GATE_PRINT_END);

            for (ndx = 0; ndx != blocks; ++ndx)
            {
                fill_block(ptr_buffer + (gate_size_t)ndx * block_size, block_size, block_id);
                ++block_id;
            }

            result = gate_stream_write_block((gate_stream_t*)stream, ptr_buffer, buffer_size, &processed);
            GATE_BREAK_IF_FAILED(result);

            if (processed != buffer_size)
            {
                result = GATE_RESULT_FAILED;
                break;
            }
        }
        if (GATE_FAILED(result))
        {
            gate_stream_print(con,
                GATE_PRINT_NEWLINE,
                GATE_PRINT_CSTR, "Error when block #",
                GATE_PRINT_UI64, (block_id + 1),
                GATE_PRINT_CSTR, " buffer was processed, Byte offset: ",
                GATE_PRINT_UI64, (block_id * (gate_uint64_t)block_size),
                GATE_PRINT_NEWLINE,
                GATE_PRINT_END);
            break;
        }

        gate_stream_print(con,
            GATE_PRINT_NEWLINE,
            GATE_PRINT_END);

        if (stream)
        {
            gate_object_release(stream);
        }

        result = gate_storagedrive_openstream(drive, GATE_STREAM_OPEN_READ, &stream);
        GATE_BREAK_IF_FAILED(result);

        gate_stream_print(con,
            GATE_PRINT_CSTR, "Verifying written data of all blocks on device:", GATE_PRINT_NEWLINE,
            GATE_PRINT_END);


        block_id = 0;

        result = gate_stream_seek(stream, (gate_int64_t)1700000 * (gate_int64_t)block_size, GATE_STREAM_SEEK_BEGIN, NULL);
        GATE_BREAK_IF_FAILED(result);

        while (block_id < drive->blockcount)
        {
            gate_stream_print(con,
                GATE_PRINT_CR,
                GATE_PRINT_CSTR, "Reading block #",
                GATE_PRINT_UI64, (block_id + 1),
                GATE_PRINT_CSTR, " of ",
                GATE_PRINT_UI64, drive->blockcount,
                GATE_PRINT_END);

            for (ndx = 0; ndx != blocks; ++ndx)
            {
                fill_block(ptr_buffer + (gate_size_t)ndx * block_size, block_size, block_id);
                ++block_id;
            }

            result = gate_stream_read_block((gate_stream_t*)stream, ptr_checkbuffer, buffer_size, &processed);
            GATE_BREAK_IF_FAILED(result);

            if (processed != buffer_size)
            {
                result = GATE_RESULT_FAILED;
                break;
            }

            if (0 != gate_mem_compare(ptr_buffer, ptr_checkbuffer, buffer_size))
            {
                gate_stream_print(con,
                    GATE_PRINT_NEWLINE,
                    GATE_PRINT_CSTR, "Error when block #",
                    GATE_PRINT_UI64, (block_id + 1),
                    GATE_PRINT_CSTR, " buffer was verified, Byte offset: ",
                    GATE_PRINT_UI64, (block_id * (gate_uint64_t)block_size),
                    GATE_PRINT_NEWLINE,
                    GATE_PRINT_END);

                result = GATE_RESULT_INVALIDDATA;
                break;
            }
        }
        if (GATE_FAILED(result))
        {
            gate_stream_print(con,
                GATE_PRINT_NEWLINE,
                GATE_PRINT_CSTR, "Error when block #",
                GATE_PRINT_UI64, (block_id + 1),
                GATE_PRINT_CSTR, " buffer was verified, Byte offset: ",
                GATE_PRINT_UI64, (block_id * (gate_uint64_t)block_size),
                GATE_PRINT_NEWLINE,
                GATE_PRINT_END);
        }
        else
        {
            gate_stream_print(con,
                GATE_PRINT_NEWLINE,
                GATE_PRINT_CSTR, "Verification succeeded without errors",
                GATE_PRINT_NEWLINE,
                GATE_PRINT_END);
        }

    } while (0);

    if (stream)
    {
        gate_object_release(stream);
    }

    gate_mem_dealloc(ptr_buffer);
    gate_mem_dealloc(ptr_checkbuffer);

    return result;
}


static gate_result_t write_drive_blocks(
    gate_storagedrive_t const* drive, gate_int64_t start_block, gate_int64_t block_count,
    gate_string_t const* in_file, gate_int64_t file_offset)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_console_t* con = gate_console();
    gate_stream_t* in_stream = NULL;
    gate_filestream_t* in_filestream = NULL;
    gate_controlstream_t* out_stream = NULL;
    gate_int64_t ndx;
    gate_int64_t start_pos;
    gate_uint64_t total_bytes_processed = 0;
    gate_size_t bytes_processed;
    char local_buffer[4096];
    char* copy_buffer = NULL;
    gate_size_t copy_buffer_len = (gate_size_t)drive->blocksize;

    do
    {
        if (copy_buffer_len > sizeof(local_buffer))
        {
            copy_buffer = (char*)gate_mem_alloc(copy_buffer_len);
            if (NULL == copy_buffer)
            {
                gate_console_println_err(con, "Failed to allocate copy buffer");
                ret = GATE_RESULT_OUTOFMEMORY;
                break;
            }
        }
        else
        {
            copy_buffer = &local_buffer[0];
        }

        if ((start_block < 0) || (start_block >= (gate_int64_t)drive->blockcount))
        {
            gate_console_println_err(con, "Start block out of bounds");
            ret = GATE_RESULT_INVALIDARG;
            break;
        }
        if (block_count == 0)
        {
            block_count = (gate_int64_t)drive->blockcount - start_block;
        }

        if (gate_string_is_empty(in_file))
        {
            gate_console_println_err(con, "Missing input file argument");
            ret = GATE_RESULT_INVALIDARG;
            break;
        }

        /* open file input stream: */
        ret = gate_file_openstream(in_file, GATE_STREAM_OPEN_READ, &in_filestream);
        if (GATE_FAILED(ret))
        {
            gate_console_println_err(con, "Failed to open file input stream");
            break;
        }
        in_stream = (gate_stream_t*)in_filestream;
        if (file_offset > 0)
        {
            ret = gate_stream_seek(in_filestream, file_offset, GATE_STREAM_SEEK_BEGIN, &file_offset);
        }
        else if (file_offset < 0)
        {
            ret = gate_stream_seek(in_filestream, file_offset, GATE_STREAM_SEEK_END, &file_offset);
        }
        if (GATE_FAILED(ret))
        {
            gate_console_println_err(con, "Failed to seek start position in file input stream");
            break;
        }

        /* open storage drive output stream: */
        ret = gate_storagedrive_openstream(drive, GATE_STREAM_OPEN_WRITE, &out_stream);
        if (GATE_FAILED(ret))
        {
            gate_console_println_err(con, "Failed to open storage drive output stream");
            break;
        }

        start_pos = start_block * (gate_int64_t)drive->blocksize;
        ret = gate_stream_seek(out_stream, start_pos, GATE_STREAM_SEEK_BEGIN, NULL);
        if (GATE_FAILED(ret))
        {
            gate_console_println_err(con, "Failed to move storage drive output stream to start position");
            break;
        }

        for (ndx = 0; ndx < block_count; ++ndx)
        {
            ret = gate_stream_read(in_stream, copy_buffer, copy_buffer_len, &bytes_processed);
            if (GATE_FAILED(ret))
            {
                gate_console_println_err(con, "Failed to read from file input stream");
                break;
            }
            if (bytes_processed == 0)
            {
                gate_console_println_err(con, "End of file input stream reached");
                ret = GATE_RESULT_ENDOFSTREAM;
                break;
            }

            ret = gate_stream_write_block((gate_stream_t*)out_stream, copy_buffer, bytes_processed, &bytes_processed);
            if (GATE_FAILED(ret))
            {
                gate_console_println_err(con, "Failed to write to storage drive output stream");
                break;
            }
            total_bytes_processed += bytes_processed;
        }

        if (GATE_FAILED(ret))
        {
            gate_console_print_err_num(con, (gate_int64_t)total_bytes_processed);
            gate_console_println_err(con, " bytes transferred");
        }
    } while (0);

    if (copy_buffer && (copy_buffer != &local_buffer[0]))
    {
        gate_mem_dealloc(copy_buffer);
    }
    if (out_stream)
    {
        gate_object_release(out_stream);
    }
    if (in_stream)
    {
        gate_object_release(in_stream);
    }

    return ret;
}

static gate_bool_t fat_root_list_cb(gate_filesystem_fat_direntry_t const* entry, void* user_param)
{
    gate_console_t* con = gate_console();
    gate_stream_t* strm = (gate_stream_t*)con;
    gate_string_t file;
    gate_string_t ext;

    GATE_UNUSED_ARG(user_param);

    gate_string_create_static_len(&file, entry->filename, 8);
    gate_string_create_static_len(&ext, entry->extension, 3);

    gate_stream_print(strm,
        GATE_PRINT_STRING, &file,
        GATE_PRINT_CSTR, ".",
        GATE_PRINT_STRING, &ext,
        GATE_PRINT_CSTR, "\t",
        GATE_PRINT_H16, entry->first_cluster,
        GATE_PRINT_CSTR, "\t",
        GATE_PRINT_UI32, entry->file_size,
        GATE_PRINT_NEWLINE,
        GATE_PRINT_END);
    return true;
}

static gate_result_t fat_list(gate_string_t const* target, gate_bool_t is_image, gate_string_t const* fat_path)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_controlstream_t* ptr_stream = NULL;
    gate_storagedrive_t drive;
    gate_filesystem_fat_bootsect_t bootsect;

    do
    {
        if (is_image)
        {
            ret = gate_file_openstream(target, GATE_STREAM_OPEN_READ, &ptr_stream);
        }
        else
        {
            ret = gate_storagedrive_find(&storedrv_args.read_storagedrive_uid, GATE_STORAGEDRIVE_UID, &drive);
            if (GATE_SUCCEEDED(ret))
            {
                ret = gate_storagedrive_openstream(&drive, GATE_STREAM_OPEN_READ, &ptr_stream);
            }
        }
        GATE_BREAK_IF_FAILED(ret);

        ret = gate_filesystem_read_bootsector(ptr_stream, &bootsect);
        GATE_BREAK_IF_FAILED(ret);

        ret = gate_filesystem_read_fat_directory(ptr_stream, &bootsect, fat_path, &fat_root_list_cb, NULL);
    } while (0);

    if (ptr_stream)
    {
        gate_object_release(ptr_stream);
    }
    return ret;
}

static gate_result_t fat_read(gate_string_t const* target, gate_bool_t is_image, gate_string_t const* fat_path,
    gate_string_t const* outfile)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_controlstream_t* ptr_in_stream = NULL;
    gate_stream_t* ptr_out_stream = NULL;
    gate_storagedrive_t drive;
    gate_filesystem_fat_bootsect_t bootsect;
    gate_filesystem_fat_direntry_t direntry;
    gate_size_t bytes_per_cluster;
    gate_size_t bytes_returned;
    gate_size_t dummy;
    char local_buffer[4096];
    char* ptr_buffer = &local_buffer[0];
    gate_int64_t bytes_processed = 0;
    gate_uint32_t next_cluster;

    do
    {
        if (is_image)
        {
            ret = gate_file_openstream(target, GATE_STREAM_OPEN_READ, &ptr_in_stream);
        }
        else
        {
            ret = gate_storagedrive_find(&storedrv_args.read_storagedrive_uid, GATE_STORAGEDRIVE_UID, &drive);
            if (GATE_SUCCEEDED(ret))
            {
                ret = gate_storagedrive_openstream(&drive, GATE_STREAM_OPEN_READ, &ptr_in_stream);
            }
        }
        GATE_BREAK_IF_FAILED(ret);

        ret = gate_filesystem_read_bootsector(ptr_in_stream, &bootsect);
        GATE_BREAK_IF_FAILED(ret);

        bytes_per_cluster = (gate_size_t)bootsect.bpb.bytes_per_sector * (gate_size_t)bootsect.bpb.sectors_per_cluster;
        if (bytes_per_cluster > sizeof(local_buffer))
        {
            ptr_buffer = (char*)gate_mem_alloc(bytes_per_cluster);
            if (ptr_buffer == NULL)
            {
                ret = GATE_RESULT_OUTOFMEMORY;
                break;
            }
        }

        ret = gate_filesystem_find_fat_file(ptr_in_stream, &bootsect, fat_path, &direntry);
        GATE_BREAK_IF_FAILED(ret);

        if (gate_string_is_empty(outfile))
        {
            ptr_out_stream = (gate_stream_t*)gate_console();
        }
        else
        {
            gate_file_openstream(outfile, GATE_STREAM_OPEN_WRITE, (gate_controlstream_t**)&ptr_out_stream);
        }

        next_cluster = direntry.first_cluster;
        while (bytes_processed < direntry.file_size)
        {
            bytes_returned = 0;
            ret = gate_filesystem_read_fat_cluster(ptr_in_stream, &bootsect, next_cluster, ptr_buffer, bytes_per_cluster, &bytes_returned);
            GATE_BREAK_IF_FAILED(ret);

            bytes_processed += bytes_returned;
            if (bytes_processed > direntry.file_size)
            {
                bytes_returned = bytes_per_cluster - (gate_size_t)(bytes_processed - direntry.file_size);
            }
            ret = gate_stream_write_block(ptr_out_stream, ptr_buffer, bytes_returned, &dummy);
            GATE_BREAK_IF_FAILED(ret);

            ret = gate_filesystem_read_next_fat_entry(ptr_in_stream, &bootsect, next_cluster, &next_cluster);
            if (ret == GATE_RESULT_ENDOFSTREAM)
            {
                ret = GATE_RESULT_OK;
                break;
            }
            GATE_BREAK_IF_FAILED(ret);
        }

    } while (0);

    if (ptr_in_stream)
    {
        gate_object_release(ptr_in_stream);
    }
    if (ptr_out_stream)
    {
        gate_object_release(ptr_out_stream);
    }
    return ret;
}


int gate_main(char const* program, char const* const* arguments, gate_size_t argcount, gate_uintptr_t apphandle)
{
    gate_console_t* con = gate_console();
    gate_stream_t* strm = (gate_stream_t*)con;
    gate_result_t result = GATE_RESULT_OK;
    gate_storagedrive_t drive;

    GATE_UNUSED_ARG(program);
    GATE_UNUSED_ARG(apphandle);

    gate_app_options_parse_strs(arguments, argcount, storedrv_options, storedrv_options_count);

    if (storedrv_args.show_help)
    {
        gate_app_options_print(storedrv_options, storedrv_options_count, strm);
        result = GATE_RESULT_CANCELED;
    }
    else if (storedrv_args.list)
    {
        result = gate_storagedrive_enum(GATE_STORAGEDRIVE_TYPE_ALL, &list_callback, NULL);
    }
    else if (!gate_string_is_empty(&storedrv_args.read_storagedrive_uid))
    {
        result = gate_storagedrive_find(&storedrv_args.read_storagedrive_uid, GATE_STORAGEDRIVE_UID, &drive);
        if (GATE_FAILED(result))
        {
            gate_console_println_err(con, "Failed to find input storage drive");
        }
        else
        {
            result = read_drive_blocks(&drive, storedrv_args.block_index, storedrv_args.block_count, &storedrv_args.file_path, storedrv_args.file_offset);
        }
    }
    else if (!gate_string_is_empty(&storedrv_args.write_storagedrive_uid))
    {
        result = gate_storagedrive_find(&storedrv_args.write_storagedrive_uid, GATE_STORAGEDRIVE_UID, &drive);
        if (GATE_FAILED(result))
        {
            gate_console_println_err(con, "Failed to find output storage drive");
        }
        else
        {
            result = write_drive_blocks(&drive, storedrv_args.block_index, storedrv_args.block_count, &storedrv_args.file_path, storedrv_args.file_offset);
        }
    }
    else if (!gate_string_is_empty(&storedrv_args.writeverify_storagedrive_uid))
    {
        result = gate_storagedrive_find(&storedrv_args.writeverify_storagedrive_uid, GATE_STORAGEDRIVE_UID, &drive);
        if (GATE_FAILED(result))
        {
            gate_console_println_err(con, "Failed to find output storage drive");
        }
        else
        {
            result = writeverify_drive_blocks(&drive);
        }
    }
    else if (!gate_string_is_empty(&storedrv_args.fat_list))
    {
        result = fat_list(&storedrv_args.fat_list, storedrv_args.image, &storedrv_args.fat_path);
        if (GATE_FAILED(result))
        {
            gate_console_println_err(con, "Failed to list storage FAT root entries");
        }
    }
    else if (!gate_string_is_empty(&storedrv_args.fat_read))
    {
        result = fat_read(&storedrv_args.fat_read, storedrv_args.image, &storedrv_args.fat_path, &storedrv_args.file_path);
        if (GATE_FAILED(result))
        {
            gate_console_println_err(con, "Failed to list storage FAT root entries");
        }
    }
    else
    {
        gate_console_println_err(con, "Missing arguments.");
        gate_console_println_err(con, "Use '--help' to list all supported arguments");

        result = GATE_RESULT_INVALIDARG;
    }

    release_storedrv_args(&storedrv_args);
    return GATE_RESULT_TO_EXITCODE(result);
}