package main import ( "bufio" "fmt" "os" "strconv" "strings" "github.com/pterm/pterm" ) func main() { pterm.DefaultHeader.WithBackgroundStyle(pterm.NewStyle(pterm.BgCyan)).WithTextStyle(pterm.NewStyle(pterm.FgCyan)).Println("Welcome to Checkdigit Calculator") directory, err := os.Getwd() Error(err) pterm.Printf(pterm.Cyan("What is the name of the file in this directory?: ")) reader := bufio.NewReader(os.Stdin) input, err := reader.ReadString('\n') Error(err) input = strings.TrimSpace(input) file, err := os.Open(input) Error(err) var upcs []string scanner := bufio.NewScanner(file) for scanner.Scan() { upcs = append(upcs, scanner.Text()) } err = file.Close() Error(err) if scanner.Err() != nil { fmt.Println(scanner.Err()) } pterm.DefaultSpinner.Start() Error(err) var gtins []string for _, upc := range upcs { upcLength := len(upc) // Check Digit Formula // Take all the digits in odd positions, add them and multiply by three // Take all the digits in even positions (except for the last one) and add to the number you got above // Divide that number by 10 and take the remainder // If the remainder is not 0, subtract it from 10 // // 12/8/2023: New git updates from https://www.gs1.org/services/how-calculate-check-digit-manually oddNumber := 0 evenNumber := 0 var remainder int if upcLength < 8 { gtins = append(gtins, "Cannot process upcs less than 8 digits") continue } if upcLength > 17 { gtins = append(gtins, "Invalid barcode") continue } if upcLength%2 == 0 { for i, num := range upc { if i%2 != 0 { convertedOddNumber, err := strconv.Atoi(string(num)) Error(err) convertedOddNumber = convertedOddNumber * 3 oddNumber += convertedOddNumber } else { if upcLength-1 > i { convertedEvenNumber, err := strconv.Atoi(string(num)) Error(err) evenNumber += convertedEvenNumber } } } } else { for i, num := range upc { if i%2 == 0 { convertedOddNumber, err := strconv.Atoi(string(num)) Error(err) convertedOddNumber = convertedOddNumber * 3 oddNumber += convertedOddNumber } else { if upcLength-1 > i { convertedEvenNumber, err := strconv.Atoi(string(num)) Error(err) evenNumber += convertedEvenNumber } } } } remainder = (oddNumber + evenNumber) % 10 if remainder != 0 { remainder = 10 - remainder } remainderString := strconv.Itoa(remainder) gtins = append(gtins, upc+remainderString) } if _, err := os.Stat(directory + "/answer.txt"); err == nil { e := os.Remove(directory + "/answer.txt") Error(e) } answerFile, err := os.Create(directory + "/answer.txt") Error(err) defer answerFile.Close() for _, gtin := range gtins { _, err := answerFile.WriteString(gtin + "\n") Error(err) } pterm.DefaultSpinner.Stop() pterm.Println("\n") pterm.Success.Println("The answer.txt file has been successfully generated with check digits.") }