package main

import (
	"fmt"
	"os"
	"strconv"
)

func printUsage() {
	fmt.Println("Usage: day10 <look-and-say> [iterations]")
	os.Exit(1)
}

/* Pt 2 Result:
Length of result: 5103798
*/
func main() {
	var debugMode bool

	args := os.Args
	if len(args) < 2 {
		printUsage()
	}
	var lasString string
	lasString = args[1]

	var iter int
	var err error
	if len(args) > 2 {
		if iter, err = strconv.Atoi(args[2]); err != nil {
			printUsage()
		}
	} else {
		iter = 40
	}
	if len(args) > 3 {
		if args[2] == "--debug" {
			debugMode = true
		}
	}

	fmt.Printf("Iterate %d times over %s\n", iter, lasString)
	for i := 0; i < iter; i++ {
		fmt.Print("O")
		if i%10 == 9 {
			fmt.Println(" " + strconv.Itoa(len(lasString)))
		}
		r := lookAndSay(lasString)
		if debugMode {
			fmt.Println(strconv.Itoa(i) + " >> " + r)
		}
		lasString = r
	}
	fmt.Println("\nLength of result: " + strconv.Itoa(len(lasString)))
}

func lookAndSay(str string) string {
	numI := 1
	var ret string

	strLen := len(str)

	for i := range str {
		if strLen > i+1 {
			if str[i+1] != str[i] {
				ret += strconv.Itoa(numI) + string(str[i])
				numI = 0
			}
		} else {
			// Last char in string
			ret += strconv.Itoa(numI) + string(str[i])
		}
		numI++
	}
	return ret
}