Welcome to mirror list, hosted at ThFree Co, Russian Federation.

dumper.c - github.com/ClusterM/famicom-dumper.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 805a673d8cd232c1e4607807a98101819fdbac7d (plain)
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
/* Famicom Dumper/Programmer
 *
 * Copyright notice for this file:
 *  Copyright (C) 2020 Cluster
 *  http://clusterrr.com
 *  clusterrr@clusterrr.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "defines.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <util/delay.h>
#include <inttypes.h>
#include "usart.h"
#include "comm.h"
#include "dumper.h"
#include "crc.h"

static void (*jump_to_bootloader)(void) = (void*)0xF800;
uint16_t flash_buffer_mask = 0xFFC0;

ISR(USART0_RX_vect)
{
  unsigned char b;
  while (UCSR0A & (1<<RXC0))
  {
    b = UDR0;
    comm_proceed(b);
  }
}

static void set_flash_buffer_size(uint16_t value)
{
  // Set maximum number of bytes in multi-byte program
  uint8_t bit_value = 0;
  while (value > 1)
  {
    value >>= 1;
    bit_value++;
  }
  flash_buffer_mask = 0xFFFF << bit_value;
}

static void set_address(uint16_t address)
{
  unsigned char l = address & 0xFF;
  unsigned char h = (address >> 8) & 0xFF;
  
  PORTA = l;
  PORTC = h;
  
  // PPU /A13
  if ((address >> 13) & 1)
    PORTF &= ~(1<<4);
  else
    PORTF |= 1<<4;
}

static inline void set_romsel(uint16_t address)
{
  if (address & 0x8000)
  {
    ROMSEL_LOW;
  } else {
    ROMSEL_HI;
  }
}

static inline void set_coolboy_rd(uint16_t address)
{
  if (address & 0x8000)
  {
    COOLBOY_PORT |= 1<<COOLBOY_WR_PIN;
    COOLBOY_PORT &= ~(1<<COOLBOY_RD_PIN);
  } else {
    COOLBOY_PORT |= 1<<COOLBOY_WR_PIN;
    COOLBOY_PORT |= 1<<COOLBOY_RD_PIN;
  }
}

static inline void set_coolboy_wr(uint16_t address)
{
  if (address & 0x8000)
  {
    COOLBOY_PORT &= ~(1<<COOLBOY_WR_PIN);
    COOLBOY_PORT |= 1<<COOLBOY_RD_PIN;
  } else {
    COOLBOY_PORT |= 1<<COOLBOY_WR_PIN;
    COOLBOY_PORT |= 1<<COOLBOY_RD_PIN;
  }
}

static unsigned char read_prg_byte(uint16_t address)
{
  PHI2_LOW;
  ROMSEL_HI;
  MODE_READ;
  PRG_READ;  
  set_address(address);
  PHI2_HI;
  set_romsel(address); // set /ROMSEL low if need
  set_coolboy_rd(address); // COOLBOY's /oe low if need
  _delay_us(1);
  uint8_t result = PIND;
  ROMSEL_HI;
  set_coolboy_rd(0);
  return result;
}

static unsigned char read_chr_byte(uint16_t address)
{
  PHI2_LOW;
  ROMSEL_HI;
  MODE_READ;
  set_address(address);
  CHR_READ_LOW;
  _delay_us(1);
  uint8_t result = PIND;
  CHR_READ_HI;
  PHI2_HI;
  return result;
}

static void read_prg_send(uint16_t address, uint16_t len)
{
  LED_GREEN_ON;
  comm_start(COMMAND_PRG_READ_RESULT, len);
  while (len > 0)
  {
    comm_send_byte(read_prg_byte(address));
    len--;
    address++;
  }
  set_address(0);
  LED_GREEN_OFF;
}

static void read_chr_send(uint16_t address, uint16_t len)
{
  LED_GREEN_ON;
  comm_start(COMMAND_CHR_READ_RESULT, len);
  while (len > 0)
  {
    comm_send_byte(read_chr_byte(address));
    len--;
    address++;
  }
  set_address(0);
  LED_GREEN_OFF;
}

static void read_prg_crc_send(uint16_t address, uint16_t len)
{
  LED_GREEN_ON;
  uint16_t crc = 0;
  MODE_READ;
  PRG_READ;  
  PHI2_HI;
  set_romsel(address); // set /ROMSEL low if need
  while (len > 0)
  {
    PORTA = address & 0xFF;
    PORTC = (address >> 8) & 0xFF;
    _delay_us(1);
    crc = calc_crc16(crc, PIND);
    len--;
    address++;
  }
  ROMSEL_HI;
  set_address(0);
  comm_start(COMMAND_PRG_READ_RESULT, 2);
  comm_send_byte(crc & 0xFF);
  comm_send_byte((crc >> 8) & 0xFF);
  LED_GREEN_OFF;
}

static void read_chr_crc_send(uint16_t address, uint16_t len)
{
  LED_GREEN_ON;
  uint16_t crc = 0;
  while (len > 0)
  {
    crc = calc_crc16(crc, read_chr_byte(address));
    len--;
    address++;
  }
  set_address(0);
  comm_start(COMMAND_CHR_READ_RESULT, 2);
  comm_send_byte(crc & 0xFF);
  comm_send_byte((crc >> 8) & 0xFF);
  LED_GREEN_OFF;
}

static void write_prg_byte(uint16_t address, uint8_t data)
{
  PHI2_LOW;
  ROMSEL_HI;
  MODE_WRITE;
  PRG_WRITE;
  PORTD = data;
  set_address(address); // PHI2 low, ROMSEL always HIGH
  _delay_us(1);
  
  PHI2_HI;
  set_romsel(address); // ROMSEL is low if need, PHI2 high  
  set_coolboy_wr(address); // COOLBOY's /we is low if need
  
  _delay_us(1); // WRITING
  
  // PHI2 low, ROMSEL high
  PHI2_LOW;
  ROMSEL_HI;
  set_coolboy_wr(0);
  
  // Back to read mode
  _delay_us(1);
  PRG_READ;
  MODE_READ;
  set_address(0);

  // Set phi2 to high state to keep cartridge unreseted
  PHI2_HI;
}

static void write_chr_byte(uint16_t address, uint8_t data)
{
  PHI2_LOW;
  ROMSEL_HI;
  MODE_WRITE;
  PORTD = data;  
  set_address(address); // PHI2 low, ROMSEL always HIGH
  CHR_WRITE_LOW;
    
  _delay_us(1); // WRITING
  
  CHR_WRITE_HI;
  
  MODE_READ;
  set_address(0);
  PHI2_HI;
}

static void write_prg(uint16_t address, uint16_t len, uint8_t* data)
{
  LED_RED_ON;
  while (len > 0)
  {
    write_prg_byte(address, *data);
    address++;
    len--;
    data++;
  }
  LED_RED_OFF;
}

static void write_chr(uint16_t address, uint16_t len, uint8_t* data)
{
  LED_RED_ON;
  while (len > 0)
  {
    write_chr_byte(address, *data);
    address++;
    len--;
    data++;
  }
  LED_RED_OFF;
}

static inline void write_prg_flash_command(uint16_t address, uint8_t data)
{
  write_prg_byte(address | 0x8000, data);
}

static void erase_flash_sector()
{
  LED_RED_ON;
  write_prg_flash_command(0x0000, 0xF0);
  write_prg_flash_command(0x0AAA, 0xAA);
  write_prg_flash_command(0x0555, 0x55);
  write_prg_flash_command(0x0AAA, 0x80);
  write_prg_flash_command(0x0AAA, 0xAA);
  write_prg_flash_command(0x0555, 0x55);
  write_prg_flash_command(0x0000, 0x30);
  
  uint8_t res;
  int16_t last_res = -1;
  TCNT1 = 0;
  // waiting for result
  while (1)
  {
    if (TCNT1 >= 23437) // 3 seconds
    {
      // timeout
      comm_start(COMMAND_FLASH_ERASE_TIMEOUT, 0);
      break;
    }
    res = read_prg_byte(0x8000);
    if ((last_res == -1) || ((res != (last_res & 0xFF))))
    {
      // in progress
      last_res = res;
      continue;
    }
    // done
    if (res == 0xFF)
    {
       // ok
       comm_start(COMMAND_PRG_WRITE_DONE, 0);
       break;
    } else {
       // error
       comm_start(COMMAND_FLASH_ERASE_ERROR, 1);
       comm_send_byte(res);
       break;
    }
  }
  LED_RED_OFF;
}

static void write_flash(uint16_t address, uint16_t len, uint8_t* data)
{
  LED_RED_ON;
  while (len > 0)
  {
    uint16_t count = 0;
    uint8_t* d = data;
    uint16_t a = address;
    uint16_t last_address;
    uint8_t last_data;
    uint16_t address_base = a & flash_buffer_mask;
    while ((len > 0) && ((a & flash_buffer_mask) == address_base))
    {
      if (*d != 0xFF)
        count++;
      a++;
      len--;
      d++;
    }

    if (count)
    {
      write_prg_flash_command(0x0000, 0xF0);
      write_prg_flash_command(0x0AAA, 0xAA);
      write_prg_flash_command(0x0555, 0x55);
      write_prg_flash_command(0x0000, 0x25);
      write_prg_flash_command(0x0000, count-1);

      while (count > 0)
      {
        if (*data != 0xFF)
        {
          write_prg_flash_command(address, *data);
          last_address = address;
          last_data = *data;
          count--;
        }
        address++;
        data++;
      }
    
      write_prg_flash_command(0x0000, 0x29);

      TCNT1 = 0;
      // waiting for result
      while (1)
      {
        if (TCNT1 >= 7812) // 1 second
        {
          // timeout
          comm_start(COMMAND_FLASH_WRITE_TIMEOUT, 0);
          LED_RED_OFF;
          return;
        }
        uint8_t read_1 = read_prg_byte(last_address | 0x8000);
        uint8_t read_2 = read_prg_byte(last_address | 0x8000);
        uint8_t read_3 = read_prg_byte(last_address | 0x8000);
        if (((read_1 ^ read_2) & (1 << 6)) && ((read_2 ^ read_3) & (1 << 6)))
        {
          if (read_1 & (1 << 1))
          {
            comm_start(COMMAND_FLASH_WRITE_ERROR, 3);
            comm_send_byte(read_1);
            comm_send_byte(read_2);
            comm_send_byte(read_3);
            LED_RED_OFF;
            return;
          } else if (read_1 & (1 << 5)) {
            comm_start(COMMAND_FLASH_WRITE_TIMEOUT, 3);
            comm_send_byte(read_1);
            comm_send_byte(read_2);
            comm_send_byte(read_3);
            LED_RED_OFF;
            return;
          }
        } else {
          read_1 = read_prg_byte(last_address | 0x8000);
          read_2 = read_prg_byte(last_address | 0x8000);
          if (read_1 == read_2 && read_2 == last_data)
            break; // ok
        }
      }
    }

    address = a;
    data = d;
  }
  comm_start(COMMAND_PRG_WRITE_DONE, 0);
  LED_RED_OFF;
}

static uint8_t transfer_fds_byte(uint8_t *output, uint8_t input, uint8_t *end_of_head)
{
  TCNT1 = 0;
  while (!IRQ_FIRED)
  {
    // waiting for interrupt
    // timeout 5 secs
    if (TCNT1 >= 39060)
    {
      write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
      comm_start(COMMAND_FDS_TIMEOUT, 0);
      return 0;
    }
  }
  if (output)
    *output = read_prg_byte(FDS_DATA_READ);
  write_prg_byte(FDS_DATA_WRITE, input); // clear interrupt
  uint8_t status = read_prg_byte(FDS_DISK_STATUS);
  if (end_of_head)
    *end_of_head |= (status >> 6) & 1;
  TCNT1 = 0;
  while (IRQ_FIRED)
  {
    // is interrupt flag cleared?
    // timeout 5 secs
    if (TCNT1 >= 39060)
    {
      write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
      comm_start(COMMAND_FDS_TIMEOUT, 0);
      return 0;
    }
  }
  return 1;
}

static uint8_t read_fds_block_send(uint16_t length, uint8_t send, uint8_t *crc_ok, uint8_t *end_of_head, uint16_t *file_size, uint32_t gap_delay)
{
  uint8_t data;
  uint8_t status;
  uint32_t b;

  write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_CONTROL_MOTOR_ON); // motor on without transfer
  if (gap_delay < 30000)
    DELAY_CLOCK(gap_delay);
  else
    DELAY_KILO_CLOCK(gap_delay / 1000);
  if (send)
  {
    LED_GREEN_ON;
    comm_start(COMMAND_FDS_READ_RESULT_BLOCK, length + 2);
  }
  // start transfer, enable IRQ
  write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_CONTROL_MOTOR_ON | FDS_CONTROL_TRANSFER_ON | FDS_CONTROL_IRQ_ON);
  for (b = 0; b < length; b++)
  {
    if (!transfer_fds_byte(&data, 0, end_of_head))
      return 0;
    if (file_size)
    {
      if (b == 13)
        *file_size |= data;
      else if (b == 14)
        *file_size |= data << 8;
    }
    if (send)
      comm_send_byte(data);
  }
  if (!transfer_fds_byte(0, 0, end_of_head))
    return 0;
  write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_CONTROL_MOTOR_ON | FDS_CONTROL_TRANSFER_ON | FDS_CONTROL_IRQ_ON | FDS_CONTROL_CRC); // enable CRC control
  if (!transfer_fds_byte(0, 0, end_of_head))
    return 0;
  status = read_prg_byte(FDS_DISK_STATUS);
  *crc_ok &= ((status >> 4) & 1) ^ 1;
  *end_of_head |= (status >> 6) & 1;
  if (send)
  {
    comm_send_byte(*crc_ok); // CRC check result
    comm_send_byte(*end_of_head); // end of head meet?
  }
  LED_GREEN_OFF;
  return 1; // success
}

static uint8_t write_fds_block(uint8_t *data, uint16_t length, uint32_t gap_delay)
{
  uint8_t end_of_head = 0;
  LED_RED_ON;
  write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_CONTROL_MOTOR_ON); // motor on without transfer
  read_prg_byte(FDS_DRIVE_STATUS); // check if disk is inserted
  write_prg_byte(FDS_CONTROL, FDS_CONTROL_WRITE | FDS_CONTROL_MOTOR_ON); // enable writing without transfer
  if (gap_delay < 30000)
    DELAY_CLOCK(gap_delay);
  else
    DELAY_KILO_CLOCK(gap_delay / 1000);
  write_prg_byte(FDS_DATA_WRITE, 0x00); // write $00
  // start transfer, enable IRQ
  write_prg_byte(FDS_CONTROL, FDS_CONTROL_WRITE | FDS_CONTROL_MOTOR_ON | FDS_CONTROL_TRANSFER_ON | FDS_CONTROL_IRQ_ON);
  transfer_fds_byte(0, 0x80, &end_of_head);  // write $80
  while (length)
  {
    if (end_of_head)
    {
      write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
      comm_start(COMMAND_FDS_END_OF_HEAD, 0);
      return 0;
    }
    if (!transfer_fds_byte(0, *data, &end_of_head))
    {
      write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
      comm_start(COMMAND_FDS_TIMEOUT, 0);
      return 0;
    }
    data++;
    length--;
  }
  if (!transfer_fds_byte(0, 0xFF, &end_of_head))
  {
    write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
    comm_start(COMMAND_FDS_TIMEOUT, 0);
    return 0;
  }
  if (end_of_head)
  {
    write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
    comm_start(COMMAND_FDS_END_OF_HEAD, 0);
    return 0;
  }
  write_prg_byte(FDS_CONTROL, FDS_CONTROL_WRITE | FDS_CONTROL_MOTOR_ON | FDS_CONTROL_TRANSFER_ON | FDS_CONTROL_IRQ_ON | FDS_CONTROL_CRC);  // enable CRC control
  DELAY_CLOCK(FDS_WRITE_CRC_DELAY);
  TCNT1 = 0;
  while (1)
  {
    uint8_t status = read_prg_byte(FDS_DRIVE_STATUS);
    if (!(status & 2))
      break; // ready
    // timeout 1 sec
    if (TCNT1 >= 7812)
    {
      write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
      comm_start(COMMAND_FDS_TIMEOUT, 0);
      return 0;
    }
  }  
  LED_RED_OFF;
  return 1;
}

static void fds_transfer(uint8_t block_read_start, uint8_t block_read_count, uint8_t block_write_count, uint8_t *block_write_ids, uint16_t *write_lengths,
    uint8_t *write_data)
{
  uint8_t crc_ok = 1;
  uint8_t end_of_head = 0;
  uint8_t current_block = 0;
  uint8_t current_writing_block = 0;

  write_prg_byte(FDS_IRQ_CONTROL, 0x00); // disable timer IRQ
  write_prg_byte(FDS_MASTER_IO, 0x01); // enable disk registers
  write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset
  uint8_t ram_adapter_connected = 1;
  write_prg_byte(FDS_EXT_WRITE, 0x00); // Ext. connector
  write_prg_byte(0x0000, 0xFF); // To prevent open bus read
  if ((read_prg_byte(FDS_EXT_READ) & 0x7F) != 0x00)
    ram_adapter_connected = 0;
  write_prg_byte(FDS_EXT_WRITE, 0xFF); // Ext. connector
  write_prg_byte(0x0000, 0x00); // To prevent open bus read
  if ((read_prg_byte(FDS_EXT_READ) & 0x7F) != 0x7F)
    ram_adapter_connected = 0;
  if (!ram_adapter_connected)
  {
    comm_start(COMMAND_FDS_NOT_CONNECTED, 0);
    return;
  }
  if (read_prg_byte(FDS_DRIVE_STATUS) & 1)
  {
    comm_start(COMMAND_FDS_DISK_NOT_INSERTED, 0);
    return;
  }  
  // battery test
  write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_CONTROL_MOTOR_ON); // monor on, unreset
  _delay_ms(100);
  if ((read_prg_byte(FDS_EXT_READ) & 0x80) == 0)
  {
    // battery low
    write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
    comm_start(COMMAND_FDS_BATTERY_LOW, 0);
    return;
  }
  // waiting until drive is rewinded
  TCNT1 = 0;
  uint8_t secs = 0;
  do
  {
    // timeout 15 secs
    if (TCNT1 >= 7812)
    {
      TCNT1 = 0;
      secs++;
      if (secs >= 15)
      {
        write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
        comm_start(COMMAND_FDS_TIMEOUT, 0);
        return;
      }
    }
  } while (!(read_prg_byte(FDS_DRIVE_STATUS) & 2));
  TCNT1 = 0;
  secs = 0;
  do
  {
    // timeout 15 secs
    if (TCNT1 >= 7812)
    {
      TCNT1 = 0;
      secs++;
      if (secs >= 15)
      {
        write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop
        comm_start(COMMAND_FDS_TIMEOUT, 0);
        return;
      }
    }
  } while (read_prg_byte(FDS_DRIVE_STATUS) & 2);

  // disk info block
  if (block_write_count && (current_block == block_write_ids[current_writing_block]))
  {
    // gap delay while writing = ~28300 bits = (~28300 / 8)bits * ~165cycles = ~583687.5
    uint16_t write_length = write_lengths[current_writing_block];
    if (!write_fds_block(write_data, write_length, FDS_WRITE_GAP_BEFORE_FIRST_BLOCK))
      return;
    write_data += write_length;
    current_writing_block++;
    block_write_count--;
  } else
  {
    // gap delay while reading = ~486974 cycles
    if (!read_fds_block_send(56, (current_block >= block_read_start) && block_read_count, &crc_ok, &end_of_head, 0, FDS_READ_GAP_BEFORE_FIRST_BLOCK))
      return;
  }
  if ((current_block >= block_read_start) && block_read_count)
    block_read_count--;
  current_block++;

  if (crc_ok && !end_of_head && (block_read_count || block_write_count))
  {
    // file amount block
    if (block_write_count && (current_block == block_write_ids[current_writing_block]))
    {
      uint16_t write_length = write_lengths[current_writing_block];
      if (!write_fds_block(write_data, write_length, FDS_WRITE_GAP_BETWEEN_BLOCKS))
        return;
      write_data += write_length;
      current_writing_block++;
      block_write_count--;
    } else
    {
      if (!read_fds_block_send(2, (current_block >= block_read_start) && block_read_count, &crc_ok, &end_of_head, 0, FDS_READ_GAP_BETWEEN_BLOCKS))
        return;
    }
    if ((current_block >= block_read_start) && block_read_count)
      block_read_count--;
    current_block++;
  }

  while (crc_ok && !end_of_head && (block_read_count || block_write_count))
  {
    // file header block
    uint16_t file_size = 0; // size of the next file
    if (block_write_count && (current_block == block_write_ids[current_writing_block]))
    {
      uint16_t write_length = write_lengths[current_writing_block];
      if (!write_fds_block(write_data, write_length, FDS_WRITE_GAP_BETWEEN_BLOCKS))
        return;
      write_data += write_length;
      current_writing_block++;
      block_write_count--;
    } else
    {
      if (!read_fds_block_send(16, (current_block >= block_read_start) && block_read_count, &crc_ok, &end_of_head, &file_size, FDS_READ_GAP_BETWEEN_BLOCKS))
        return;
    }
    if ((current_block >= block_read_start) && block_read_count)
      block_read_count--;
    current_block++;

    if (crc_ok && !end_of_head && (block_read_count || block_write_count))
    {
      // file data block
      if (block_write_count && (current_block == block_write_ids[current_writing_block]))
      {
        uint16_t write_length = write_lengths[current_writing_block];
        if (!write_fds_block(write_data, write_length, FDS_WRITE_GAP_BETWEEN_BLOCKS))
          return;
        write_data += write_length;
        current_writing_block++;
        block_write_count--;
      } else
      {
        if (!read_fds_block_send(file_size + 1, (current_block >= block_read_start) && block_read_count, &crc_ok, &end_of_head, 0, FDS_READ_GAP_BETWEEN_BLOCKS))
          return;
      }
      if ((current_block >= block_read_start) && block_read_count)
        block_read_count--;
      current_block++;
    }
  }

  write_prg_byte(FDS_CONTROL, FDS_CONTROL_READ | FDS_MOTOR_OFF); // reset, stop

  _delay_ms(50);
  if (current_writing_block && !block_write_count && !block_read_count)
  {
    comm_start(COMMAND_FDS_WRITE_DONE, 0);
    return;
  }
  comm_start(COMMAND_FDS_READ_RESULT_END, 0);
}

static void get_mirroring()
{
  comm_start(COMMAND_MIRRORING_RESULT, 4);
  LED_GREEN_ON;
  set_address(0);
  _delay_us(1);
  comm_send_byte((PINE >> 2) & 1);
  set_address(1<<10);
  _delay_us(1);
  comm_send_byte((PINE >> 2) & 1);
  set_address(1<<11);
  _delay_us(1);
  comm_send_byte((PINE >> 2) & 1);
  set_address((1<<10) | (1<<11));
  _delay_us(1);
  comm_send_byte((PINE >> 2) & 1);
  set_address(0);
}

static void init_ports()
{
  DDRB |= (1 << 6) | (1 << 7); // LEDS
  DDRF = 0b10110111; // CPU R/W, IRQ, PPU /RD, PPU /A13, CIRAM /CE, PPU /WR, /ROMSEL, PHI2
  PORTF = 0b11111111; // CPU R/W, IRQ, PPU /RD, PPU /A13, CIRAM /CE, PPU /WR, /ROMSEL, PHI2  
  DDRE &= ~(1<<2); // CIRAM A10
  PORTE |= 1<<2; // CIRAM A10
  MODE_READ;
  set_address(0);
  DDRA = 0xFF; // Address low  
  DDRC = 0xFF; // Address high
  COOLBOY_DDR |= (1<<COOLBOY_RD_PIN) | (1<<COOLBOY_WR_PIN);
  COOLBOY_PORT |= (1<<COOLBOY_RD_PIN) | (1<<COOLBOY_WR_PIN);
}

static void reset_phi2()
{
  LED_RED_ON;
  LED_GREEN_ON;
  PHI2_LOW;
  ROMSEL_HI;
  _delay_ms(100);
  PHI2_HI;
  LED_RED_OFF;
  LED_GREEN_OFF;
}

int main (void)
{
  sei();
  USART_init();
  init_ports();

  LED_RED_OFF;
  LED_GREEN_OFF;  
  
  comm_init();
  comm_start(COMMAND_PRG_STARTED, 0);

  uint32_t address;
  uint32_t length;
  
  unsigned long int t = 0;
  char led_down = 0;
  int led_bright = 0;
  
  while (1)
  {
    // PWM for leds
    TCCR1A |= (1<<COM1C1) | (1<<COM1B1) | (1<<WGM10);
    TCCR1B = 1<<CS10; // no prescaler
    if (t++ >= 10000)
    {
      if (!led_down)
      {
        led_bright++;
        if (led_bright >= 110) led_down = 1;
      } else {
        led_bright--;
        if (!led_bright) led_down = 0;
      }
      if (led_bright >= 100) OCR1B = led_bright - 100;
      if (led_down)
      {
        int led_bright2 = 110-led_bright;
        if (led_bright2 <= 20)
        {
          if (led_bright2 > 10) led_bright2 = 20 - led_bright2;
          OCR1C = led_bright2*2;
        }
      }
      t = 0;
    }
    
    if (comm_recv_done)
    {
      comm_recv_done = 0;
      t = led_down = led_bright = 0;
      // Just timer without PWM for timeouts
      TCCR1A = OCR1B = OCR1C = 0;
      TCCR1B = (1<<CS12) | (1<<CS10); // /1024 prescaler
      
      switch (comm_recv_command)
      {
        case COMMAND_PRG_INIT:
          comm_start(COMMAND_PRG_STARTED, 5);
          comm_send_byte(PROTOCOL_VERSION);
          comm_send_byte((SEND_BUFFER_SIZE - 5) & 0xFF);
          comm_send_byte(((SEND_BUFFER_SIZE - 5) >> 8) & 0xFF);
          comm_send_byte((RECV_BUFFER_SIZE - 5) & 0xFF);
          comm_send_byte(((RECV_BUFFER_SIZE - 5) >> 8) & 0xFF);
          break;
          
        case COMMAND_COOLBOY_READ_REQUEST:
        case COMMAND_PRG_READ_REQUEST:
          address = recv_buffer[0] | ((uint16_t)recv_buffer[1]<<8);
          length = recv_buffer[2] | ((uint16_t)recv_buffer[3]<<8);
          read_prg_send(address, length);
          break;

        case COMMAND_PRG_CRC_READ_REQUEST:
          address = recv_buffer[0] | ((uint16_t)recv_buffer[1]<<8);
          length = recv_buffer[2] | ((uint16_t)recv_buffer[3]<<8);
          read_prg_crc_send(address, length);
          break;

        case COMMAND_PRG_WRITE_REQUEST:
          address = recv_buffer[0] | ((uint16_t)recv_buffer[1]<<8);
          length = recv_buffer[2] | ((uint16_t)recv_buffer[3]<<8);
          write_prg(address, length, (uint8_t*)&recv_buffer[4]);
          comm_start(COMMAND_PRG_WRITE_DONE, 0);
          break;

        case COMMAND_RESET:
          reset_phi2();
          comm_start(COMMAND_RESET_ACK, 0);
          break;
          
        case COMMAND_FLASH_ERASE_SECTOR_REQUEST:
        case COMMAND_COOLBOY_ERASE_SECTOR_REQUEST:
          erase_flash_sector();
          break;

        case COMMAND_FLASH_WRITE_REQUEST:
        case COMMAND_COOLBOY_WRITE_REQUEST:
          address = recv_buffer[0] | ((uint16_t)recv_buffer[1]<<8);
          length = recv_buffer[2] | ((uint16_t)recv_buffer[3]<<8);
          write_flash(address, length, (uint8_t*)&recv_buffer[4]);
          break;
          
        case COMMAND_CHR_INIT:
          comm_start(COMMAND_CHR_STARTED, 0);
          break;
          
        case COMMAND_CHR_READ_REQUEST:
          address = recv_buffer[0] | ((uint16_t)recv_buffer[1]<<8);
          length = recv_buffer[2] | ((uint16_t)recv_buffer[3]<<8);
          read_chr_send(address, length);
          break;

        case COMMAND_CHR_CRC_READ_REQUEST:
          address = recv_buffer[0] | ((uint16_t)recv_buffer[1]<<8);
          length = recv_buffer[2] | ((uint16_t)recv_buffer[3]<<8);
          read_chr_crc_send(address, length);
          break;

        case COMMAND_CHR_WRITE_REQUEST:
          address = recv_buffer[0] | ((uint16_t)recv_buffer[1]<<8);
          length = recv_buffer[2] | ((uint16_t)recv_buffer[3]<<8);
          write_chr(address, length, (uint8_t*)&recv_buffer[4]);
          comm_start(COMMAND_CHR_WRITE_DONE, 0);
          break;

        case COMMAND_FDS_READ_REQUEST:
          fds_transfer(recv_buffer[0], recv_buffer[1], 0, 0, 0, 0);
          break;

        case COMMAND_FDS_WRITE_REQUEST:
          fds_transfer(0, 0, recv_buffer[0], (uint8_t*) &recv_buffer[1], (uint16_t*) &recv_buffer[1 + recv_buffer[0]],
            (uint8_t*) &recv_buffer[1 + recv_buffer[0] + recv_buffer[0] * 2]);
          break;        
        
        case COMMAND_MIRRORING_REQUEST:
          get_mirroring();
          break;
          
        case COMMAND_SET_FLASH_BUFFER_SIZE:
          set_flash_buffer_size(recv_buffer[0] | ((uint16_t) recv_buffer[1] << 8));
          comm_start(COMMAND_SET_VALUE_DONE, 0);
          break;

        case COMMAND_BOOTLOADER:
          cli();
          MCUCSR = 0;
          jump_to_bootloader();
      }

      LED_GREEN_OFF;
      LED_RED_OFF;
    }    
  }
}