DEWQ 0.0.4

QR Code Generation Library
Documentation
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
//! # QR Code Generation Module
//!
//! This module provides functionality for generating QR codes with support for different encoding modes and error correction levels.
//!
//! ## Features
//!
//! - Supports multiple encoding modes:
//!   - Numeric
//!   - Alphanumeric
//!   - Byte
//!
//! - Supports various QR code versions and error correction levels
//!
//! ## Encoding Modes
//!
//! The module can automatically detect and encode data in different modes:
//! - Numeric mode: For pure numeric data
//! - Alphanumeric mode: For data containing alphanumeric characters
//! - Byte mode: For ASCII data
//!
//! ## Error Correction
//!
//! Four error correction levels are supported:
//! - L: Lowest error correction (7% recovery)
//! - M: Medium error correction (15% recovery)
//! - Q: Quartile error correction (25% recovery)
//! - H: Highest error correction (30% recovery)
//!
//! ## Usage Example
//!
//! ```rust 
//! let qr_mode = QRMode::analyze_data("HELLO WORLD", ErrorCorrectionLevel::M);
//! let encoded_bits = qr_mode.encode();
//! let qr_data = qr_code.generate_error_correction(encoded_bits);
//! encoded_bits = qr_code.structure_codewords(qr_data);
//! let bit_map = qr_mode.create_bit_map(encoded_bits); 
//! ```

use crate::bit_utils::{bit::*, bit_string::*, bitmap::*};
use crate::galios::*;

// Constants
use crate::qr_code::constants::*;

mod constants;


/// Represents different encoding modes for QR code generation
///
/// # Variants
///
/// * Numeric: Encodes pure numeric data
/// * AlphaNumeric: Encodes alphanumeric data
/// * Byte: Encodes ASCII byte data
///
/// # Methods
///
/// * analyze_data: Automatically detect the appropriate encoding mode for input data
/// * encode: Encode the data into a bitstring
/// * generate_error_correction: Generate error correction codes
/// * structure_codewords: Structure the encoded data and error correction codes
/// * create_bit_map: Create the final QR code bitmap
///
/// # Example
///
/// ```rust 
/// let qr_mode = QRMode::analyze_data("12345", ErrorCorrectionLevel::L); 
/// let encoded_bits = qr_mode.encode(); 
/// ``` 
#[derive(PartialEq, Eq, Debug)]
pub enum QRMode {
    Numeric(QrCode),
    AlphaNumeric(QrCode),
    Byte(QrCode),
    // Kanji(Vec<u16>), // Double byte mode
}

/// Represents a QR Code with its data, version, and error correction level
#[derive(PartialEq, Eq, Debug)]
pub struct QrCode {
    /// Raw data bytes for the QR code
    data: Vec<u8>,
    /// QR code version (size)
    version: usize,
    /// Selected error correction level
    error_correction_level: ErrorCorrectionLevel,
}


/// Represents the error correction levels for QR codes
///
/// # Variants
///
/// * L: Lowest error correction (approximately 7% of codewords can be restored)
/// * M: Medium error correction (approximately 15% of codewords can be restored)
/// * Q: Quartile error correction (approximately 25% of codewords can be restored)
/// * H: Highest error correction (approximately 30% of codewords can be restored)
///
/// # Methods
///
/// Provides methods to retrieve various parameters specific to each error correction level:
/// * get_format_bits: Get the format bits for the error correction level
/// * get_alpha_numeric_version_size: Get max capacity for alphanumeric encoding
/// * get_numeric_version_size: Get max capacity for numeric encoding
/// * get_byte_version_size: Get max capacity for byte encoding
/// * get_num_codewords: Get number of codewords
///
/// # Example
///
/// ```rust 
/// let max_numeric_size = ErrorCorrectionLevel::M.get_numeric_version_size(1); 
/// ``` 
#[derive(PartialEq, Eq, Debug)]
pub enum ErrorCorrectionLevel {
    /// Lowest error correction (approximately 7% of codewords can be restored)
    L,
    /// Medium error correction (approximately 15% of codewords can be restored)
    M,
    /// Quartile error correction (approximately 25% of codewords can be restored
    Q,
    /// Highest error correction (approximately 30% of codewords can be restored)
    H,
}

