#include <stdio.h>
#include <stdlib.h>

int populate_array(int, int *);
int check_sin(int *);


int main(int argc, char **argv) {
    // TODO: Verify that command line arguments are valid.
    if (argc != 2) {
        return 2;
    }

    int sin = strtol(argv[1], NULL, 10);
    int sin_array[10];

    // TODO: Parse arguments and then call the two helpers in sin_helpers.c
    // to verify the SIN given as a command line argument.

    int valid = populate_array(sin, sin_array);

    if (valid != 0){
        return 1;
    }

    return check_sin(sin_array);
}

int populate_array(int sin, int *sin_array) {
    for (int i = 8; i >= 0; i--){
        if (sin == 0) {
            return 1; // less than 9 digits
        }
        sin_array[i] = sin % 10;
        sin /= 10;
    }
    if (sin != 0){
        return 1; // more than 9 digits
    }
    return 0; 
}

// TODO: Implement check_sin
/*
 * Return 0 if the given sin_array is a valid SIN, and 1 otherwise.
 */
int check_sin(int *sin_array) {
    int sum = 0;
    for (int i = 0; i < 9; i += 2){
        sum += sin_array[i];
    }
    for (int i = 1; i < 9; i += 2){
        int doubled = sin_array[i] * 2;
        sum += doubled % 10 + doubled / 10;
    }
    if (sum % 10 == 0){
        return 0;
    }
    else {
        return 1;
    }
}

check if the SIN given by command line argument is valid, using the Luhn algorithm