package main

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

func main() {
	if len(os.Args) < 2 || os.Args[1] == "-help" {
		fmt.Println("Usage: day25 <row> <col>")
		fmt.Println("   or: day25 <code number>")
	}
	row := mustAtoi(os.Args[1])
	if len(os.Args) == 2 {
		fmt.Printf("%d\n", genCodeNum(row))
		os.Exit(0)
	}
	// Must be row/col request
	col := mustAtoi(os.Args[2])
	fmt.Printf("%d\n", genCodeNum(codeNumFromRowCol(row, col)))
}

func codeNumFromRowCol(r int, c int) int {
	if r == 1 {
		if c == 1 {
			return 1
		}
		return c + codeNumFromRowCol(r, c-1)
	}
	if c == 1 {
		return codeNumFromRowCol(1, (r-1)) + 1
	}
	return codeNumFromRowCol((r+1), (c-1)) + 1
}

func genCodeNum(i int) int64 {
	ret := int64(20151125)
	for i > 1 {
		ret *= 252533
		ret = ret % 33554393
		i--
	}
	return ret
}

func mustAtoi(s string) int {
	var i int
	var err error
	if i, err = strconv.Atoi(s); err != nil {
		fmt.Println("Tried to atoi " + s)
		os.Exit(1)
	}
	return i
}