impl ErrorCorrectionLevel {
    fn get_format_bits(&self) -> u32 {
        match self {
            ErrorCorrectionLevel::L => 0b01,
            ErrorCorrectionLevel::M => 0b00,
            ErrorCorrectionLevel::Q => 0b11,
            ErrorCorrectionLevel::H => 0b10,
        }
    }

    // TODO: add functionality for multiple mask patterns
    #[allow(unused)]
    fn get_format_mask_bits(&self) -> u32 {
        match self {
            ErrorCorrectionLevel::L => 0x77C4,
            ErrorCorrectionLevel::M => 0x5412,
            ErrorCorrectionLevel::Q => 0x355F,
            ErrorCorrectionLevel::H => 0x1689,
        }
    }

    fn get_alpha_numeric_version_size(&self, version: usize) -> usize {
        match self {
            ErrorCorrectionLevel::L => ALPHA_NUMERIC_L_MAX_CAPACITY[version],
            ErrorCorrectionLevel::M => ALPHA_NUMERIC_M_MAX_CAPACITY[version],
            ErrorCorrectionLevel::Q => ALPHA_NUMERIC_Q_MAX_CAPACITY[version],
            ErrorCorrectionLevel::H => ALPHA_NUMERIC_H_MAX_CAPACITY[version],
        }
    }

    fn get_numeric_version_size(&self, version: usize) -> usize {
        match self {
            ErrorCorrectionLevel::L => NUMERIC_L_MAX_CAPACITY[version],
            ErrorCorrectionLevel::M => NUMERIC_M_MAX_CAPACITY[version],
            ErrorCorrectionLevel::Q => NUMERIC_Q_MAX_CAPACITY[version],
            ErrorCorrectionLevel::H => NUMERIC_H_MAX_CAPACITY[version],
        }
    }

    fn get_byte_version_size(&self, version: usize) -> usize {
        match self {
            ErrorCorrectionLevel::L => BYTE_L_MAX_CAPACITY[version],
            ErrorCorrectionLevel::M => BYTE_M_MAX_CAPACITY[version],
            ErrorCorrectionLevel::Q => BYTE_Q_MAX_CAPACITY[version],
            ErrorCorrectionLevel::H => BYTE_H_MAX_CAPACITY[version],
        }
    }

    fn get_num_codewords(&self, version: usize) -> usize {
        match self {
            ErrorCorrectionLevel::L => L_NUM_CODEWORDS[version],
            ErrorCorrectionLevel::M => M_NUM_CODEWORDS[version],
            ErrorCorrectionLevel::Q => Q_NUM_CODEWORDS[version],
            ErrorCorrectionLevel::H => H_NUM_CODEWORDS[version],
        }
    }

    fn get_block_data(&self, version: usize) -> (usize, usize, usize, usize) {
        match self {
            ErrorCorrectionLevel::L => (
                NUM_ERROR_CORRECTION_BLOCKS_GROUP_1_L[version],
                NUM_CODE_WORDS_PER_BLOCK_GROUP_1_L[version],
                NUM_ERROR_CORRECTION_BLOCKS_GROUP_2_L[version],
                NUM_CODE_WORDS_PER_BLOCK_GROUP_2_L[version],
            ),
            ErrorCorrectionLevel::M => (
                NUM_ERROR_CORRECTION_BLOCKS_GROUP_1_M[version],
                NUM_CODE_WORDS_PER_BLOCK_GROUP_1_M[version],
                NUM_ERROR_CORRECTION_BLOCKS_GROUP_2_M[version],
                NUM_CODE_WORDS_PER_BLOCK_GROUP_2_M[version],
            ),
            ErrorCorrectionLevel::Q => (
                NUM_ERROR_CORRECTION_BLOCKS_GROUP_1_Q[version],
                NUM_CODE_WORDS_PER_BLOCK_GROUP_1_Q[version],
                NUM_ERROR_CORRECTION_BLOCKS_GROUP_2_Q[version],
                NUM_CODE_WORDS_PER_BLOCK_GROUP_2_Q[version],
            ),
            ErrorCorrectionLevel::H => (
                NUM_ERROR_CORRECTION_BLOCKS_GROUP_1_H[version],
                NUM_CODE_WORDS_PER_BLOCK_GROUP_1_H[version],
                NUM_ERROR_CORRECTION_BLOCKS_GROUP_2_H[version],
                NUM_CODE_WORDS_PER_BLOCK_GROUP_2_H[version],
            ),
        }
    }

