Well, from now on follow that rule. Reading files is pretty expensive :P
Looks like you figured out the image stuff, good work!
Though with those variable names and lack of comments (other then that 1 comment), I have a hard time trying to figure out what's going on. Comment it/give better names for "a,b,c,r,n" and I can probably help you cut down on it a little (6 for loops is a lot, you can probably do it in 1-2 with some recursion).