module IPynbToJl

using JSON

export ipynb_to_jl

function ipynb_to_jl(infile, outfile=replace(infile, r"\.ipynb", ".jl")) 
    f = JSON.parsefile(infile, use_mmap=false)
    f == nothing && error("Could not open [$infile]")
    outf = open(outfile, "w")
    write(outf, "#  ", abspath(outfile), "\n")
    write(outf, "#  AUTOGENERATED FROM ", abspath(infile), " on ", string(Dates.now()), "\n")

    for c in f["worksheets"][1]["cells"]
        cell_type = c["cell_type"]
        if cell_type == "code"
            write(outf, c["input"])
            write(outf, "\n")
        else
            write(outf, "#[$cell_type]\n")
            write(outf, map(l -> "# $l\n", c["source"]))
            write(outf, "\n")
        end
    end
    close(outf)
    print("Wrote $outfile\n") # If generating a source file, I like to ensure there's some output to stdout
end

end