    fn get_num_error_correction_codewords(&self, version: usize) -> usize {
        match self {
            ErrorCorrectionLevel::L => L_ERROR_CORRECTION_CODE_WORDS[version],
            ErrorCorrectionLevel::M => M_ERROR_CORRECTION_CODE_WORDS[version],
            ErrorCorrectionLevel::Q => Q_ERROR_CORRECTION_CODE_WORDS[version],
            ErrorCorrectionLevel::H => H_ERROR_CORRECTION_CODE_WORDS[version],
        }
    }
}

// ------------------ Helper functions ----------------------

fn is_numeric(input: &str) -> bool {
    for character in input.chars() {
        if !character.is_ascii_digit() {
            return false;
        }
    }

    true
}

fn is_alphanumeric(input: &str) -> bool {
    for character in input.bytes() {
        if !(
            character == 32                     // space
        || (character > 35 && character < 38)   // $ and %
        || (character > 41 && character < 44)   // * and +
        || (character > 44 && character < 59)   // -, ., /, numerals, and :
        || (character > 64 && character < 90)
            // Capital Letters
        ) {
            return false;
        }
    }

    true
}

// ----------------------------------------------------------

impl QRMode {
     /// Analyzes input data and determines the appropriate QR code encoding mode
    ///
    /// # Arguments
    ///
    /// * `input` - The data to be encoded
    /// * `error_correction_level` - The desired error correction level
    ///
    /// # Returns
    ///
    /// A `QRMode` variant representing the encoded data
    pub fn analyze_data<'a, S>(input: S, error_correction_level: ErrorCorrectionLevel) -> QRMode
    where
        S: Into<&'a str>,
    {
        let converted_input: &str = input.into();

        if is_numeric(&converted_input) {
            let mut digit_buffer: Vec<u8> = Vec::with_capacity(converted_input.len());
            for i in 0..converted_input.len() {
                // This is to bypass any unnecessary checking
                unsafe {
                    digit_buffer.push(converted_input[i..=i].parse().unwrap_unchecked());
                }
            }

            // Get the version of QR code needed
            let version = {
                let mut out: usize = 0;
                for version_index in (0..MAX_VERSION).rev() {
                    if digit_buffer.len()
                        > error_correction_level.get_numeric_version_size(version_index)
                    {
                        out = version_index + 1;
                        break;
                    }
                }
                out
            };

            return QRMode::Numeric(QrCode {
                data: digit_buffer,
                version,
                error_correction_level,
            });
        } else if is_alphanumeric(&converted_input) {
            // Get the alphanumeric conversion of the data
            let mut data: Vec<u8> = Vec::with_capacity(converted_input.len());
            for character in converted_input.bytes() {
                if character > 47 && character < 58 {
                    data.push(character - 48);
                } else if character > 64 && character < 91 {
                    data.push(character - 55);
                } else if character == 32 {
                    data.push(36);
                } else if character > 35 && character < 38 {
                    data.push(character + 1);
                } else if character > 41 && character < 44 {
                    data.push(character - 2);
                } else if character > 44 && character < 48 {
                    data.push(character - 4);
                } else {
                    data.push(44);
                }
            }

            // Get the version of QR code needed
            let version = {
                let mut out: usize = 0;
                for version_index in (0..MAX_VERSION).rev() {
                    if data.len()
                        > error_correction_level.get_alpha_numeric_version_size(version_index)
                    {
                        out = version_index + 1;
                        break;
                    }
                }
                out
            };

            return QRMode::AlphaNumeric(QrCode {
                data,
                version,
                error_correction_level,
            });
        } else if converted_input.is_ascii() {
            // Get the version of QR code needed
            let version = {
                let mut out: usize = 0;
                for version_index in (0..MAX_VERSION).rev() {
                    if converted_input.len()
                        > error_correction_level.get_byte_version_size(version_index)
                    {
                        out = version_index + 1;
                        break;
                    }
                }
                out
            };

            return QRMode::Byte(QrCode {
                data: converted_input.bytes().collect(),
                version,
                error_correction_level,
            });
        }

        panic!()
    }

    // Private getters for easy abstraction
    fn version(&self) -> usize {
        use QRMode::*;
        match self {
            Numeric(qr_code) | AlphaNumeric(qr_code) | Byte(qr_code) => qr_code.version,
        }
    }

