/*
    This file is part of Page Layout Detection Tools.

    This code is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This code is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this code; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <formats/pbmfact.h>

extern "C"{
#include <pbm.h>
}

namespace pagetools{

PBMFactory::PBMFactory(const char *path)
:path_(path){
}

CntPtr<BWImage> 
PBMFactory::create(){
    FILE *fp=fopen(path_, "rb");
    if(fp){
        int w, h; // CHECKME: 64 bit alignment precludes using unsigned int
        int format;
        pbm_readpbminit(fp, &w, &h, &format);
        unsigned int row;
        CntPtr<BWImage> retval=CntPtr<BWImage>(new BWImage(w, h));
        unsigned char padmask=0xFF<<((w+7)%8);
        unsigned int i_last=retval->bytewidth()-1; // Index of the last byte in a row
        for(row=0; row<h; row++){
            pbm_readpbmrow_packed(fp, retval->scanline(row), w, format);
            retval->scanline(row)[i_last] &= padmask; // Zero padding
        }
        fclose(fp);
        return retval;
    }
    return 0;
}

}//namespace pagetools
