%% to compile: erlc day3A.erl
%% to run: erl -noshell -s day5 solve
%%
-module(day13).

-export ([solve/0, solve/1, solve/2]).
-export ([read_input/0]).

solve() ->
    solve(['1']),
    solve(['2']),
    init:stop().

solve(A) ->
    solve(A, read_input()).

solve(['1'], D) ->
    io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
solve(1, D) ->
    solution1(D);
solve(['2'], D) ->
    io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
solve(2, D) ->
    solution2(D).

read_input() ->
    {ok, IO} = file:open("input.txt", 'read'),
    Data = read_input(IO),
    file:close(IO),
    Data.

read_input(IO) ->
	read_input(IO, []).

read_input(IO, Input) ->
    case read_line(IO) of
	'eof' -> Input;
	Line -> read_input(IO, Input ++ [Line])
    end.

read_line(IO) ->
	case file:read_line(IO) of
		'eof' -> 'eof';
		{ok, Line} -> parse_line(Line)
	end.

parse_line(Line) ->
    Points = string:tokens(Line, " ,\n"),
    [X, Y] = [list_to_integer(X) || X <- Points],
    {X, Y}.

solution1(Input) ->
    io:format("Input ~p~n", [Input]),
    F1 = fold(x, 655, Input),
    length(F1).

solution2(Input) ->
    I = fold(y,6,fold(y,13,fold(y,27,fold(x,40,fold(y,55,fold(x,81,fold(y,111,fold(x,163,fold(y,223,fold(x,327,fold(y,447,fold(x,655, Input)))))))))))),
    MaxX = lists:foldl(fun({T, _}, Acc) -> case T > Acc of 'true' -> T; _ -> Acc end end, 0, I),
    MaxY = lists:foldl(fun({_, T}, Acc) -> case T > Acc of 'true' -> T; _ -> Acc end end, 0, I),
    Coords = [{X,Y} || Y <- lists:seq(0,MaxY), X <- lists:seq(0,MaxX)],
    output(Coords, I, MaxX).

output([], I, MaxX) -> ok;
output([{X,Y}|Rest], I, MaxX) ->
	case lists:member({X,Y}, I) of
		'true' -> io:format("#");
		'false' -> io:format(" ")
	end,
	case X == MaxX of
		'true' -> io:format("~n");
		'false' -> ok
	end,
	output(Rest, I, MaxX).

fold(y, N, Input) ->
    L1 = [ {X, (Y * -1) + N}  || {X, Y} <- Input],
    {Sat, NotSat} = lists:partition(fun({_,Y}) -> Y < 0 end, L1),
    Sat2 = [{X, Y * -1}|| {X, Y} <- Sat],
    L2 = lists:usort(NotSat ++ Sat2),
    [ {X, (Y - N) * -1}  || {X,Y} <- L2];
fold(x, N, Input) ->
    L1 = [ {(X * -1) + N, Y}  || {X, Y} <- Input],
    {Sat, NotSat} = lists:partition(fun({X,_}) -> X < 0 end, L1),
    Sat2 = [{X * -1, Y}|| {X, Y} <- Sat],
    L2 = lists:usort(NotSat ++ Sat2),
    [ {(X - N) * -1, Y}  || {X,Y} <- L2].