    fn error_correction_level(&self) -> &ErrorCorrectionLevel {
        use QRMode::*;
        match self {
            Numeric(qr_code) | AlphaNumeric(qr_code) | Byte(qr_code) => {
                &qr_code.error_correction_level
            }
        }
    }

    /// Encodes the QR code data into a bitstring
    ///
    /// # Returns
    ///
    /// A `BitString` containing the encoded data
    pub fn encode(&mut self) -> BitString {
        let mut bit_string: BitString = BitString::new();
        let size_of_character_length_bits: usize;

        // Perform the mode dependent encoding
        match self {
            QRMode::Numeric(nqr) => {
                bit_string.push_bit(0);
                bit_string.push_bit(0);
                bit_string.push_bit(0);
                bit_string.push_bit(1);

                size_of_character_length_bits = {
                    let out: usize;
                    if (nqr.version + 1) < 10 {
                        out = 10;
                    } else if (nqr.version + 1) > 9 && (nqr.version + 1) < 27 {
                        out = 12;
                    } else {
                        out = 14;
                    }

                    out
                };

                // Encode the character count
                for i in (0..size_of_character_length_bits).rev() {
                    bit_string.push_bit((nqr.data.len() & (1 << i)) as i32);
                }

                // Split input string into groups of 3 with the remainder being group of 1 or 2
                let encoded_data = {
                    // both u16 so it fits in a word boundary
                    let mut numbers: Vec<(u16, u16)> = Vec::with_capacity(nqr.data.len() / 3 + 1);

                    let mut current_number: u16 = 0;
                    let mut current_number_size: u16 = 0;

                    for digit in nqr.data.iter() {
                        current_number *= 10;
                        current_number += *digit as u16;
                        current_number_size += 1;

                        if current_number_size == 3 {
                            numbers.push((current_number, current_number_size));
                            current_number = 0;
                            current_number_size = 0;
                        }
                    }

                    // Push the last number if it is not a group of 3
                    if current_number_size != 0 {
                        numbers.push((current_number, current_number_size));
                    }

                    numbers
                };

                // Push the bits for each number to the bitstring
                // if the number is 3 digits
                for group in encoded_data {
                    let (number, digits) = group;

                    let size: usize = match digits {
                        3 => 10,
                        2 => 7,
                        1 => 4,
                        _ => 0,
                    };

                    for i in (0..size).rev() {
                        bit_string.push_bit(number & (1 << i));
                    }
                }
            }
            QRMode::AlphaNumeric(anqr) => {
                // Adding the mode indicator
                bit_string.push_bit(0);
                bit_string.push_bit(0);
                bit_string.push_bit(1);
                bit_string.push_bit(0);

                size_of_character_length_bits = {
                    let out: usize;
                    if (anqr.version + 1) < 10 {
                        out = 9;
                    } else if (anqr.version + 1) > 9 && (anqr.version + 1) < 27 {
                        out = 11;
                    } else {
                        out = 13;
                    }

                    out
                };

                // Encode the character count
                for i in (0..size_of_character_length_bits).rev() {
                    bit_string.push_bit((anqr.data.len() & (1 << i)) as i32);
                }

                // Encode the values in alphanumeric encoding
                for value_index in (0..anqr.data.len()).step_by(2) {
                    // Since stepping by 2 we know that this is always going to be Some()
                    let first_value = unsafe { anqr.data.get(value_index).unwrap_unchecked() };

                    match anqr.data.get(value_index + 1) {
                        Some(second_value) => {
                            let encoded = (*first_value as u16 * 45) + *second_value as u16;

                            // 11 bits for double characters
                            for i in (0..11).rev() {
                                bit_string.push_bit(encoded & (1 << i));
                            }
                        }
                        None => {
                            let encoded = *first_value;

                            // 6 bits for single characters
                            for i in (0..6).rev() {
                                bit_string.push_bit(encoded & (1 << i));
                            }
                        }
                    }
                }
            }
            QRMode::Byte(bqr) => {
                // Adding the mode indicator
                bit_string.push_bit(0);
                bit_string.push_bit(1);
                bit_string.push_bit(0);
                bit_string.push_bit(0);

                size_of_character_length_bits = {
                    let out: usize;
                    if (bqr.version + 1) < 10 {
                        out = 8;
                    } else {
                        out = 16;
                    }

                    out
                };

                // Encode the character count
                for i in (0..size_of_character_length_bits).rev() {
                    bit_string.push_bit((bqr.data.len() & (1 << i)) as i32);
                }

                // Add the data to the bit string
                for data in bqr.data.iter() {
                    bit_string.push_byte(*data);
                }
            }
        }

        // The rest is the mode independed encoding
        let required_number_of_bits = self
            .error_correction_level()
            .get_num_codewords(self.version())
            * BYTE_SIZE;

        // Add terminator 0s if necessary
        {
            let total_bits = bit_string.len() - 4 - (size_of_character_length_bits);

            let bit_difference = required_number_of_bits - total_bits;

            for _ in 0..bit_difference.min(4) {
                bit_string.push_bit(0);
            }
        }

        // Make sure the bitstring is a multiple of 8
        while bit_string.len() % 8 != 0 {
            bit_string.push_bit(0);
        }

        // Add the necessary pad bytes
        while bit_string.len() < required_number_of_bits {
            // append binary 236
            bit_string.push_bit(1);
            bit_string.push_bit(1);
            bit_string.push_bit(1);
            bit_string.push_bit(0);
            bit_string.push_bit(1);
            bit_string.push_bit(1);
            bit_string.push_bit(0);
            bit_string.push_bit(0);

            // Check if the bitsting is long enough
            if bit_string.len() >= required_number_of_bits {
                break;
            }

            // append binary 17
            bit_string.push_bit(0);
            bit_string.push_bit(0);
            bit_string.push_bit(0);
            bit_string.push_bit(1);
            bit_string.push_bit(0);
            bit_string.push_bit(0);
            bit_string.push_bit(0);
            bit_string.push_bit(1);
        }

        return bit_string;
    }

