//This excercise uses the Luhn-algorithm (mod-10-algorithm). Let the security code be comprised of exactly 10 numbers.

//From https://en.wikipedia.org/wiki/Luhn_algorithm

//From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8* 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9).
//2.Take the sum of all the digits.
//3.If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.

#include <stdio.h>

//#include "print.h" //header for verbose capabilities


int persnr_arr[10];

int dec_split(int x){
  int var0 = x % 10; //digit 0 is obtained
  int var1 = (x - var0)/10; //x with var0 subtracted gives a number divisible by 10, reducing it to a single digit.
  printf("DEBUG DEC_SPLIT %d + %d = %d\n", var1, var0, var1+var0);

  return var0 + var1;
}

int persnr_koll(int arr[], int length){
  int i;
  int summa = 0;  
  for (i=length; i>0; i=i-2){ 
    summa = summa + arr[i];
    printf("%d DEBUG %d\n", i, arr[i]);
    printf("%d DEBUG %d\n",i-1, arr[i-1]*2);
    if (9 >= arr[i-1]*2){
      summa = summa + arr[i-1]*2;
    }
    else{
      summa = summa + dec_split(arr[i-1]*2);
    }
  }
  printf("DEBUG FINAL SUM %d\n", summa);

  return summa%10;   
}

int main(){
 
  int persnr_arr[10] = {9,3,0,8,1,4,7,9,5,9};
  int ok_eller_ej;

  ok_eller_ej = persnr_koll(persnr_arr, 9);
  
  if (ok_eller_ej == 0){
    printf("OK\n");
  }
  else{
    printf("INVALID\n");
  }

  return 0;
}


