Canola  0.8.D001
lib/calculator/save_memories_as_program.cc
Go to the documentation of this file.
00001 //
00002 // canola - canon canola 1614p emulator
00003 // Copyright (C) 2012 Peter Miller
00004 //
00005 // This program is free software; you can redistribute it and/or modify
00006 // it under the terms of the GNU General Public License, version 3, as
00007 // published by the Free Software Foundation.
00008 //
00009 // This program is distributed in the hope that it will be useful,
00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012 // General Public License for more details.
00013 //
00014 // You should have received a copy of the GNU General Public License along
00015 // with this program. If not, see <http://www.gnu.org/licenses/>.
00016 //
00017 
00018 #include <lib/ac/stdio.h>
00019 #include <libexplain/fclose.h>
00020 #include <libexplain/fflush.h>
00021 #include <libexplain/fopen.h>
00022 
00023 #include <lib/calculator.h>
00024 
00025 
00026 bool
00027 calculator::save_memories_as_program(const std::string &filename)
00028 {
00029     FILE *fp = fopen(filename.c_str(), "w");
00030     if (!fp)
00031     {
00032         on_error("%s", explain_fopen(filename.c_str(), "w"));
00033         return false;
00034     }
00035     for (unsigned j = 1; j <= 14; ++j)
00036     {
00037         const number &n = memory[j];
00038         if (n != 0)
00039         {
00040             std::string s = n.to_string();
00041             const char *cp = s.c_str();
00042             const char *ep = cp + s.size();
00043             while (*cp == ' ')
00044                 ++cp;
00045             while (*cp == '0')
00046                 ++cp;
00047             while (ep > cp && ep[-1] == '0')
00048                 --ep;
00049             if (ep > cp && ep[-1] == '.')
00050                 --ep;
00051             assert(cp != ep);
00052             fprintf(fp, "%.*s\n", (int)(ep - cp), cp);
00053             if (j == 1 || j == 2)
00054             {
00055                 fprintf(fp, "CM%d\n", j);
00056                 fprintf(fp, "M%d\n", j);
00057             }
00058             else
00059             {
00060                 fprintf(fp, "SM%d\n", j);
00061             }
00062         }
00063     }
00064     if (fflush(fp))
00065     {
00066         on_error("%s", explain_fflush(fp));
00067         fclose(fp);
00068         return false;
00069     }
00070     if (fclose(fp))
00071     {
00072         on_error("%s", explain_fclose(fp));
00073         return false;
00074     }
00075     return true;
00076 }