    /// Generates error correction codes for the QR code data
    ///
    /// # Arguments
    ///
    /// * `bits` - The input bitstring to generate error correction for
    ///
    /// # Returns
    ///
    /// A tuple of data blocks and error correction blocks
    pub fn generate_error_correction(&self, bits: BitString) -> (Vec<Vec<u8>>, Vec<Vec<u8>>) {
        let mut data: Vec<Vec<u8>> = Vec::new();
        let mut error_correction_data: Vec<Vec<u8>> = Vec::new();

        let (
            num_blocks_group_1,
            num_code_words_group_1,
            num_blocks_group_2,
            num_code_words_group_2,
        ) = self.error_correction_level().get_block_data(self.version());

        // Create all the message polynomials from the data codewords
        let mut message_polynomials: Vec<Polynomial> = Vec::new();
        let mut index = 0;

        for _ in 0..num_blocks_group_1 {
            let mut block: Vec<u8> = Vec::new();
            for _ in 0..num_code_words_group_1 {
                block.push(bits.get_byte(index));
                index += 1;
            }

            data.push(Vec::from(block.clone()));
            message_polynomials.push(Polynomial::from_integer_notation(block));
        }

        for _ in 0..num_blocks_group_2 {
            let mut block = Vec::new();
            for _ in 0..num_code_words_group_2 {
                block.push(bits.get_byte(index));
                index += 1;
            }

            data.push(Vec::from(block.clone()));
            message_polynomials.push(Polynomial::from_integer_notation(block));
        }

        for message_polynomial in message_polynomials {
            // Create a generator polynomial based on the number of blocks needed
            let mut generator_polynomial = {
                let mut poly = Polynomial::from_exponent_notation(vec![0, 0]);

                for i in 1..self
                    .error_correction_level()
                    .get_num_error_correction_codewords(self.version())
                {
                    poly =
                        poly.multiply(&mut Polynomial::from_exponent_notation(vec![0, i as i32]));
                }

                poly
            };

            // Perform the long division on the message polynomial with the generator polynomial
            let mut current_message = message_polynomial.clone();
            let mut inter_poly;
            let mut step = 0;
            while step < message_polynomial.len() {
                // Multiply the generator by the first coefficient of the message polynomial
                inter_poly = generator_polynomial
                    .multiply_by_exponent(current_message.get_as_exponent_vec()[0]);
                // xor the resulting multiplaction with the current message polynomial
                inter_poly = current_message.xor(&mut inter_poly);
                // Drop the leading zeros of the resulting xor operation
                inter_poly.drop_leading_zero();
                // Make sure the skip steps while the leading term is still 0
                while inter_poly.drop_leading_zero() {
                    step += 1;
                }
                // Set the new current message to the resulting computation
                current_message = inter_poly;
                step += 1;
            }

            while current_message.len() < message_polynomial.len() {
                current_message = current_message.prepend(0);
            }

            // Push the data to the error correction data as u8
            error_correction_data.push({
                let mut output: Vec<u8> = Vec::new();

                for elem in current_message.get_as_integer_vec() {
                    output.push(elem as u8);
                }

                output
            });
        }

        (data, error_correction_data)
    }

    /// Structures the data and error correction codewords
    ///
    /// # Arguments
    ///
    /// * `data` - A tuple of data blocks and error correction blocks
    ///
    /// # Returns
    ///
    /// A `BitString` with structured codewords
    pub fn structure_codewords(&self, data: (Vec<Vec<u8>>, Vec<Vec<u8>>)) -> BitString {
        let mut new_data: Vec<u8> = Vec::new();

        let max_index = data.0.iter().max_by_key(|block| block.len()).unwrap().len();

        // Interleave the data codewords
        for i in 0..max_index {
            for block in data.0.iter() {
                if let Some(value) = block.get(i) {
                    new_data.push(*value);
                }
            }
        }

        let max_index = data.1.iter().max_by_key(|block| block.len()).unwrap().len();

        // Interleave the error codewords
        for i in 0..max_index {
            for block in data.1.iter() {
                if let Some(value) = block.get(i) {
                    new_data.push(*value);
                }
            }
        }

        // Create a new bitstring from the data and push the required remainder bits to it
        let mut new_bitstring = BitString::from_vec(new_data);
        new_bitstring.push_bit_times(0, REQUIRED_REMAINDER_BITS[self.version()]);

        new_bitstring
    }

    /// Creates the final QR code bitmap
    ///
    /// # Arguments
    ///
    /// * `bits` - The encoded bitstring to place in the bitmap
    ///
    /// # Returns
    ///
    /// A `BitMap` representing the complete QR code
    pub fn create_bit_map(&self, bits: BitString) -> BitMap {
        let size = 21 + (4 * (self.version()));

        let mut bit_map = BitMap::new(size);
        let mut reservations = BitMap::new(size);

        // High level overview of the steps to create the QR code
        create_finder_patterns(&mut bit_map, &mut reservations);
        create_alignment_patterns(&mut bit_map, &mut reservations);
        create_timing_patterns(&mut bit_map, &mut reservations);
        create_dark_module(&mut bit_map, &mut reservations);
        reserve_format_information_areas(&mut reservations);
        place_data_bits(&mut bit_map, &reservations, &bits);
        mask_data(&mut bit_map, &reservations);
        add_format_information(&mut bit_map, self.error_correction_level(), self.version());

        bit_map
    }
}

fn add_format_information(
    bit_map: &mut BitMap,
    error_correction_level: &ErrorCorrectionLevel,
    version: usize,
) {
    // HACK: temparory mask variable while still testing with only mask 0
    let mask = 0;

    // Put the bits into the bitmap
    let mut index = 0;

    // Add the version information if the version is greater than 7
    if version >= 6 {
        // Get the format information bits and error correction for those bits
        let version_bits: u32 = {
            let data = version as u32 + 1;
            // Generator polynomial: x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
            const GENERATOR_POLYNOMIAL: u32 = 0x1F25;

            let mut rem: u32 = data;
            // This is the same as doing a division by the generator polynomial until the remainder is
            // less than 4096
            for _ in 0..12 {
                rem = (rem << 1) ^ ((rem >> 11) * GENERATOR_POLYNOMIAL);
            }

            (data << 12) | rem
        };

        for j in 0..6 {
            for i in 0..3 {
                bit_map.set(bit_map.size() - 11 + i, j, version_bits & (1 << index));
                bit_map.set(j, bit_map.size() - 11 + i, version_bits & (1 << index));

                index += 1;
            }
        }
    }

    index = 0;
    // Get the format information bits and error correction for those bits
    let bits: u32 = {
        let data = error_correction_level.get_format_bits() << 3 | mask;

        // Generator polynomial: x^10 + x^8 + x^5 + x^4 + x^2 + x + 1
        const GENERATOR_POLYNOMIAL: u32 = 0x537;

        let mut rem: u32 = data;
        // This is the same as doing a division by the generator polynomial until the remainder is
        // less than 1024
        for _ in 0..10 {
            rem = (rem << 1) ^ ((rem >> 9) * GENERATOR_POLYNOMIAL);
        }

        ((data << 10) | rem) ^ 0x5412
    };

    for i in 0..=5 {
        let bit = bits & (0x4000 >> index);
        bit_map.set(8, i, bit);
        bit_map.set(bit_map.size() - 1 - i, 8, bit);
        index += 1;
    }

    // Add bits 6, 7, and 8
    let (bit_6, bit_7, bit_8) = (
        bits & (0x4000 >> index),
        bits & (0x4000 >> (index + 1)),
        bits & (0x4000 >> (index + 2)),
    );
    index += 3;

    // Set bits 6, 7, and 8
    bit_map.set(8, 7, bit_6);
    bit_map.set(bit_map.size() - 6, 8, bit_6);

    bit_map.set(8, 8, bit_7);
    bit_map.set(8, bit_map.size() - 7, bit_7);

    bit_map.set(7, 8, bit_8);
    bit_map.set(8, bit_map.size() - 6, bit_8);

    for i in 9..=14 {
        let bit = bits & (0x4000 >> index);
        index += 1;
        bit_map.set(14 - i, 8, bit);
        bit_map.set(8, bit_map.size() - (15 - i), bit);
    }
}

// TODO: Add support for other data masking as well
fn mask_data(bit_map: &mut BitMap, reservations: &BitMap) {
    // Doing data masking number 0
    for row in 0..bit_map.size() {
        for column in 0..bit_map.size() {
            if (row + column) % 2 == 0 {
                if reservations.get(row, column) == Bit::Zero {
                    bit_map.invert_bit(row, column);
                }
            }
        }
    }
}

fn place_data_bits(bit_map: &mut BitMap, reservations: &BitMap, bits: &BitString) {
    enum Direction {
        Up,
        Down,
    }

    impl Direction {
        fn toggle(&mut self) {
            match self {
                Direction::Up => {
                    *self = Direction::Down;
                }
                Direction::Down => {
                    *self = Direction::Up;
                }
            }
        }
    }

    // Place bits up in a zig zag pattern
    fn place_bits(
        bit_map: &mut BitMap,
        reservations: &BitMap,
        bits: &BitString,
        index: &mut usize,
        x_pos: usize,
        direction: &Direction,
    ) {
        let mut y_pos = match direction {
            Direction::Up => bit_map.size() - 1,
            Direction::Down => 0,
        };

        loop {
            // if *index >= bits.len() {
            //     break;
            // }

            if reservations.get(y_pos, x_pos) == Bit::Zero {
                bit_map.set(y_pos, x_pos, bits.get_bit(*index).unwrap());
                *index += 1;
            }

            // if *index >= bits.len() {
            //     break;
            // }

            if reservations.get(y_pos, x_pos - 1) == Bit::Zero {
                bit_map.set(y_pos, x_pos - 1, bits.get_bit(*index).unwrap());
                *index += 1;
            }

            if y_pos
                == match direction {
                    Direction::Up => 0,
                    Direction::Down => bit_map.size() - 1,
                }
            {
                break;
            }

            y_pos = match direction {
                Direction::Up => y_pos - 1,
                Direction::Down => y_pos + 1,
            };
        }
    }

    let mut index = 0;
    let mut x_pos = bit_map.size() - 1;
    let mut current_direction = Direction::Up;

    while x_pos > 0 {
        place_bits(
            bit_map,
            reservations,
            bits,
            &mut index,
            x_pos,
            &current_direction,
        );

        if x_pos < 2 {
            break;
        }

        x_pos -= 2;

        if x_pos == 6 {
            x_pos -= 1;
        }

        current_direction.toggle();
    }
}

fn reserve_format_information_areas(reservations: &mut BitMap) {
    let version = ((reservations.size() - 21) / 4) + 1;

    if version >= 6 {
        for i in 0..=5 {
            reservations.set(i, reservations.size() - 11, 1);
            reservations.set(i, reservations.size() - 10, 1);
            reservations.set(i, reservations.size() - 9, 1);

            reservations.set(reservations.size() - 11, i, 1);
            reservations.set(reservations.size() - 10, i, 1);
            reservations.set(reservations.size() - 9, i, 1);
        }
    }

    for i in 0..=8 {
        reservations.set(i, 8, 1);
        reservations.set(8, i, 1);
        reservations.set(reservations.size() - i, 8, 1);
        reservations.set(8, reservations.size() - i, 1);
    }
}

fn create_dark_module(bit_map: &mut BitMap, reservations: &mut BitMap) {
    bit_map.set(bit_map.size() - 8, 8, Bit::One);
    reservations.set(reservations.size() - 8, 8, Bit::One);
}

fn create_timing_patterns(bit_map: &mut BitMap, reservations: &mut BitMap) {
    for i in 7..(bit_map.size() - 7) {
        if i % 2 == 0 {
            bit_map.set(i, 6, Bit::One);
            bit_map.set(6, i, Bit::One);
        }

        reservations.set(i, 6, Bit::One);
        reservations.set(6, i, Bit::One);
    }
}

fn get_alignment_pattern_coordinates_list(bit_map_size: usize) -> Vec<usize> {
    let version = ((bit_map_size - 21) / 4) + 1;

    let intervals = (version / 7) + 1;
    let distance = 4 * version + 4;
    let mut step = ((distance as f64) / (intervals as f64)).round() as usize;
    step += step & 0b1; // Round step to the next even number
    let mut coordinates: Vec<usize> = vec![6]; // The first coordinate is always 6
    for i in 1..=intervals {
        coordinates.push(6 + distance - step * (intervals - i));
    }

    coordinates
}

fn create_alignment_patterns(bit_map: &mut BitMap, reservations: &mut BitMap) {
    if bit_map.size() <= 21 {
        return;
    }

    fn add_alignment_pattern(bit_map: &mut BitMap, reservations: &mut BitMap, i: usize, j: usize) {
        // The center dot
        bit_map.set(i, j, Bit::One);

        for x in -2..=2 as isize {
            bit_map.set(i - 2, (j as isize + x) as usize, 1);
            bit_map.set(i + 2, (j as isize + x) as usize, 1);
            bit_map.set((i as isize + x) as usize, j + 2, 1);
            bit_map.set((i as isize + x) as usize, j - 2, 1);
        }

        // Reserve the alignment patterns
        for reservation_x in -2..=2 as isize {
            for reservation_y in -2..=2 as isize {
                reservations.set(
                    (reservation_x + i as isize) as usize,
                    (reservation_y + j as isize) as usize,
                    Bit::One,
                );
            }
        }
    }

    let coords = get_alignment_pattern_coordinates_list(bit_map.size());

    for x in 0..coords.len() {
        for y in 0..coords.len() {
            // Skip the coordinate if it is an invalid placement
            if (x == 0 && y == 0)
                || (x == 0 && y == coords.len() - 1)
                || (x == coords.len() - 1 && y == 0)
            {
                continue;
            }

            add_alignment_pattern(bit_map, reservations, coords[x], coords[y]);
        }
    }
}

fn create_finder_patterns(bit_map: &mut BitMap, reservations: &mut BitMap) {
    // Adds and reserves the finder starting from the top left corner i, j
    fn add_finder(
        location: (usize, usize),
        bit_map: &mut BitMap,
        reservations: &mut BitMap,
        separator_offset: (isize, isize),
    ) {
        let (i, j) = location;

        for x in 0..7 {
            bit_map.set(i, j + x, 1);
            bit_map.set(i + 6, j + x, 1);

            bit_map.set(i + x, j, 1);
            bit_map.set(i + x, j + 6, 1);
        }

        for x in 2..5 {
            for y in 2..5 {
                bit_map.set(i + x, j + y, 1);
            }
        }

        let (i_off, j_off) = separator_offset;

        // Reserve the place on the bitmap with the separators as well
        for reservation_x in i_off..=(i_off + 7) {
            for reservation_y in j_off..=(j_off + 7) {
                reservations.set(
                    (reservation_x + i as isize) as usize,
                    (reservation_y + j as isize) as usize,
                    Bit::One,
                );
            }
        }
    }

    add_finder((0, 0), bit_map, reservations, (0, 0));
    add_finder((bit_map.size() - 7, 0), bit_map, reservations, (-1, 0));
    add_finder((0, bit_map.size() - 7), bit_map, reservations, (0, -1));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_qr_modes() {
        let qr_mode = QRMode::analyze_data("A113", ErrorCorrectionLevel::L);
        assert_eq!(
            qr_mode,
            QRMode::AlphaNumeric(QrCode {
                data: vec![10, 1, 1, 3],
                version: 0,
                error_correction_level: ErrorCorrectionLevel::L
            })
        );
    }
}